Commit 5d40c7b6 authored by Matthias Betz's avatar Matthias Betz
Browse files

CityDoctor2 validation open source release

parents
/*-
* Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
*
* This file is part of CityDoctor2.
*
* CityDoctor2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CityDoctor2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CityDoctor2. If not, see <https://www.gnu.org/licenses/>.
*/
package de.hft.stuttgart.citydoctor2.reporting;
import java.io.OutputStream;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import de.hft.stuttgart.citydoctor2.CDVMessages;
import de.hft.stuttgart.citydoctor2.check.CheckConfiguration;
import de.hft.stuttgart.citydoctor2.check.CheckError;
import de.hft.stuttgart.citydoctor2.check.CheckId;
import de.hft.stuttgart.citydoctor2.check.ErrorType;
import de.hft.stuttgart.citydoctor2.check.ValidationConfiguration;
import de.hft.stuttgart.citydoctor2.checkresult.CheckReport;
import de.hft.stuttgart.citydoctor2.checkresult.Environment;
import de.hft.stuttgart.citydoctor2.checkresult.ErrorDetails;
import de.hft.stuttgart.citydoctor2.checkresult.ErrorReport;
import de.hft.stuttgart.citydoctor2.checkresult.ErrorStatistic;
import de.hft.stuttgart.citydoctor2.checkresult.ErrorStatus;
import de.hft.stuttgart.citydoctor2.checkresult.Feature;
import de.hft.stuttgart.citydoctor2.checkresult.FeatureReport;
import de.hft.stuttgart.citydoctor2.checkresult.GlobalErrorStatistics;
import de.hft.stuttgart.citydoctor2.checkresult.GlobalStatistics;
import de.hft.stuttgart.citydoctor2.checkresult.Header;
import de.hft.stuttgart.citydoctor2.checkresult.ModelStatistics;
import de.hft.stuttgart.citydoctor2.checkresult.PlanCheck;
import de.hft.stuttgart.citydoctor2.checkresult.PlanParameter;
import de.hft.stuttgart.citydoctor2.checkresult.Statistics;
import de.hft.stuttgart.citydoctor2.checkresult.ValidationPlan;
import de.hft.stuttgart.citydoctor2.checkresult.ValidationResults;
import de.hft.stuttgart.citydoctor2.checkresult.utility.CheckReportWriteException;
import de.hft.stuttgart.citydoctor2.datastructure.BridgeObject;
import de.hft.stuttgart.citydoctor2.datastructure.Building;
import de.hft.stuttgart.citydoctor2.datastructure.BuildingPart;
import de.hft.stuttgart.citydoctor2.datastructure.CityObject;
import de.hft.stuttgart.citydoctor2.datastructure.LandObject;
import de.hft.stuttgart.citydoctor2.datastructure.TransportationObject;
import de.hft.stuttgart.citydoctor2.datastructure.Vegetation;
import de.hft.stuttgart.citydoctor2.datastructure.WaterObject;
/**
* Report for creating a XML report out of a stream of feature results
*
* @author Matthias Betz
*
*/
public class XmlStreamReporter implements StreamReporter {
private static final Logger logger = LogManager.getLogger(XmlStreamReporter.class);
private OutputStream output;
private CheckReport report;
private Map<String, FeatureReport> reportMap;
private ValidationConfiguration config;
public XmlStreamReporter(OutputStream output, String fileName, ValidationConfiguration config) {
this.output = output;
this.config = config;
reportMap = new HashMap<>();
report = new CheckReport();
report.setHeader(createHeader(fileName));
report.setValidationPlan(createValidationPlan());
report.setValidationResults(new ValidationResults());
}
private Header createHeader(String fileName) {
Header header = new Header();
header.setDate(ZonedDateTime.now());
header.setFile(fileName);
Environment env = new Environment();
header.setEnvironment(env);
env.setJavaVersion(System.getProperties().getProperty("java.vm.version"));
env.setJavaVmVendor(System.getProperties().getProperty("java.vm.vendor"));
env.setJavaVmVersion(System.getProperties().getProperty("java.version"));
env.setOsArch(System.getProperties().getProperty("os.arch"));
env.setOsName(System.getProperties().getProperty("os.name"));
env.setValidationVersion(CDVMessages.getString(CDVMessages.VERSION));
return header;
}
private ValidationPlan createValidationPlan() {
ValidationPlan plan = new ValidationPlan();
plan.setNumberOfRoundingPlaces(config.getNumberOfRoundingPlaces());
List<PlanCheck> checkConfigs = new ArrayList<>();
plan.setChecks(checkConfigs);
for (Entry<CheckId, CheckConfiguration> e : config.getChecks().entrySet()) {
PlanCheck checkConfig = new PlanCheck();
checkConfigs.add(checkConfig);
checkConfig.setName(e.getKey().toString());
if (e.getValue().isEnabled()) {
checkConfig.setActivated(true);
Map<String, String> checkParams = e.getValue().getParameters();
if (checkParams != null && !checkParams.isEmpty()) {
List<PlanParameter> parameters = new ArrayList<>();
checkConfig.setParameters(parameters);
for (Entry<String, String> entry : checkParams.entrySet()) {
PlanParameter param = new PlanParameter();
param.setName(entry.getKey());
param.setValue(entry.getValue());
parameters.add(param);
}
}
} else {
checkConfig.setActivated(false);
}
}
plan.setSchematronFile(config.getSchematronFilePath());
return plan;
}
@Override
public void report(CityObject co) {
if (co instanceof Building) {
reportBuilding((Building) co);
} else if (co instanceof Vegetation) {
reportVegetation((Vegetation) co);
} else if (co instanceof TransportationObject) {
reportTrans((TransportationObject) co);
} else if (co instanceof BridgeObject) {
reportBridge((BridgeObject) co);
} else if (co instanceof WaterObject) {
reportWater((WaterObject) co);
} else if (co instanceof LandObject) {
reportLand((LandObject) co);
} else {
throw new IllegalStateException("Not reportable CityObject found: " + co.getClass().getSimpleName());
}
}
@Override
public void reportGlobalError(CheckError err) {
report.getValidationResults().getGlobalErrors().add(createErrorReport(err));
}
private void reportLand(LandObject lo) {
FeatureReport fr = createCityObjectReportNode(lo);
report.getValidationResults().getLandReports().add(fr);
}
private void reportWater(WaterObject wo) {
FeatureReport fr = createCityObjectReportNode(wo);
report.getValidationResults().getWaterReports().add(fr);
}
private void reportBridge(BridgeObject bo) {
FeatureReport fr = createCityObjectReportNode(bo);
report.getValidationResults().getBridgeReports().add(fr);
}
private void reportTrans(TransportationObject to) {
FeatureReport fr = createCityObjectReportNode(to);
report.getValidationResults().getTransportationReports().add(fr);
}
private void reportVegetation(Vegetation v) {
FeatureReport fr = createCityObjectReportNode(v);
report.getValidationResults().getVegetationReports().add(fr);
}
private void reportBuilding(Building co) {
FeatureReport fr = createCityObjectReportNode(co);
for (BuildingPart bp : co.getBuildingParts()) {
reportMap.put(bp.getGmlId().getGmlString(), fr);
}
report.getValidationResults().getBuildingReports().add(fr);
}
private FeatureReport createCityObjectReportNode(CityObject co) {
FeatureReport fr = new FeatureReport();
reportMap.put(co.getGmlId().getGmlString(), fr);
fr.setGmlId(co.getGmlId().getGmlString());
List<CheckError> errors = new ArrayList<>();
co.collectContainedErrors(errors);
// Filter out duplicate errors (from linked polygons)
Set<CheckError> errorSet = new HashSet<>(errors);
for (CheckError err : errorSet) {
ErrorReport errReport = createErrorReport(err);
fr.getErrors().add(errReport);
}
return fr;
}
private ErrorReport createErrorReport(CheckError err) {
ErrorReport errReport = new ErrorReport();
errReport.setId(err.getErrorId().toString());
if (err.getType() == ErrorType.WARNING) {
errReport.setStatus(ErrorStatus.WARNING);
} else if (err.getType() == ErrorType.ERROR) {
errReport.setStatus(ErrorStatus.ERROR);
} else {
throw new IllegalStateException("Unknown error type: " + err.getType());
}
if (err.getFeature() != null) {
Feature feature = new Feature();
feature.setGmlId(err.getFeature().getGmlId().getGmlString());
feature.setType(err.getFeature().getCheckClass().getSimpleName());
errReport.setFeature(feature);
}
XmlStreamErrorHandler handler = new XmlStreamErrorHandler(config.getParserConfiguration());
err.report(handler);
ErrorDetails details = handler.getDetails();
errReport.setErrorDetails(details);
return errReport;
}
@Override
public void finishReport() throws CheckReportWriteException {
GlobalStatistics stats = new GlobalStatistics();
GlobalErrorStatistics globErrStats = new GlobalErrorStatistics();
globErrStats
.setNumErrorBridgeObjects(getNumberOfErrorFeatures(report.getValidationResults().getBridgeReports()));
globErrStats.setNumErrorBuildings(getNumberOfErrorFeatures(report.getValidationResults().getBuildingReports()));
globErrStats.setNumErrorLandObjects(getNumberOfErrorFeatures(report.getValidationResults().getLandReports()));
globErrStats.setNumErrorTransportation(
getNumberOfErrorFeatures(report.getValidationResults().getTransportationReports()));
globErrStats
.setNumErrorVegetation(getNumberOfErrorFeatures(report.getValidationResults().getVegetationReports()));
globErrStats.setNumErrorWaterObjects(getNumberOfErrorFeatures(report.getValidationResults().getWaterReports()));
stats.setGlobalErrorStats(globErrStats);
ModelStatistics modelStats = new ModelStatistics();
modelStats.setNumBridgeObjects(report.getValidationResults().getBridgeReports().size());
modelStats.setNumBuildings(report.getValidationResults().getBuildingReports().size());
modelStats.setNumLandObjects(report.getValidationResults().getLandReports().size());
modelStats.setNumTransportation(report.getValidationResults().getTransportationReports().size());
modelStats.setNumVegetation(report.getValidationResults().getVegetationReports().size());
modelStats.setNumWaterObjects(report.getValidationResults().getWaterReports().size());
stats.setModelStats(modelStats);
ErrorStatisticsCollector globalErrorCount = new ErrorStatisticsCollector();
for (ErrorReport errReport : report.getValidationResults().getGlobalErrors()) {
globalErrorCount.addError(errReport.getId());
}
createStatistics(globalErrorCount, report.getValidationResults().getBridgeReports());
createStatistics(globalErrorCount, report.getValidationResults().getBuildingReports());
createStatistics(globalErrorCount, report.getValidationResults().getLandReports());
createStatistics(globalErrorCount, report.getValidationResults().getTransportationReports());
createStatistics(globalErrorCount, report.getValidationResults().getVegetationReports());
createStatistics(globalErrorCount, report.getValidationResults().getWaterReports());
addStatisticsObjects(stats.getErrorStats(), globalErrorCount);
report.setGlobalStatistics(stats);
report.saveAs(output);
}
private void createStatistics(ErrorStatisticsCollector globalErrorCount, List<FeatureReport> reports) {
for (FeatureReport fReport : reports) {
if (fReport.getErrors().isEmpty()) {
fReport.setErrors(null);
continue;
}
ErrorStatisticsCollector collector = new ErrorStatisticsCollector();
for (ErrorReport errReport : fReport.getErrors()) {
collector.addError(errReport.getId());
globalErrorCount.addError(errReport.getId());
}
Statistics reportStats = new Statistics();
addStatisticsObjects(reportStats.getErrorStats(), collector);
fReport.setStatistics(reportStats);
}
}
private void addStatisticsObjects(List<ErrorStatistic> stats, ErrorStatisticsCollector collector) {
for (Entry<String, AtomicInteger> er : collector.getErrorCounts().entrySet()) {
if (er.getValue().get() > 0) {
ErrorStatistic errStats = new ErrorStatistic();
errStats.setName(er.getKey());
errStats.setCount(er.getValue().get());
stats.add(errStats);
}
}
}
private int getNumberOfErrorFeatures(List<FeatureReport> reports) {
int errorFeatures = 0;
for (FeatureReport fReport : reports) {
boolean hasError = hasError(fReport);
if (hasError) {
errorFeatures++;
}
}
return errorFeatures;
}
private boolean hasError(FeatureReport fReport) {
return !fReport.getErrors().isEmpty();
}
@Override
public void addError(String gmlId, CheckError err) {
FeatureReport fReport = reportMap.get(gmlId);
if (fReport == null) {
logger.warn("Error reported for unknown gml id: {}, adding to global errors instead", gmlId);
reportGlobalError(err);
} else {
fReport.getErrors().add(createErrorReport(err));
}
}
}
/*-
* Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
*
* This file is part of CityDoctor2.
*
* CityDoctor2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CityDoctor2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CityDoctor2. If not, see <https://www.gnu.org/licenses/>.
*/
package de.hft.stuttgart.citydoctor2.reporting;
import java.io.OutputStream;
import de.hft.stuttgart.citydoctor2.check.CheckError;
import de.hft.stuttgart.citydoctor2.check.ValidationConfiguration;
import de.hft.stuttgart.citydoctor2.checkresult.utility.CheckReportWriteException;
import de.hft.stuttgart.citydoctor2.checks.Checks;
import de.hft.stuttgart.citydoctor2.datastructure.BridgeObject;
import de.hft.stuttgart.citydoctor2.datastructure.Building;
import de.hft.stuttgart.citydoctor2.datastructure.CityDoctorModel;
import de.hft.stuttgart.citydoctor2.datastructure.LandObject;
import de.hft.stuttgart.citydoctor2.datastructure.TransportationObject;
import de.hft.stuttgart.citydoctor2.datastructure.Vegetation;
import de.hft.stuttgart.citydoctor2.datastructure.WaterObject;
/**
*
* @author Matthias Betz
*
*/
public class XmlValidationReporter implements Reporter {
@Override
public void writeReport(Checks checks, OutputStream filePath, CityDoctorModel model, ValidationConfiguration config) throws CheckReportWriteException {
StreamReporter streamReporter = new XmlStreamReporter(filePath, model.getFileName(), config);
for (BridgeObject bo : model.getBridges()) {
streamReporter.report(bo);
}
for (Building b : model.getBuildings()) {
streamReporter.report(b);
}
for (TransportationObject to : model.getTransportation()) {
streamReporter.report(to);
}
for (LandObject lo : model.getLand()) {
streamReporter.report(lo);
}
for (Vegetation v : model.getVegetation()) {
streamReporter.report(v);
}
for (WaterObject wo : model.getWater()) {
streamReporter.report(wo);
}
for (CheckError err : model.getGlobalErrors()) {
streamReporter.reportGlobalError(err);
}
streamReporter.finishReport();
}
}
/*-
* Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
*
* This file is part of CityDoctor2.
*
* CityDoctor2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CityDoctor2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CityDoctor2. If not, see <https://www.gnu.org/licenses/>.
*/
package de.hft.stuttgart.citydoctor2.reporting.pdf;
import org.jdom2.Element;
/**
* Insert a code block into the PDF report. It will have a border and the
* content has a different font. Supports colored test elements.
*
* @author Matthias Betz
*
*/
public class CodeBlock {
private static final String BLOCK = "block";
private Element codeBlockContainer;
private Element codeBlockElement;
private Element currentLine;
public CodeBlock() {
codeBlockContainer = new Element("block-container", PdfReport.FO_NS);
codeBlockContainer.setAttribute("width", "97%");
codeBlockContainer.setAttribute("margin-left", "9");
codeBlockContainer.setAttribute("margin-bottom", "5px");
codeBlockElement = new Element(BLOCK, PdfReport.FO_NS);
codeBlockElement.setAttribute("padding-after", "10");
codeBlockElement.setAttribute("font-family", "Courier");
codeBlockElement.setAttribute("font-size", "10pt");
codeBlockElement.setAttribute("border-style", "solid");
codeBlockElement.setAttribute("padding", "5px");
codeBlockContainer.addContent(codeBlockElement);
currentLine = new Element(BLOCK, PdfReport.FO_NS);
codeBlockElement.addContent(currentLine);
}
/**
* Adds a text with the specified color to the block
*
* @param text the text that is added
* @param color the color of the text in HTML code, e.g. #ffffff
*/
public void addText(String text, String color) {
Element inline = new Element("inline", PdfReport.FO_NS);
currentLine.addContent(inline);
inline.addContent(text);
inline.setAttribute("color", color);
}
/**
* Adds a black colored text to the block.
*
* @param text the text that is added
*/
public void addText(String text) {
currentLine.addContent(text);
}
/**
* Create a new line in the block. The page can break after this.
*/
public void newLine() {
newLine(0);
}
/**
* Add a new line with a distance from the left border for the next line.
*
* @param marginLeft the distance from the left in pixel
*/
public void newLine(int marginLeft) {
currentLine = new Element(BLOCK, PdfReport.FO_NS);
codeBlockElement.addContent(currentLine);
if (marginLeft != 0) {
currentLine.setAttribute("margin-left", "" + marginLeft);
}
}
Element getCodeBlock() {
return codeBlockContainer;
}
}
/*-
* Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
*
* This file is part of CityDoctor2.
*
* CityDoctor2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CityDoctor2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CityDoctor2. If not, see <https://www.gnu.org/licenses/>.
*/
package de.hft.stuttgart.citydoctor2.reporting.pdf;
import java.util.Collection;
import org.osgeo.proj4j.ProjCoordinate;
import de.hft.stuttgart.citydoctor2.check.ErrorReport;
import de.hft.stuttgart.citydoctor2.datastructure.BoundarySurface;
import de.hft.stuttgart.citydoctor2.datastructure.Edge;
import de.hft.stuttgart.citydoctor2.datastructure.Geometry;
import de.hft.stuttgart.citydoctor2.datastructure.GmlElement;
import de.hft.stuttgart.citydoctor2.datastructure.LinearRing;
import de.hft.stuttgart.citydoctor2.datastructure.Polygon;
import de.hft.stuttgart.citydoctor2.datastructure.Vertex;
import de.hft.stuttgart.citydoctor2.math.Vector3d;
import de.hft.stuttgart.citydoctor2.parser.ParserConfiguration;
/**
* Handler for the information given by the errors. The information is formatted
* and written out in the PDF report. Most information is formatted into code
* blocks with a border for more overview.
*
* @author Matthias Betz
*
*/
public class PdfErrorHandler implements ErrorReport {
private static final String VERTEX_FORMAT = "%f %f %f";
private static final String TAG_COLOR = "#3F7F7F";
private static final String ATTRIBUTE_KEY_COLOR = "#7F007F";
private static final String ATTRIBUTE_VALUE_COLOR = "#2A00FF";
private Section section;
private ParserConfiguration config;
public PdfErrorHandler(Section section, ParserConfiguration config) {
this.config = config;
this.section = section;
}
@Override
public void add(Polygon p) {
CodeBlock block = new CodeBlock();
section.addCodeBlock(block);
block.addText("<Polygon", TAG_COLOR);
addGmlId(p, block);
block.addText(">", TAG_COLOR);
block.newLine(10);
block.addText("<Exterior Ring", TAG_COLOR);
addGmlId(p.getExteriorRing(), block);
block.addText(">", TAG_COLOR);
for (Vertex v : p.getExteriorRing().getVertices()) {
block.newLine(20);
addVertexToBlock(block, v);
}
block.newLine(10);
block.addText("</Exterior Ring>", TAG_COLOR);
if (p.getInnerRings().isEmpty()) {
return;
}
block.newLine(10);
block.addText("<Interior Rings>", TAG_COLOR);
for (LinearRing ring : p.getInnerRings()) {
block.newLine(20);
block.addText("<Interior Ring", TAG_COLOR);
addGmlId(ring, block);
block.addText(">", TAG_COLOR);
for (Vertex v : p.getExteriorRing().getVertices()) {
block.newLine(30);
addVertexToBlock(block, v);
}
block.newLine(20);
block.addText("</Interior Ring>", TAG_COLOR);
}
block.newLine(10);
block.addText("</Interior Rings>", TAG_COLOR);
}
private void addVertexToBlock(CodeBlock block, Vertex v) {
double x = v.getX();
double y = v.getY();
double z = v.getZ();
if (config.getOriginalTransform() != null) {
ProjCoordinate p1 = new ProjCoordinate();
ProjCoordinate p2 = new ProjCoordinate();
p1.x = v.getX();
p1.y = v.getY();
config.getOriginalTransform().transform(p1, p2);
x = p2.x;
y = p2.y;
}
block.addText(String.format(VERTEX_FORMAT, x, y, z));
}
private void addGmlId(GmlElement e, CodeBlock block) {
if (!e.getGmlId().isGenerated()) {
block.addText(" gml:id", ATTRIBUTE_KEY_COLOR);
block.addText("=");
block.addText(e.getGmlId().getGmlString(), ATTRIBUTE_VALUE_COLOR);
}
}
@Override
public void add(LinearRing lr) {
CodeBlock block = new CodeBlock();
section.addCodeBlock(block);
block.addText("<LinearRing", TAG_COLOR);
addGmlId(lr, block);
block.addText(" type", ATTRIBUTE_KEY_COLOR);
block.addText("=");
block.addText(lr.getType().toString(), ATTRIBUTE_VALUE_COLOR);
block.addText(">", TAG_COLOR);
for (Vertex v : lr.getVertices()) {
block.newLine(10);
addVertexToBlock(block, v);
}
block.newLine();
block.addText("</LinearRing>", TAG_COLOR);
}
@Override
public void add(Geometry geom) {
CodeBlock block = new CodeBlock();
section.addCodeBlock(block);
block.addText("<Geometry", TAG_COLOR);
addGmlId(geom, block);
block.addText(" type", ATTRIBUTE_KEY_COLOR);
block.addText("=");
block.addText(geom.getType().toString(), ATTRIBUTE_VALUE_COLOR);
block.addText(" lod", ATTRIBUTE_KEY_COLOR);
block.addText("=");
block.addText(geom.getLod().toString(), ATTRIBUTE_VALUE_COLOR);
block.addText(">", TAG_COLOR);
for (Polygon p : geom.getPolygons()) {
block.newLine(10);
block.addText("<Polygon", TAG_COLOR);
block.addText(" gml:id", ATTRIBUTE_KEY_COLOR);
block.addText("=");
block.addText(p.getGmlId().getGmlString(), ATTRIBUTE_VALUE_COLOR);
block.addText(">", TAG_COLOR);
}
block.newLine();
block.addText("</Geometry>", TAG_COLOR);
}
@Override
public void add(Vertex v) {
addVector(v);
}
private void addVector(Vector3d v) {
CodeBlock block = new CodeBlock();
section.addCodeBlock(block);
block.addText("<Vertex>", TAG_COLOR);
block.addText(String.format(VERTEX_FORMAT, v.getX(), v.getY(), v.getZ()));
block.addText("</Vertex>", TAG_COLOR);
}
@Override
public void add(String name, Vertex v) {
section.add10PtTextElement(name, 5);
add(v);
}
@Override
public void add(Edge e) {
CodeBlock block = new CodeBlock();
section.addCodeBlock(block);
addEdgeToBlock(e, block);
}
private void addEdgeToBlock(Edge e, CodeBlock block) {
block.addText("<Edge>", TAG_COLOR);
block.newLine(10);
block.addText("<From>", TAG_COLOR);
block.addText(String.format(VERTEX_FORMAT, e.getFrom().getX(), e.getFrom().getY(), e.getFrom().getZ()));
block.addText("</From>", TAG_COLOR);
block.newLine(10);
block.addText("<To>", TAG_COLOR);
block.addText(String.format(VERTEX_FORMAT, e.getTo().getX(), e.getTo().getY(), e.getTo().getZ()));
block.addText("</To>", TAG_COLOR);
block.newLine();
block.addText("</Edge>", TAG_COLOR);
block.newLine();
}
@Override
public void add(BoundarySurface bs) {
section.add10PtTextElement("In BoundarySurface " + bs.getType().toString() + " id=" + bs.getGmlId(), 5);
}
@Override
public void add(String name, Edge e) {
section.add10PtTextElement(name, 5);
add(e);
}
@Override
public void add(String name, int value) {
add(name, "" + value);
}
@Override
public void add(String name, double value) {
add(name, "" + value);
}
@Override
public void add(String name, String value) {
section.add10PtTextElement(String.join(": ", name, value), 5);
}
@Override
public void add(String name, Vector3d point) {
section.add10PtTextElement(name, 5);
addVector(point);
}
@Override
public void addPolygons(String name, Collection<Polygon> polygons) {
section.add10PtTextElement(name, 5);
for (Polygon p : polygons) {
section.add10PtTextElement(p.getGmlId().getGmlString(), 10);
}
}
@Override
public void addEdges(String name, Collection<Edge> edges) {
section.add10PtTextElement(name, 5);
CodeBlock block = new CodeBlock();
section.addCodeBlock(block);
for (Edge e : edges) {
addEdgeToBlock(e, block);
}
}
}
/*-
* Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
*
* This file is part of CityDoctor2.
*
* CityDoctor2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CityDoctor2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CityDoctor2. If not, see <https://www.gnu.org/licenses/>.
*/
package de.hft.stuttgart.citydoctor2.reporting.pdf;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import javax.xml.XMLConstants;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXResult;
import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.xmlgraphics.util.MimeConstants;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.output.DOMOutputter;
import de.hft.stuttgart.citydoctor2.checkresult.utility.CheckReportWriteException;
/**
*
* @author Matthias Betz
*
*/
public class PdfReport {
private static final String FRONT_PAGE = "front-page";
private static final String REGION_BODY = "region-body";
private static final String MASTER_NAME = "master-name";
private static final String SIMPLE_PAGE_MASTER = "simple-page-master";
private static final String MARGIN_BOTTOM = "margin-bottom";
private static final String FONT_SIZE = "font-size";
private static final String CENTER = "center";
private static final String XSL_REGION_BODY = "xsl-region-body";
private static final String TEXT_ALIGN = "text-align";
private static final String BLOCK = "block";
private static final String FLOW_NAME = "flow-name";
private static final String MASTER_REFERENCE = "master-reference";
private static final String PAGE_SEQUENCE = "page-sequence";
private static final FopFactory FOP_FACTORY;
private static final String HEADLINE_FONT_SIZE = "24pt";
private static final String SUB_HEADLINE_FONT_SIZE = "18pt";
static final Namespace FO_NS = Namespace.getNamespace("fo", "http://www.w3.org/1999/XSL/Format");
static final Namespace SVG_NS = Namespace.getNamespace("svg", "http://www.w3.org/2000/svg");
private static final String COPY_RIGHT = "Copyright (c) 2020 HFT Stuttgart. All rights reserved."
+ " HFT Stuttgart and its licensors retain all intellectual property"
+ " and proprietary rights in and to this software and related documentation."
+ " Any use, reproduction, disclosure, or distribution of this software and"
+ " related documentation without an express license agreement from HFT Stuttgart is strictly prohibited.";
private Document doc;
private Element fileElement;
private Element tocFlow;
private Element pageFlow;
private Element headerBlock;
private List<Section> sections;
static {
URI uri = new File(".").toURI();
FOP_FACTORY = FopFactory.newInstance(uri);
}
public PdfReport(String logoPath) {
doc = new Document();
sections = new ArrayList<>();
Element root = new Element("root", FO_NS);
doc.setRootElement(root);
root.addNamespaceDeclaration(FO_NS);
createLayout(root);
writeFrontPage(root, logoPath);
writeTableOfContent(root);
createHeaderAndFooter(root);
}
public void writeSourceFileName(String sourceFile) {
sourceFile = split(sourceFile, 35);
fileElement.addContent("For File: " + sourceFile);
headerBlock.addContent(sourceFile);
}
/**
* Split string in multiple lines
*
* @param s the string to be split
* @param size the number of characters per line
* @return the split string concatenated with \n
*/
private String split(String s, int size) {
if (s.length() <= 35) {
return s;
}
StringJoiner joiner = new StringJoiner("\n");
for (int start = 0; start < s.length(); start += size) {
joiner.add(s.substring(start, Math.min(s.length(), start + size)));
}
return joiner.toString();
}
public Section createSection(String headline) {
return createSection(headline, false);
}
public Section createSection(String headline, boolean newPage) {
Section s = new Section(headline, 0, newPage);
sections.add(s);
pageFlow.addContent(s.getContentBlock());
return s;
}
public void save(OutputStream outFile) throws CheckReportWriteException {
// finish writing the table of content, 3 layers
for (Section s : sections) {
tocFlow.addContent(s.getTocBlock());
for (Section ss : s.getSubSections()) {
tocFlow.addContent(ss.getTocBlock());
for (Section sss : ss.getSubSections()) {
tocFlow.addContent(sss.getTocBlock());
}
}
}
try {
FOUserAgent userAgent = FOP_FACTORY.newFOUserAgent();
Fop fop = FOP_FACTORY.newFop(MimeConstants.MIME_PDF, userAgent, outFile);
TransformerFactory factory = TransformerFactory.newInstance();
// deactivate external dtds because of security issues
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
// identity transformer
Transformer transformer = factory.newTransformer();
DOMOutputter domOutputter = new DOMOutputter();
Source src = new DOMSource(domOutputter.output(doc));
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(src, res);
outFile.flush();
} catch (FOPException | JDOMException | TransformerException | IOException e) {
throw new CheckReportWriteException(e);
}
}
private void createHeaderAndFooter(Element root) {
Element pageSequence = new Element(PAGE_SEQUENCE, FO_NS);
root.addContent(pageSequence);
pageSequence.setAttribute("initial-page-number", "1");
pageSequence.setAttribute(MASTER_REFERENCE, "content");
Element headerContent = new Element("static-content", FO_NS);
pageSequence.addContent(headerContent);
headerContent.setAttribute(FLOW_NAME, "header");
headerBlock = new Element(BLOCK, FO_NS);
applyFont(headerBlock);
headerBlock.setAttribute(FONT_SIZE, "8pt");
headerBlock.setAttribute("text-align-last", "justify");
Element inlineHeader = new Element("inline", FO_NS);
inlineHeader.addContent("Check Report");
headerBlock.addContent(inlineHeader);
headerBlock.addContent(new Element("leader", FO_NS));
headerContent.addContent(headerBlock);
Element footerContent = new Element("static-content", FO_NS);
pageSequence.addContent(footerContent);
footerContent.setAttribute(FLOW_NAME, "footer");
Element pageNumberBlock = new Element(BLOCK, FO_NS);
footerContent.addContent(pageNumberBlock);
pageNumberBlock.setAttribute(TEXT_ALIGN, "end");
pageNumberBlock.addContent(new Element("page-number", FO_NS));
pageFlow = new Element("flow", FO_NS);
pageFlow.setAttribute(FLOW_NAME, XSL_REGION_BODY);
pageSequence.addContent(pageFlow);
}
private void writeTableOfContent(Element root) {
Element pageSequence = new Element(PAGE_SEQUENCE, FO_NS);
root.addContent(pageSequence);
pageSequence.setAttribute(MASTER_REFERENCE, "toc");
tocFlow = new Element("flow", FO_NS);
pageSequence.addContent(tocFlow);
tocFlow.setAttribute(FLOW_NAME, XSL_REGION_BODY);
Element title = new Element(BLOCK, FO_NS);
tocFlow.addContent(title);
applyHeadlineAttributes(title);
title.addContent("Table of Contents");
}
private void writeFrontPage(Element root, String logoPath) {
Element pageSequence = new Element(PAGE_SEQUENCE, FO_NS);
root.addContent(pageSequence);
pageSequence.setAttribute(MASTER_REFERENCE, FRONT_PAGE);
Element frontPageFlow = new Element("flow", FO_NS);
pageSequence.addContent(frontPageFlow);
frontPageFlow.setAttribute(FLOW_NAME, XSL_REGION_BODY);
Element title = new Element(BLOCK, FO_NS);
frontPageFlow.addContent(title);
title.setAttribute(TEXT_ALIGN, CENTER);
applyFont(title);
title.setAttribute(FONT_SIZE, "34pt");
title.setAttribute("font-weight", "bold");
title.addContent("Check Report");
Element blockPicture = new Element(BLOCK, FO_NS);
frontPageFlow.addContent(blockPicture);
blockPicture.setAttribute(TEXT_ALIGN, CENTER);
Element externalPicture = new Element("external-graphic", FO_NS);
blockPicture.addContent(externalPicture);
externalPicture.setAttribute("src", logoPath);
fileElement = new Element(BLOCK, FO_NS);
frontPageFlow.addContent(fileElement);
fileElement.setAttribute(TEXT_ALIGN, CENTER);
applyFont(fileElement);
fileElement.setAttribute(FONT_SIZE, "24pt");
String date = ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME);
Element createdOn = new Element(BLOCK, FO_NS);
frontPageFlow.addContent(createdOn);
createdOn.setAttribute(TEXT_ALIGN, CENTER);
createdOn.setAttribute("space-before", "10mm");
applyFont(createdOn);
createdOn.addContent("Created on " + date);
Element copyRightText = createTextElement(COPY_RIGHT);
frontPageFlow.addContent(copyRightText);
copyRightText.setAttribute("space-before", "100mm");
copyRightText.setAttribute(FONT_SIZE, "8pt");
}
static void applyHeadlineAttributes(Element headline) {
applyFont(headline);
headline.setAttribute(FONT_SIZE, HEADLINE_FONT_SIZE);
headline.setAttribute("font-weight", "bold");
headline.setAttribute("margin-top", "10mm");
headline.setAttribute(MARGIN_BOTTOM, "10mm");
}
static void applySubHeadlineAttributes(Element subHeadline) {
applyFont(subHeadline);
subHeadline.setAttribute(FONT_SIZE, SUB_HEADLINE_FONT_SIZE);
subHeadline.setAttribute(MARGIN_BOTTOM, "10mm");
}
static void applySubSubHeadlineAttributes(Element h) {
applyFont(h);
h.setAttribute(FONT_SIZE, "14pt");
h.setAttribute(MARGIN_BOTTOM, "5mm");
}
static void applyFont(Element e) {
e.setAttribute("font-family", "Helvetica");
}
static void applySolidBorder(Element e) {
e.setAttribute("border-style", "solid");
e.setAttribute("border-width", "1pt");
}
private void createLayout(Element root) {
Element layoutMaster = new Element("layout-master-set", FO_NS);
root.addContent(layoutMaster);
Element firstPageMaster = new Element(SIMPLE_PAGE_MASTER, FO_NS);
layoutMaster.addContent(firstPageMaster);
firstPageMaster.setAttribute(MASTER_NAME, FRONT_PAGE);
applyPageSize(firstPageMaster);
Element firstPageRegionBody = new Element(REGION_BODY, FO_NS);
firstPageMaster.addContent(firstPageRegionBody);
Element tableOfContentLayout = new Element(SIMPLE_PAGE_MASTER, FO_NS);
layoutMaster.addContent(tableOfContentLayout);
tableOfContentLayout.setAttribute(MASTER_NAME, "toc");
applyPageSize(tableOfContentLayout);
Element tocRegionBody = new Element(REGION_BODY, FO_NS);
tableOfContentLayout.addContent(tocRegionBody);
Element contentLayout = new Element(SIMPLE_PAGE_MASTER, FO_NS);
layoutMaster.addContent(contentLayout);
contentLayout.setAttribute(MASTER_NAME, "content");
applyPageSize(contentLayout);
Element contentRegionBody = new Element(REGION_BODY, FO_NS);
contentRegionBody.setAttribute("margin", "5mm");
contentLayout.addContent(contentRegionBody);
Element contentRegionBefore = new Element("region-before", FO_NS);
contentLayout.addContent(contentRegionBefore);
contentRegionBefore.setAttribute("region-name", "header");
contentRegionBefore.setAttribute("extent", "10mm");
Element contentRegionAfter = new Element("region-after", FO_NS);
contentLayout.addContent(contentRegionAfter);
contentRegionAfter.setAttribute("region-name", "footer");
contentRegionAfter.setAttribute("extent", "10mm");
contentRegionAfter.setAttribute("display-align", "after");
}
static Element createTextElement(String text) {
Element textElement = new Element(BLOCK, FO_NS);
textElement.setAttribute("space-after", "6pt");
applyFont(textElement);
textElement.addContent(text);
return textElement;
}
private void applyPageSize(Element pageMaster) {
pageMaster.setAttribute("margin-left", "15mm");
pageMaster.setAttribute("margin-right", "15mm");
pageMaster.setAttribute("margin-top", "10mm");
pageMaster.setAttribute(MARGIN_BOTTOM, "10mm");
pageMaster.setAttribute("page-height", "297mm");
pageMaster.setAttribute("page-width", "210mm");
}
}
/*-
* Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
*
* This file is part of CityDoctor2.
*
* CityDoctor2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CityDoctor2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CityDoctor2. If not, see <https://www.gnu.org/licenses/>.
*/
package de.hft.stuttgart.citydoctor2.reporting.pdf;
import java.io.OutputStream;
import java.util.Objects;
import de.hft.stuttgart.citydoctor2.check.ValidationConfiguration;
import de.hft.stuttgart.citydoctor2.checkresult.utility.CheckReportWriteException;
import de.hft.stuttgart.citydoctor2.checks.Checks;
import de.hft.stuttgart.citydoctor2.datastructure.CityDoctorModel;
import de.hft.stuttgart.citydoctor2.reporting.Reporter;
/**
* Reporter to write a PDF report from a complete model
*
* @author Matthias Betz
*
*/
public class PdfReporter implements Reporter {
private String logoPath;
public PdfReporter(String logoPath) {
Objects.requireNonNull(logoPath);
this.logoPath = logoPath;
}
@Override
public void writeReport(Checks checks, OutputStream outFile, CityDoctorModel model, ValidationConfiguration config)
throws CheckReportWriteException {
PdfStreamReporter reporter = new PdfStreamReporter(outFile, model.getFileName(), config, logoPath);
model.createFeatureStream().forEach(reporter::report);
reporter.finishReport();
}
}
/*-
* Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
*
* This file is part of CityDoctor2.
*
* CityDoctor2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CityDoctor2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CityDoctor2. If not, see <https://www.gnu.org/licenses/>.
*/
package de.hft.stuttgart.citydoctor2.reporting.pdf;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import de.hft.stuttgart.citydoctor2.CDVMessages;
import de.hft.stuttgart.citydoctor2.check.CheckConfiguration;
import de.hft.stuttgart.citydoctor2.check.CheckError;
import de.hft.stuttgart.citydoctor2.check.CheckId;
import de.hft.stuttgart.citydoctor2.check.CheckResult;
import de.hft.stuttgart.citydoctor2.check.ErrorId;
import de.hft.stuttgart.citydoctor2.check.ResultStatus;
import de.hft.stuttgart.citydoctor2.check.ValidationConfiguration;
import de.hft.stuttgart.citydoctor2.check.error.SchematronError;
import de.hft.stuttgart.citydoctor2.checkresult.utility.CheckReportWriteException;
import de.hft.stuttgart.citydoctor2.datastructure.BoundarySurface;
import de.hft.stuttgart.citydoctor2.datastructure.BridgeObject;
import de.hft.stuttgart.citydoctor2.datastructure.Building;
import de.hft.stuttgart.citydoctor2.datastructure.BuildingPart;
import de.hft.stuttgart.citydoctor2.datastructure.CityObject;
import de.hft.stuttgart.citydoctor2.datastructure.Geometry;
import de.hft.stuttgart.citydoctor2.datastructure.LandObject;
import de.hft.stuttgart.citydoctor2.datastructure.LinearRing;
import de.hft.stuttgart.citydoctor2.datastructure.Opening;
import de.hft.stuttgart.citydoctor2.datastructure.Polygon;
import de.hft.stuttgart.citydoctor2.datastructure.TransportationObject;
import de.hft.stuttgart.citydoctor2.datastructure.Vegetation;
import de.hft.stuttgart.citydoctor2.datastructure.WaterObject;
import de.hft.stuttgart.citydoctor2.reporting.StreamReporter;
/**
* Reporter to create a PDF report out of a stream of feature results
*
* @author Matthias Betz
*
*/
public class PdfStreamReporter implements StreamReporter {
private static final Logger logger = LogManager.getLogger(PdfStreamReporter.class);
private static final String ERROR_COLOR = "red";
@SuppressWarnings("unused")
private static final String WARNING_COLOR = "yellow";
private static final String OK_COLOR = "green";
private PdfReport report;
private OutputStream outFile;
private Map<ErrorId, AtomicInteger> errorStatistics;
private ValidationConfiguration config;
private Section statistics;
private Section vr;
private Section buildings;
private int numErrorBuildings;
private int numOkBuildings;
private Section vegetation;
private int numErrorVegetation;
private int numOkVegetation;
private Section trans;
private int numErrorTrans;
private int numOkTrans;
private Section bridge;
private int numErrorBridge;
private int numOkBridge;
private Section water;
private int numErrorWater;
private int numOkWater;
private Section land;
private int numErrorLand;
private int numOkLand;
private Section globalErrors;
private Map<String, Section> sectionMap = new HashMap<>();
public PdfStreamReporter(OutputStream pdfOutputFile, String fileName, ValidationConfiguration config,
String logoPath) {
this.config = config;
errorStatistics = new EnumMap<>(ErrorId.class);
outFile = pdfOutputFile;
report = new PdfReport(logoPath);
report.writeSourceFileName(fileName);
writeEnvironment();
statistics = report.createSection("Statistics", true);
statistics.addTextElement("Object distribution:");
writeValidationPlan();
vr = report.createSection("Validation Results", true);
}
private void writeValidationPlan() {
Section vp = report.createSection("Validation Plan", true);
vp.addTextElement("numberOfRoundingPlaces = " + config.getNumberOfRoundingPlaces());
if (config.getSchematronFilePath() != null && !config.getSchematronFilePath().isEmpty()) {
vp.addTextElement("Schematron file: " + config.getSchematronFilePath());
}
for (Entry<CheckId, CheckConfiguration> e : config.getChecks().entrySet()) {
String text = e.getKey().toString();
String color;
if (e.getValue().isEnabled()) {
text = text + " = enabled";
color = OK_COLOR;
} else {
text = text + " = disabled";
color = ERROR_COLOR;
}
vp.addTextElement(text, color);
for (Entry<String, String> parameter : e.getValue().getParameters().entrySet()) {
vp.add10PtTextElement(parameter.getKey() + " = " + parameter.getValue(), 10);
}
}
}
private void writeEnvironment() {
Section env = report.createSection("Environment");
env.addTextElement("The checks were executed under the following environment:");
Table t = new Table(2);
t.setTitle("Name", "Value");
t.addRow("City Doctor Version", CDVMessages.getString(CDVMessages.VERSION));
t.addRow("Java VM-Version", System.getProperties().getProperty("java.vm.version"));
t.addRow("Java VM-Vendor", System.getProperties().getProperty("java.vm.vendor"));
t.addRow("Java Version", System.getProperties().getProperty("java.version"));
t.addRow("OS Name", System.getProperties().getProperty("os.name"));
t.addRow("OS Architecture", System.getProperties().getProperty("os.arch"));
env.addTable(t);
}
@Override
public void report(CityObject co) {
List<CheckError> errorList = new ArrayList<>();
co.collectContainedErrors(errorList);
Set<CheckError> errors = new HashSet<>(errorList);
for (CheckError e : errors) {
AtomicInteger errorCount = errorStatistics.computeIfAbsent(e.getErrorId(), k -> new AtomicInteger(0));
errorCount.incrementAndGet();
}
boolean hasError = containsError(co);
if (co instanceof Building) {
reportBuilding(co, hasError);
} else if (co instanceof Vegetation) {
reportVegetation(co, hasError);
} else if (co instanceof TransportationObject) {
reportTrans(co, hasError);
} else if (co instanceof BridgeObject) {
reportBridge(co, hasError);
} else if (co instanceof WaterObject) {
reportWater(co, hasError);
} else if (co instanceof LandObject) {
reportLand(co, hasError);
} else {
throw new IllegalStateException("Unknown City Object found: " + co.getClass());
}
}
private void reportLand(CityObject co, boolean hasError) {
if (land == null) {
land = vr.createSubSection("Land Objects");
}
Section lSection = land.createSubSection(co.getGmlId().getGmlString());
sectionMap.put(co.getGmlId().getGmlString(), lSection);
if (hasError) {
numErrorLand++;
lSection.setHeadlineColor(ERROR_COLOR);
} else {
numOkLand++;
lSection.setHeadlineColor(OK_COLOR);
}
writeErrorForCityObject(co, lSection);
}
private void reportWater(CityObject co, boolean hasError) {
if (water == null) {
water = vr.createSubSection("Water Objects");
}
Section wSection = water.createSubSection(co.getGmlId().getGmlString());
sectionMap.put(co.getGmlId().getGmlString(), wSection);
if (hasError) {
numErrorWater++;
wSection.setHeadlineColor(ERROR_COLOR);
} else {
numOkWater++;
wSection.setHeadlineColor(OK_COLOR);
}
writeErrorForCityObject(co, wSection);
}
private void reportBridge(CityObject co, boolean hasError) {
if (bridge == null) {
bridge = vr.createSubSection("Bridge Objects");
}
Section bSection = bridge.createSubSection(co.getGmlId().getGmlString());
sectionMap.put(co.getGmlId().getGmlString(), bSection);
if (hasError) {
numErrorBridge++;
bSection.setHeadlineColor(ERROR_COLOR);
} else {
numOkBridge++;
bSection.setHeadlineColor(OK_COLOR);
}
writeErrorForCityObject(co, bSection);
}
private void reportTrans(CityObject co, boolean hasError) {
if (trans == null) {
trans = vr.createSubSection("Transportation Objects");
}
Section tSection = trans.createSubSection(co.getGmlId().getGmlString());
sectionMap.put(co.getGmlId().getGmlString(), tSection);
if (hasError) {
numErrorTrans++;
tSection.setHeadlineColor(ERROR_COLOR);
} else {
numOkTrans++;
tSection.setHeadlineColor(OK_COLOR);
}
writeErrorForCityObject(co, tSection);
TransportationObject to = (TransportationObject) co;
for (TransportationObject transO : to.getChildren()) {
writeCheckResultForTransportationObject(transO, tSection);
}
}
private void reportVegetation(CityObject co, boolean hasError) {
if (vegetation == null) {
vegetation = vr.createSubSection("Vegetation");
}
Section vSection = vegetation.createSubSection(co.getGmlId().getGmlString());
sectionMap.put(co.getGmlId().getGmlString(), vSection);
if (hasError) {
numErrorVegetation++;
vSection.setHeadlineColor(ERROR_COLOR);
} else {
numOkVegetation++;
vSection.setHeadlineColor(OK_COLOR);
}
writeErrorForCityObject(co, vSection);
}
private void reportBuilding(CityObject co, boolean hasError) {
if (buildings == null) {
buildings = vr.createSubSection("Buildings");
}
Section bSection = buildings.createSubSection(co.getGmlId().getGmlString());
sectionMap.put(co.getGmlId().getGmlString(), bSection);
if (hasError) {
bSection.setHeadlineColor(ERROR_COLOR);
} else {
bSection.setHeadlineColor(OK_COLOR);
}
writeErrorForCityObject(co, bSection);
Building b = (Building) co;
for (BuildingPart bp : b.getBuildingParts()) {
sectionMap.put(bp.getGmlId().getGmlString(), bSection);
writeCheckResultForBuildingPart(bp, bSection);
}
for (BoundarySurface bs : b.getBoundarySurfaces()) {
writeCheckResultForBoundarySurface(bs, bSection);
}
}
private void writeCheckResultForTransportationObject(TransportationObject to, Section root) {
Map<CheckId, CheckResult> results = to.getAllCheckResults();
writeCheckResults(results.values(), root);
for (Geometry geom : to.getGeometries()) {
writeCheckResultForGeometry(geom, root);
}
}
private void writeCheckResultForBuildingPart(BuildingPart bp, Section root) {
Map<CheckId, CheckResult> results = bp.getAllCheckResults();
writeCheckResults(results.values(), root);
for (Geometry geom : bp.getGeometries()) {
writeCheckResultForGeometry(geom, root);
}
for (BoundarySurface bs : bp.getBoundarySurfaces()) {
writeCheckResultForBoundarySurface(bs, root);
}
}
private void writeErrorForCityObject(CityObject co, Section section) {
Map<CheckId, CheckResult> results = co.getAllCheckResults();
writeCheckResults(results.values(), section);
for (Geometry geom : co.getGeometries()) {
writeCheckResultForGeometry(geom, section);
}
}
private void writeCheckResultForBoundarySurface(BoundarySurface bs, Section root) {
Map<CheckId, CheckResult> results = bs.getAllCheckResults();
writeCheckResults(results.values(), root);
for (Opening o : bs.getOpenings()) {
writeCheckResultForOpening(o, root);
}
}
private void writeCheckResultForOpening(Opening o, Section root) {
Map<CheckId, CheckResult> results = o.getAllCheckResults();
writeCheckResults(results.values(), root);
}
private void writeCheckResultForGeometry(Geometry geom, Section root) {
Map<CheckId, CheckResult> results = geom.getAllCheckResults();
writeCheckResults(results.values(), root);
for (Polygon poly : geom.getPolygons()) {
writeCheckResultForPolygon(poly, root);
}
}
private void writeCheckResultForPolygon(Polygon poly, Section root) {
Map<CheckId, CheckResult> results = poly.getAllCheckResults();
writeCheckResults(results.values(), root);
writeCheckResultForLinearRing(poly.getExteriorRing(), root);
for (LinearRing ring : poly.getInnerRings()) {
writeCheckResultForLinearRing(ring, root);
}
}
private void writeCheckResultForLinearRing(LinearRing ring, Section root) {
Map<CheckId, CheckResult> results = ring.getAllCheckResults();
writeCheckResults(results.values(), root);
}
private void writeCheckResults(Collection<CheckResult> results, Section root) {
for (CheckResult cr : results) {
if (cr.getResultStatus() == ResultStatus.ERROR) {
writeError(root, cr.getError());
}
}
}
private void writeError(Section root, CheckError error) {
String text = "Error " + error.getErrorId().toString() + ":";
root.add12PtTextElement(text, 0);
PdfErrorHandler handler = new PdfErrorHandler(root, config.getParserConfiguration());
error.report(handler);
root.addError(error);
}
private boolean containsError(CityObject co) {
return co.containsAnyError();
}
@Override
public void finishReport() throws CheckReportWriteException {
for (Section s : buildings.getSubSections()) {
if (!s.hasErrors()) {
numOkBuildings++;
// building has no errors, no table
continue;
}
numErrorBuildings++;
Table t = new Table(2);
t.setTableColumnWidth(75, 25);
t.setTitle("Error", "Count");
for (Entry<String, AtomicInteger> e : s.getStats().getErrorCounts().entrySet()) {
t.addRow(e.getKey(), e.getValue().toString());
}
s.addTable(1, t);
}
int numBuildings = numErrorBuildings + numOkBuildings;
if (numBuildings > 0) {
statistics.addDistributionBar("Buildings", numErrorBuildings, numOkBuildings);
}
int numVegetation = numErrorVegetation + numOkVegetation;
if (numVegetation > 0) {
statistics.addDistributionBar("Vegetation", numErrorVegetation, numOkVegetation);
}
int numtr = numErrorTrans + numOkTrans;
if (numtr > 0) {
statistics.addDistributionBar("Transportation Objects", numErrorTrans, numOkTrans);
}
int numbri = numErrorBridge + numOkBridge;
if (numbri > 0) {
statistics.addDistributionBar("Bridge Objects", numErrorBridge, numOkBridge);
}
int numWater = numErrorWater + numOkWater;
if (numWater > 0) {
statistics.addDistributionBar("Water Objects", numErrorWater, numOkWater);
}
int numLand = numErrorLand + numOkLand;
if (numLand > 0) {
statistics.addDistributionBar("Land Objects", numErrorLand, numOkLand);
}
statistics.addTextElement("Error Statistics:");
for (Entry<ErrorId, AtomicInteger> e : errorStatistics.entrySet()) {
statistics.add10PtTextElement(e.getKey().toString() + ": " + e.getValue().intValue(), 10);
}
report.save(outFile);
}
@Override
public void reportGlobalError(CheckError err) {
AtomicInteger errorCount = errorStatistics.computeIfAbsent(err.getErrorId(), k -> new AtomicInteger(0));
errorCount.incrementAndGet();
if (globalErrors == null) {
globalErrors = vr.createSubSection("Global Errors");
}
String text = "Global error " + err.getErrorId();
globalErrors.add10PtTextElement(text, 10);
if (err instanceof SchematronError) {
text = ((SchematronError) err).getText();
globalErrors.add10PtTextElement(text, 20);
}
}
@Override
public void addError(String gmlId, CheckError err) {
AtomicInteger errorCount = errorStatistics.computeIfAbsent(err.getErrorId(), k -> new AtomicInteger(0));
errorCount.incrementAndGet();
Section section = sectionMap.get(gmlId);
if (section == null) {
logger.warn("No section found for gml id: {}, adding to global errors instead", gmlId);
reportGlobalError(err);
} else {
section.setHeadlineColor(ERROR_COLOR);
writeError(section, err);
section.addError(err);
}
}
}
/*-
* Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
*
* This file is part of CityDoctor2.
*
* CityDoctor2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CityDoctor2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CityDoctor2. If not, see <https://www.gnu.org/licenses/>.
*/
package de.hft.stuttgart.citydoctor2.reporting.pdf;
import org.jdom2.Element;
import org.jdom2.Namespace;
/**
* Utility class for creating PDF diagrams
*
* @author Matthias Betz
*
*/
public class PdfUtils {
private static final Namespace svgNs = Namespace.getNamespace("svg", "http://www.w3.org/2000/svg");
private static final int WIDTH = 450;
private PdfUtils() {
// only static use
}
public static Element createBar(int val1, int val2) {
int max = val1 + val2;
double val1Percentage = val1 / (double) max;
int val1Length = (int) (val1Percentage * WIDTH);
int val2Length = WIDTH - val1Length;
String val1LengthString = "" + val1Length;
String val2LengthString = "" + val2Length;
Element svgElement = new Element("svg", svgNs);
svgElement.setAttribute("width", "450px");
svgElement.setAttribute("height", "30px");
if (val1 > 0) {
Element gVal1Style = new Element("g", svgNs);
svgElement.addContent(gVal1Style);
gVal1Style.setAttribute("style", "fill:red");
Element val1Rect = new Element("rect", svgNs);
gVal1Style.addContent(val1Rect);
val1Rect.setAttribute("x", "0");
val1Rect.setAttribute("y", "0");
val1Rect.setAttribute("width", val1LengthString);
val1Rect.setAttribute("height", "30");
Element val1Text = new Element("text", svgNs);
svgElement.addContent(val1Text);
val1Text.setAttribute("x", "5");
val1Text.setAttribute("y", "20");
val1Text.setAttribute("font-size", "18pt");
val1Text.addContent("" + val1);
}
if (val2 > 0) {
Element gVal2Style = new Element("g", svgNs);
svgElement.addContent(gVal2Style);
gVal2Style.setAttribute("style", "fill:green");
Element val2Rect = new Element("rect", svgNs);
gVal2Style.addContent(val2Rect);
val2Rect.setAttribute("x", val1LengthString);
val2Rect.setAttribute("y", "0");
val2Rect.setAttribute("width", val2LengthString);
val2Rect.setAttribute("height", "30");
Element val2Text = new Element("text", svgNs);
svgElement.addContent(val2Text);
val2Text.setAttribute("x", "" + (WIDTH - 30));
val2Text.setAttribute("y", "20");
val2Text.setAttribute("font-size", "18pt");
val2Text.addContent("" + val2);
}
return svgElement;
}
}
/*-
* Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
*
* This file is part of CityDoctor2.
*
* CityDoctor2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CityDoctor2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CityDoctor2. If not, see <https://www.gnu.org/licenses/>.
*/
package de.hft.stuttgart.citydoctor2.reporting.pdf;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.jdom2.Element;
import de.hft.stuttgart.citydoctor2.check.CheckError;
import de.hft.stuttgart.citydoctor2.reporting.ErrorStatisticsCollector;
/**
* Represents a section in a pdf report
*
* @author Matthias Betz
*
*/
public class Section {
private static final String FONT_FAMILY = "font-family";
private static final String COLOR_TEXT = "color";
private static final String BASIC_LINK = "basic-link";
private static final String JUSTIFY = "justify";
private static final String TEXT_ALIGN_LAST = "text-align-last";
private static final String MARGIN_LEFT = "margin-left";
private static final String MARGIN_BOTTOM = "margin-bottom";
private static final String FONT_WEIGHT = "font-weight";
private static final String FONT_SIZE = "font-size";
private static final String BLOCK = "block";
private static final String TOC_LINE_MARGIN = "5pt";
private static final AtomicInteger S_COUNTER = new AtomicInteger(0);
private Element tocBlock;
private Element contentBlock;
private Element headlineBlock;
private String linkId;
private List<Section> subSections;
private int depth;
// attributes for error reporting
private ErrorStatisticsCollector stats;
Section(String headline, int depth) {
this(headline, depth, false);
}
Section(String headline, int depth, boolean newPage) {
this.depth = depth;
linkId = "s" + S_COUNTER.getAndIncrement();
tocBlock = new Element(BLOCK, PdfReport.FO_NS);
PdfReport.applyFont(tocBlock);
if (depth == 0) {
tocBlock.setAttribute(FONT_SIZE, "16pt");
} else if (depth == 1) {
tocBlock.setAttribute(FONT_SIZE, "14pt");
} else {
tocBlock.setAttribute(FONT_SIZE, "12pt");
}
tocBlock.setAttribute(FONT_WEIGHT, "bold");
tocBlock.setAttribute(MARGIN_BOTTOM, TOC_LINE_MARGIN);
tocBlock.setAttribute(MARGIN_LEFT, (depth + 1) + "0mm");
tocBlock.setAttribute(TEXT_ALIGN_LAST, JUSTIFY);
Element tocLine = new Element(BASIC_LINK, PdfReport.FO_NS);
tocBlock.addContent(tocLine);
tocLine.setAttribute("internal-destination", linkId);
tocLine.addContent(headline);
Element inline = new Element("inline", PdfReport.FO_NS);
tocLine.addContent(inline);
Element leader = new Element("leader", PdfReport.FO_NS);
inline.addContent(leader);
leader.setAttribute("leader-pattern", "dots");
Element pageNumberCitation = new Element("page-number-citation", PdfReport.FO_NS);
tocLine.addContent(pageNumberCitation);
pageNumberCitation.setAttribute("ref-id", linkId);
contentBlock = new Element(BLOCK, PdfReport.FO_NS);
headlineBlock = new Element(BLOCK, PdfReport.FO_NS);
contentBlock.addContent(headlineBlock);
if (depth == 0) {
PdfReport.applyHeadlineAttributes(headlineBlock);
} else if (depth == 1) {
PdfReport.applySubHeadlineAttributes(headlineBlock);
} else {
PdfReport.applySubSubHeadlineAttributes(headlineBlock);
}
headlineBlock.addContent(headline);
headlineBlock.setAttribute("id", linkId);
if (newPage) {
headlineBlock.setAttribute("page-break-before", "always");
}
}
public boolean hasErrors() {
return stats != null && !stats.getErrorCounts().isEmpty();
}
public ErrorStatisticsCollector getStats() {
if (stats == null) {
stats = new ErrorStatisticsCollector();
}
return stats;
}
public void addError(CheckError err) {
getStats().addError(err.getErrorId().toString());
}
public Section createSubSection(String headline) {
Section sub = new Section(headline, depth + 1);
if (subSections == null) {
subSections = new ArrayList<>();
}
subSections.add(sub);
contentBlock.addContent(sub.getContentBlock());
return sub;
}
public void setHeadlineColor(String color) {
headlineBlock.setAttribute(COLOR_TEXT, color);
tocBlock.setAttribute(COLOR_TEXT, color);
}
public void addTable(Table t) {
contentBlock.addContent(t.getTableBlock());
}
public void addTable(int pos, Table t) {
contentBlock.addContent(pos, t.getTableBlock());
}
public void addTextElement(String text) {
contentBlock.addContent(PdfReport.createTextElement(text));
}
public void addTextElement(String text, String color) {
Element textBlock = PdfReport.createTextElement(text);
textBlock.setAttribute(COLOR_TEXT, color);
contentBlock.addContent(textBlock);
}
public void addTextElement(String text, int intend) {
Element textBlock = PdfReport.createTextElement(text);
textBlock.setAttribute(MARGIN_LEFT, intend + "mm");
contentBlock.addContent(textBlock);
}
public void add10PtTextElement(String text, int intend) {
Element textBlock = PdfReport.createTextElement(text);
textBlock.setAttribute(FONT_SIZE, "10pt");
textBlock.setAttribute(MARGIN_LEFT, intend + "mm");
contentBlock.addContent(textBlock);
}
public void add12PtTextElement(String text, int intend) {
Element textBlock = PdfReport.createTextElement(text);
textBlock.setAttribute(FONT_SIZE, "12pt");
textBlock.setAttribute(MARGIN_LEFT, intend + "mm");
contentBlock.addContent(textBlock);
}
public void add10PtTextElement(String fontFamily, String text, int intend) {
Element textBlock = PdfReport.createTextElement(text);
textBlock.setAttribute(FONT_SIZE, "10pt");
textBlock.setAttribute(MARGIN_LEFT, intend + "mm");
textBlock.setAttribute(FONT_FAMILY, fontFamily);
contentBlock.addContent(textBlock);
}
public void addDistributionBar(String title, int redCount, int greenCount) {
int complete = redCount + greenCount;
Element distributionBlock = new Element(BLOCK, PdfReport.FO_NS);
contentBlock.addContent(distributionBlock);
distributionBlock.addContent(PdfReport.createTextElement(title + " (" + complete + "):"));
Element distribInstream = new Element("instream-foreign-object", PdfReport.FO_NS);
distributionBlock.addContent(distribInstream);
distribInstream.addNamespaceDeclaration(PdfReport.SVG_NS);
distribInstream.addContent(PdfUtils.createBar(redCount, greenCount));
}
Element getContentBlock() {
return contentBlock;
}
Element getTocBlock() {
return tocBlock;
}
List<Section> getSubSections() {
if (subSections == null) {
return Collections.emptyList();
}
return subSections;
}
public void addCodeBlock(CodeBlock codeBlock) {
contentBlock.addContent(codeBlock.getCodeBlock());
}
}
/*-
* Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
*
* This file is part of CityDoctor2.
*
* CityDoctor2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CityDoctor2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CityDoctor2. If not, see <https://www.gnu.org/licenses/>.
*/
package de.hft.stuttgart.citydoctor2.reporting.pdf;
import org.jdom2.Element;
/**
* Construct a table for the pdf report.
*
* @author Matthias Betz
*
*/
public class Table {
private static final String TABLE_HEADER_COLOR = "#58ACFA";
private Element tableBlock;
private Element tableHeader;
private Element tableBody;
private Element table;
private int columns;
public Table(int columns) {
this.columns = columns;
tableBlock = new Element("block", PdfReport.FO_NS);
tableBlock.setAttribute("padding-after", "10");
tableBlock.setAttribute("keep-together", "always");
table = new Element("table", PdfReport.FO_NS);
tableBlock.addContent(table);
PdfReport.applySolidBorder(table);
table.setAttribute("table-layout", "fixed");
table.setAttribute("width", "100%");
tableHeader = new Element("table-header", PdfReport.FO_NS);
table.addContent(tableHeader);
tableHeader.setAttribute("background-color", TABLE_HEADER_COLOR);
tableBody = new Element("table-body", PdfReport.FO_NS);
table.addContent(tableBody);
}
public void setTableColumnWidth(int... width) {
int sum = 0;
for (int w : width) {
sum += w;
}
if (sum != 100 || width.length != columns) {
throw new IllegalArgumentException("column width must result in a sum of 100");
}
for (int i = 1; i <= width.length; i++) {
int w = width[i - 1];
Element tableColumn = new Element("table-column", PdfReport.FO_NS);
table.addContent(i - 1, tableColumn);
tableColumn.setAttribute("column-number", "" + i);
tableColumn.setAttribute("column-width", w + "%");
}
}
public void setTitle(String... content) {
if (content.length != columns) {
throw new IllegalArgumentException(
"Column length is: " + columns + " but only " + content.length + " values given");
}
if (tableHeader.getContentSize() > 0) {
tableHeader.removeContent();
}
tableHeader.addContent(createTableRow(content));
}
public void addRow(String... content) {
if (content.length != columns) {
throw new IllegalArgumentException(
"Column length is: " + columns + " but only " + content.length + " values given");
}
tableBody.addContent(createTableRow(content));
}
Element getTableBlock() {
return tableBlock;
}
private Element createTableRow(String... content) {
Element tableRow = new Element("table-row", PdfReport.FO_NS);
for (int i = 0; i < content.length; i++) {
Element tableCell = new Element("table-cell", PdfReport.FO_NS);
tableRow.addContent(tableCell);
tableCell.addContent(PdfReport.createTextElement(content[i]));
tableCell.setAttribute("padding", "3pt 3pt 3pt 3pt");
PdfReport.applySolidBorder(tableCell);
}
return tableRow;
}
}
<?xml version="1.0" encoding="UTF-8"?><?xar XSLT?>
<!--
OVERVIEW - iso_abstract_expand.xsl
This is a preprocessor for ISO Schematron, which implements abstract patterns.
It also
* extracts a particular schema using an ID, where there are multiple
schemas, such as when they are embedded in the same NVDL script
* allows parameter substitution inside @context, @test, @select, @path
* experimentally, allows parameter recognition and substitution inside
text (NOTE: to be removed, for compataibility with other implementations,
please do not use this)
This should be used after iso-dsdl-include.xsl and before the skeleton or
meta-stylesheet (e.g. iso-svrl.xsl) . It only requires XSLT 1.
Each kind of inclusion can be turned off (or on) on the command line.
-->
<!--
Open Source Initiative OSI - The MIT License:Licensing
[OSI Approved License]
This source code was previously available under the zlib/libpng license.
Attribution is polite.
The MIT License
Copyright (c) 2004-2010 Rick Jellife and Academia Sinica Computing Centre, Taiwan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<!--
VERSION INFORMATION
2013-09-19 RJ
* Allow macro expansion in @path attributes, eg. for sch:name/@path
2010-07-10 RJ
* Move to MIT license
2008-09-18 RJ
* move out param test from iso:schema template to work with XSLT 1. (Noah Fontes)
2008-07-29 RJ
* Create. Pull out as distinct XSL in its own namespace from old iso_pre_pro.xsl
* Put everything in private namespace
* Rewrite replace_substring named template so that copyright is clear
2008-07-24 RJ
* correct abstract patterns so for correct names: param/@name and
param/@value
2007-01-12 RJ
* Use ISO namespace
* Use pattern/@id not pattern/@name
* Add Oliver Becker's suggests from old Schematron-love-in list for <copy>
* Add XT -ism?
2003 RJ
* Original written for old namespace
* http://www.topologi.com/resources/iso-pre-pro.xsl
-->
<xslt:stylesheet version="1.0" xmlns:xslt="http://www.w3.org/1999/XSL/Transform"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:iso="http://purl.oclc.org/dsdl/schematron"
xmlns:nvdl="http://purl.oclc.org/dsdl/nvdl"
xmlns:iae="http://www.schematron.com/namespace/iae"
>
<xslt:param name="schema-id"></xslt:param>
<!-- Driver for the mode -->
<xsl:template match="/">
<xsl:apply-templates select="." mode="iae:go" />
</xsl:template>
<!-- ================================================================================== -->
<!-- Normal processing rules -->
<!-- ================================================================================== -->
<!-- Output only the selected schema -->
<xslt:template match="iso:schema" >
<xsl:if test="string-length($schema-id) =0 or @id= $schema-id ">
<xslt:copy>
<xslt:copy-of select="@*" />
<xslt:apply-templates mode="iae:go" />
</xslt:copy>
</xsl:if>
</xslt:template>
<!-- Strip out any foreign elements above the Schematron schema .
-->
<xslt:template match="*[not(ancestor-or-self::iso:*)]" mode="iae:go" >
<xslt:apply-templates mode="iae:go" />
</xslt:template>
<!-- ================================================================================== -->
<!-- Handle Schematron abstract pattern preprocessing -->
<!-- abstract-to-real calls
do-pattern calls
macro-expand calls
multi-macro-expand
replace-substring -->
<!-- ================================================================================== -->
<!--
Abstract patterns allow you to say, for example
<pattern name="htmlTable" is-a="table">
<param name="row" value="html:tr"/>
<param name="cell" value="html:td" />
<param name="table" value="html:table" />
</pattern>
For a good introduction, see Uche Ogbujii's article for IBM DeveloperWorks
"Discover the flexibility of Schematron abstract patterns"
http://www-128.ibm.com/developerworks/xml/library/x-stron.html
However, note that ISO Schematron uses @name and @value attributes on
the iso:param element, and @id not @name on the pattern element.
-->
<!-- Suppress declarations of abstract patterns -->
<xslt:template match="iso:pattern[@abstract='true']" mode="iae:go" >
<xslt:comment>Suppressed abstract pattern <xslt:value-of select="@id"/> was here</xslt:comment>
</xslt:template>
<!-- Suppress uses of abstract patterns -->
<xslt:template match="iso:pattern[@is-a]" mode="iae:go" >
<xslt:comment>Start pattern based on abstract <xslt:value-of select="@is-a"/></xslt:comment>
<xslt:call-template name="iae:abstract-to-real" >
<xslt:with-param name="caller" select="@id" />
<xslt:with-param name="is-a" select="@is-a" />
</xslt:call-template>
</xslt:template>
<!-- output everything else unchanged -->
<xslt:template match="*" priority="-1" mode="iae:go" >
<xslt:copy>
<xslt:copy-of select="@*" />
<xslt:apply-templates mode="iae:go"/>
</xslt:copy>
</xslt:template>
<!-- Templates for macro expansion of abstract patterns -->
<!-- Sets up the initial conditions for the recursive call -->
<xslt:template name="iae:macro-expand">
<xslt:param name="caller"/>
<xslt:param name="text" />
<xslt:call-template name="iae:multi-macro-expand">
<xslt:with-param name="caller" select="$caller"/>
<xslt:with-param name="text" select="$text"/>
<xslt:with-param name="paramNumber" select="1"/>
</xslt:call-template>
</xslt:template>
<!-- Template to replace the current parameter and then
recurse to replace subsequent parameters. -->
<xslt:template name="iae:multi-macro-expand">
<xslt:param name="caller"/>
<xslt:param name="text" />
<xslt:param name="paramNumber" />
<xslt:choose>
<xslt:when test="//iso:pattern[@id=$caller]/iso:param[ $paramNumber]">
<xslt:call-template name="iae:multi-macro-expand">
<xslt:with-param name="caller" select="$caller"/>
<xslt:with-param name="paramNumber" select="$paramNumber + 1"/>
<xslt:with-param name="text" >
<xslt:call-template name="iae:replace-substring">
<xslt:with-param name="original" select="$text"/>
<xslt:with-param name="substring"
select="concat('$', //iso:pattern[@id=$caller]/iso:param[ $paramNumber ]/@name)"/>
<xslt:with-param name="replacement"
select="//iso:pattern[@id=$caller]/iso:param[ $paramNumber ]/@value"/>
</xslt:call-template>
</xslt:with-param>
</xslt:call-template>
</xslt:when>
<xslt:otherwise><xslt:value-of select="$text" /></xslt:otherwise>
</xslt:choose>
</xslt:template>
<!-- generate the real pattern from an abstract pattern + parameters-->
<xslt:template name="iae:abstract-to-real" >
<xslt:param name="caller"/>
<xslt:param name="is-a" />
<xslt:for-each select="//iso:pattern[@id= $is-a]">
<xslt:copy>
<xslt:choose>
<xslt:when test=" string-length( $caller ) = 0">
<xslt:attribute name="id"><xslt:value-of select="concat( generate-id(.) , $is-a)" /></xslt:attribute>
</xslt:when>
<xslt:otherwise>
<xslt:attribute name="id"><xslt:value-of select="$caller" /></xslt:attribute>
</xslt:otherwise>
</xslt:choose>
<xslt:apply-templates select="*|text()" mode="iae:do-pattern" >
<xslt:with-param name="caller"><xslt:value-of select="$caller"/></xslt:with-param>
</xslt:apply-templates>
</xslt:copy>
</xslt:for-each>
</xslt:template>
<!-- Generate a non-abstract pattern -->
<xslt:template mode="iae:do-pattern" match="*">
<xslt:param name="caller"/>
<xslt:copy>
<xslt:for-each select="@*[name()='test' or name()='context' or name()='select' or name()='path' ]">
<xslt:attribute name="{name()}">
<xslt:call-template name="iae:macro-expand">
<xslt:with-param name="text"><xslt:value-of select="."/></xslt:with-param>
<xslt:with-param name="caller"><xslt:value-of select="$caller"/></xslt:with-param>
</xslt:call-template>
</xslt:attribute>
</xslt:for-each>
<xslt:copy-of select="@*[name()!='test'][name()!='context'][name()!='select'][name()!='path']" />
<xsl:for-each select="node()">
<xsl:choose>
<!-- Experiment: replace macros in text as well, to allow parameterized assertions
and so on, without having to have spurious <iso:value-of> calls and multiple
delimiting.
NOTE: THIS FUNCTIONALITY WILL BE REMOVED IN THE FUTURE -->
<xsl:when test="self::text()">
<xslt:call-template name="iae:macro-expand">
<xslt:with-param name="text"><xslt:value-of select="."/></xslt:with-param>
<xslt:with-param name="caller"><xslt:value-of select="$caller"/></xslt:with-param>
</xslt:call-template>
</xsl:when>
<xsl:otherwise>
<xslt:apply-templates select="." mode="iae:do-pattern">
<xslt:with-param name="caller"><xslt:value-of select="$caller"/></xslt:with-param>
</xslt:apply-templates>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xslt:copy>
</xslt:template>
<!-- UTILITIES -->
<!-- Simple version of replace-substring function -->
<xslt:template name="iae:replace-substring">
<xslt:param name="original" />
<xslt:param name="substring" />
<xslt:param name="replacement" select="''"/>
<xsl:choose>
<xsl:when test="not($original)" />
<xsl:when test="not(string($substring))">
<xsl:value-of select="$original" />
</xsl:when>
<xsl:when test="contains($original, $substring)">
<xsl:variable name="before" select="substring-before($original, $substring)" />
<xsl:variable name="after" select="substring-after($original, $substring)" />
<xsl:value-of select="$before" />
<xsl:value-of select="$replacement" />
<!-- recursion -->
<xsl:call-template name="iae:replace-substring">
<xsl:with-param name="original" select="$after" />
<xsl:with-param name="substring" select="$substring" />
<xsl:with-param name="replacement" select="$replacement" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<!-- no substitution -->
<xsl:value-of select="$original" />
</xsl:otherwise>
</xsl:choose>
</xslt:template>
</xslt:stylesheet>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?><?xar XSLT?>
<!--
OVERVIEW : iso_dsdl_include.xsl
This is an inclusion preprocessor for the non-smart text inclusions
of ISO DSDL. It handles
<relax:extRef> for ISO RELAX NG
<sch:include> for ISO Schematron and Schematron 1.n
<sch:extends> for 2009 draft ISO Schematron
<xi:xinclude> simple W3C XIncludes for ISO NVRL and DSRL
<crdl:ref> for draft ISO CRDL
<dtll:include> for draft ISO DTLL
<* @xlink:href> for simple W3C XLink 1.1 embedded links
This should be the first in any chain of processing. It only requires
XSLT 1. Each kind of inclusion can be turned off (or on) on the command line.
Ids in fragment identifiers or xpointers will be sought in the following
order:
* @xml:id
* id() for typed schemas (e.g. from DTD) [NOTE: XInclude does not support this]
* untyped @id
The proposed behaviour for the update to ISO Schematron has been implemented. If an
include points to an element with the same name as the parent, then that element's
contents will be included. This supports the merge style of inclusion.
When an inclusion is made, it is preceded by a PI with target DSDL_INCLUDE_START
and the href and closed by a PI with target DSDL_INCLUDE_START and the href. This is
to allow better location of problems, though only to the file level.
Limitations:
* No rebasing: relative paths will be interpreted based on the initial document's
path, not the including document. (Severe limitation!)
* No checking for circular references
* Not full xpointers: only ID matching
* <relax:include> not implemented
* XInclude handling of xml:base and xml:lang not implemented
-->
<!--
Open Source Initiative OSI - The MIT License:Licensing
[OSI Approved License]
This source code was previously available under the zlib/libpng license.
Attribution is polite.
The MIT License
Copyright (c) 2008-2010 Rick Jelliffe
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<!--
VERSION INFORMATION
2010-07-10
* Move to MIT license
2010-04-21
* Add basic syntax checks on XPaths belonging to Schematron elements only
* Unlocalized messages are put out using xsl:message. The intent is to allow
* problems to be caught at compile time.
2009-02-25
* Update DSDL namespace to use schematron.com
* Tested with SAXON9, Xalan 2.7.1, IE7,
* IE does not like multiple variables in same template with same name: rename.
2008-09-18
* Remove new behaviour for include, because it conflicts with existing usage [KH]
* Add extends[@href] element with that merge functionality
* Generate PIs to notate source of inclusions for potential better diagnostics
2008-09-16
* Fix for XSLT1
2008-08-28
* New behaviour for schematron includes: if the pointed to element is the same as the current,
include the children. [Note: this has been removed: use sch:extends with @href.]
2008-08-20
* Fix bug: in XSLT1 cannot do $document/id('x') but need to use for-each
2008-08-04
* Add support for inclusions in old namespace
2008-08-03
* Fix wrong param name include-relaxng & include-crdl (KH, PH)
* Allow inclusion of XSLT and XHTML (KH)
* Fix inclusion of fragments (KH)
2008-07-25
* Add selectable input parameter
2008-07-24
* RJ New
-->
<xslt:stylesheet version="1.0"
xmlns:xslt="http://www.w3.org/1999/XSL/Transform"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:iso="http://purl.oclc.org/dsdl/schematron"
xmlns:nvdl="http://purl.oclc.org/dsdl/nvdl"
xmlns:xhtml="http://www.w3.org/1999/xhtml"
xmlns:schold="http://www.ascc.net/xml/schematron"
xmlns:crdl="http://purl.oclc.org/dsdl/crepdl/ns/structure/1.0"
xmlns:xi="http://www.w3.org/2001/XInclude"
xmlns:dtll="http://www.jenitennison.com/datatypes"
xmlns:dsdl="http://www.schematron.com/namespace/dsdl"
xmlns:relax="http://relaxng.org/ns/structure/1.0"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:sch-check="http://www.schematron.com/namespace/sch-check"
>
<!-- Note: The URL for the dsdl namespace is not official -->
<xsl:param name="include-schematron">true</xsl:param>
<xsl:param name="include-crdl">true</xsl:param>
<xsl:param name="include-xinclude">true</xsl:param>
<xsl:param name="include-dtll">true</xsl:param>
<xsl:param name="include-relaxng">true</xsl:param>
<xsl:param name="include-xlink">true</xsl:param>
<!-- ========================================================== -->
<!-- Output and process contents, check Schematron XPaths too -->
<!-- ========================================================== -->
<xsl:template match="/">
<xsl:apply-templates select="." mode="dsdl:go" />
</xsl:template>
<!-- output everything else unchanged. But check Xpaths here. -->
<xslt:template match="iso:rule[@context]" mode="dsdl:go">
<xsl:call-template name="sch-check:xpath-wf-message">
<xsl:with-param name="string" select=" @context " />
<xsl:with-param name="subject" select=" 'Bad rule: ' " />
</xsl:call-template>
<xslt:copy>
<xslt:copy-of select="@*" />
<xslt:apply-templates mode="dsdl:go" />
</xslt:copy>
</xslt:template>
<xslt:template match="iso:assert[@test]" mode="dsdl:go">
<xsl:call-template name="sch-check:xpath-wf-message">
<xsl:with-param name="string" select=" @test " />
<xsl:with-param name="subject" select=" 'Bad assert: ' " />
</xsl:call-template>
<xslt:copy>
<xslt:copy-of select="@*" />
<xslt:apply-templates mode="dsdl:go" />
</xslt:copy>
</xslt:template>
<xslt:template match="iso:report[@test]" mode="dsdl:go">
<xsl:call-template name="sch-check:xpath-wf-message">
<xsl:with-param name="string" select=" @test " />
<xsl:with-param name="subject" select=" 'Bad report: ' " />
</xsl:call-template>
<xslt:copy>
<xslt:copy-of select="@*" />
<xslt:apply-templates mode="dsdl:go" />
</xslt:copy>
</xslt:template>
<xslt:template match="iso:let[@value]" mode="dsdl:go">
<xsl:call-template name="sch-check:xpath-wf-message">
<xsl:with-param name="string" select=" @value " />
<xsl:with-param name="subject" select=" 'Bad let: ' " />
</xsl:call-template>
<xslt:copy>
<xslt:copy-of select="@*" />
<xslt:apply-templates mode="dsdl:go" />
</xslt:copy>
</xslt:template>
<xslt:template match="iso:value-of[@select]" mode="dsdl:go">
<xsl:call-template name="sch-check:xpath-wf-message">
<xsl:with-param name="string" select=" @select " />
<xsl:with-param name="subject" select=" 'Bad value-of: ' " />
</xsl:call-template>
<xslt:copy>
<xslt:copy-of select="@*" />
<xslt:apply-templates mode="dsdl:go" />
</xslt:copy>
</xslt:template>
<xslt:template match="iso:name[@path]" mode="dsdl:go">
<xsl:call-template name="sch-check:xpath-wf-message">
<xsl:with-param name="string" select=" @select " />
<xsl:with-param name="subject" select=" 'Bad name element: ' " />
</xsl:call-template>
<xslt:copy>
<xslt:copy-of select="@*" />
<xslt:apply-templates mode="dsdl:go" />
</xslt:copy>
</xslt:template>
<!-- output everything else unchanged -->
<xslt:template match="node()" priority="-1" mode="dsdl:go">
<xslt:copy>
<xslt:copy-of select="@*" />
<xslt:apply-templates mode="dsdl:go" />
</xslt:copy>
</xslt:template>
<!-- =========================================================== -->
<!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
<!-- Part 2 - Regular grammar-based validation - RELAX NG -->
<!-- This only implements relax:extRef not relax:include which -->
<!-- is complex. -->
<!-- =========================================================== -->
<xslt:template match="relax:extRef" mode="dsdl:go">
<!-- Insert subschema -->
<xsl:variable name="document-uri"
select="substring-before(concat(@href,'#'), '#')" />
<xsl:variable name="fragment-id"
select="substring-after(@href, '#')" />
<xsl:processing-instruction name="DSDL_INCLUDE_START">
<xsl:value-of select="@href" />
</xsl:processing-instruction>
<xsl:choose>
<xsl:when test="not( $include-relaxng = 'true' )">
<xslt:copy>
<xslt:copy-of select="@*" />
<xslt:apply-templates mode="dsdl:go" />
</xslt:copy>
</xsl:when>
<xsl:otherwise>
<xsl:choose>
<xsl:when
test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
<xsl:message>
Error: Impossible URL in RELAX NG extRef
include
</xsl:message>
</xsl:when>
<!-- this case is when there is in embedded schema in the same document elsewhere -->
<xslt:when
test="string-length( $document-uri ) = 0">
<xslt:apply-templates mode="dsdl:go"
select="//*[@xml:id= $fragment-id ] | id( $fragment-id) | //*[@id= $fragment-id ]" />
</xslt:when>
<xsl:when
test="string-length( $fragment-id ) &gt; 0">
<xsl:variable name="theDocument_1"
select="document( $document-uri,/ )" />
<xsl:if test="not($theDocument_1)">
<xsl:message terminate="no">
<xsl:text>Unable to open referenced included file: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<!-- use a for-each so that the id() function works correctly on the external document -->
<xsl:for-each select="$theDocument_1">
<xsl:variable name="theFragment_1"
select="$theDocument_1//*[@xml:id= $fragment-id ]
| id( $fragment-id)
| $theDocument_1//*[@id= $fragment-id ]" />
<xsl:if test="not($theFragment_1)">
<xsl:message terminate="no">
<xsl:text>Unable to locate id attribute: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<xsl:apply-templates
select=" $theFragment_1[1]" mode="dsdl:go" />
</xsl:for-each>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="theDocument_2"
select="document( $document-uri,/ )" />
<xsl:variable name="theFragment_2"
select="$theDocument_2/*" />
<xsl:if test="not($theDocument_2)">
<xsl:message terminate="no">
<xsl:text>Unable to open referenced included file: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<xsl:if test="not($theFragment_2)">
<xsl:message terminate="no">
<xsl:text>Unable to locate id attribute: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<xsl:apply-templates select="$theFragment_2 "
mode="dsdl:go" />
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
<xsl:processing-instruction name="DSDL_INCLUDE_END">
<xsl:value-of select="@href" />
</xsl:processing-instruction>
</xslt:template>
<!-- =========================================================== -->
<!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
<!-- Part 3 - Rule-based validation - Schematron -->
<!-- =========================================================== -->
<!-- Extend the URI syntax to allow # references -->
<!-- Add experimental support for simple containers like /xxx:xxx/iso:pattern to allow better includes -->
<xsl:template match="iso:include" mode="dsdl:go">
<xsl:variable name="document-uri"
select="substring-before(concat(@href,'#'), '#')" />
<xsl:variable name="fragment-id"
select="substring-after(@href, '#')" />
<xsl:processing-instruction name="DSDL_INCLUDE_START">
<xsl:value-of select="@href" />
</xsl:processing-instruction>
<xsl:choose>
<xsl:when test="not( $include-schematron = 'true' )">
<xslt:copy>
<xslt:copy-of select="@*" />
<xslt:apply-templates mode="dsdl:go" />
</xslt:copy>
</xsl:when>
<xsl:otherwise>
<xsl:choose>
<xsl:when
test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
<xsl:message>
Error: Impossible URL in Schematron include
</xsl:message>
</xsl:when>
<!-- this case is when there is in embedded schema in the same document elsewhere -->
<xslt:when
test="string-length( $document-uri ) = 0">
<xslt:apply-templates mode="dsdl:go"
select="//iso:*[@xml:id= $fragment-id ]
|id( $fragment-id)
| //iso:*[@id= $fragment-id ]" />
</xslt:when>
<!-- case where there is a fragment in another document (should be an iso: element) -->
<!-- There are three cases for includes with fragment:
0) No href file or no matching id - error!
1) REMOVED
2) The linked-to element is sch:schema however the parent of the include
is not a schema. In this case, it is an error. (Actually, it should
be an error for other kinds of containment problems, but we won't
check for them in this version.)
3) Otherwise, include the pointed-to element
-->
<xsl:when
test="string-length( $fragment-id ) &gt; 0">
<xsl:variable name="theDocument_1"
select="document( $document-uri,/ )" />
<xsl:variable name="originalParent" select=".." />
<!-- case 0 -->
<xsl:if test="not($theDocument_1)">
<xsl:message terminate="no">
<xsl:text>Unable to open referenced included file: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<!-- use for-each to rebase id() to external document -->
<xsl:for-each select="$theDocument_1">
<xsl:variable name="theFragment_1"
select=" $theDocument_1//iso:*[@xml:id= $fragment-id ] |
id($fragment-id) |
$theDocument_1//iso:*[@id= $fragment-id ]" />
<xsl:choose>
<!-- case 0 -->
<xsl:when test="not($theFragment_1)">
<xsl:message terminate="no">
<xsl:text>Unable to locate id attribute: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:when>
<!-- case 1 REMOVED -->
<!-- case 2 -->
<xsl:when
test=" $theFragment_1/self::iso:schema ">
<xsl:message>
Schema error: Use include to
include fragments, not a whole
schema
</xsl:message>
</xsl:when>
<!-- case 3 -->
<xsl:otherwise>
<xsl:apply-templates
select=" $theFragment_1[1]" mode="dsdl:go" />
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:when>
<!-- Case where there is no ID so we include the whole document -->
<!-- Experimental addition: include fragments of children -->
<xsl:otherwise>
<xsl:variable name="theDocument_2"
select="document( $document-uri,/ )" />
<xsl:variable name="theFragment_2"
select="$theDocument_2/iso:*" />
<xsl:variable name="theContainedFragments"
select="$theDocument_2/*/iso:* | $theDocument_2/*/xsl:* | $theDocument_2/*/xhtml:*" />
<xsl:if test="not($theDocument_2)">
<xsl:message terminate="no">
<xsl:text>Unable to open referenced included file: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<!-- There are three cases for includes:
0) No text specified- error!
1) REMOVED
2) The linked-to element is sch:schema however the parent of the include
is not a schema. In this case, it is an error. (Actually, it should
be an error for other kinds of containment problems, but we won't
check for them in this version.)
3) Otherwise, include the pointed-to element
-->
<xsl:choose>
<!-- case 0 -->
<xsl:when
test="not($theFragment_2) and not ($theContainedFragments)">
<xsl:message terminate="no">
<xsl:text>Unable to locate id attribute: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:when>
<!-- case 1 removed -->
<!-- case 2 -->
<xsl:when
test=" $theFragment_2/self::iso:schema or $theContainedFragments/self::iso:schema">
<xsl:message>
Schema error: Use include to include
fragments, not a whole schema
</xsl:message>
</xsl:when>
<!-- If this were XLST 2, we could use
if ($theFragment) then $theFragment else $theContainedFragments
here (thanks to KN)
-->
<!-- case 3 -->
<xsl:otherwise>
<xsl:apply-templates
select="$theFragment_2 " mode="dsdl:go" />
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
<xsl:processing-instruction name="DSDL_INCLUDE_END">
<xsl:value-of select="@href" />
</xsl:processing-instruction>
</xsl:template>
<!-- WARNING sch:extends[@href] is experimental and non standard -->
<!-- Basically, it adds the children of the selected element, not the element itself. -->
<xsl:template match="iso:extends[@href]" mode="dsdl:go">
<xsl:variable name="document-uri"
select="substring-before(concat(@href,'#'), '#')" />
<xsl:variable name="fragment-id"
select="substring-after(@href, '#')" />
<xsl:processing-instruction name="DSDL_INCLUDE_START">
<xsl:value-of select="@href" />
</xsl:processing-instruction>
<xsl:choose>
<xsl:when test="not( $include-schematron = 'true' )">
<xslt:copy>
<xslt:copy-of select="@*" />
<xslt:apply-templates mode="dsdl:go" />
</xslt:copy>
</xsl:when>
<xsl:otherwise>
<xsl:choose>
<xsl:when
test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
<xsl:message>
Error: Impossible URL in Schematron include
</xsl:message>
</xsl:when>
<!-- this case is when there is in embedded schema in the same document elsewhere -->
<xslt:when
test="string-length( $document-uri ) = 0">
<xslt:apply-templates mode="dsdl:go"
select="//iso:*[@xml:id= $fragment-id ]/*
|id( $fragment-id)/*
| //iso:*[@id= $fragment-id ]/*" />
</xslt:when>
<!-- case where there is a fragment in another document (should be an iso: element) -->
<!-- There are three cases for includes with fragment:
0) No href file or no matching id - error!
1) REMOVED
2) REMOVED
3) Otherwise, include the pointed-to element
-->
<xsl:when
test="string-length( $fragment-id ) &gt; 0">
<xsl:variable name="theDocument_1"
select="document( $document-uri,/ )" />
<xsl:variable name="originalParent" select=".." />
<!-- case 0 -->
<xsl:if test="not($theDocument_1)">
<xsl:message terminate="no">
<xsl:text>Unable to open referenced included file: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<!-- use for-each to rebase id() to external document -->
<xsl:for-each select="$theDocument_1">
<xsl:variable name="theFragment_1"
select=" $theDocument_1//iso:*[@xml:id= $fragment-id ] |
id($fragment-id) |
$theDocument_1//iso:*[@id= $fragment-id ]" />
<xsl:choose>
<!-- case 0 -->
<xsl:when test="not($theFragment_1)">
<xsl:message terminate="no">
<xsl:text>Unable to locate id attribute: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:when>
<!-- case 1 REMOVED -->
<!-- case 2 REMOVED -->
<!-- case 3 -->
<xsl:otherwise>
<xsl:apply-templates
select=" $theFragment_1[1]/*" mode="dsdl:go" />
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:when>
<!-- Case where there is no ID so we include the whole document -->
<!-- Experimental addition: include fragments of children -->
<xsl:otherwise>
<xsl:variable name="theDocument_2"
select="document( $document-uri,/ )" />
<xsl:variable name="theFragment_2"
select="$theDocument_2/iso:*" />
<xsl:variable name="theContainedFragments"
select="$theDocument_2/*/iso:* | $theDocument_2/*/xsl:* | $theDocument_2/*/xhtml:*" />
<xsl:if test="not($theDocument_2)">
<xsl:message terminate="no">
<xsl:text>Unable to open referenced included file: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<!-- There are three cases for includes:
0) No text specified- error!
1) REMOVED
2) REMOVED
3) Otherwise, include the pointed-to element
-->
<xsl:choose>
<!-- case 0 -->
<xsl:when
test="not($theFragment_2) and not ($theContainedFragments)">
<xsl:message terminate="no">
<xsl:text>Unable to locate id attribute: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:when>
<!-- case 1 removed -->
<!-- case 2 removed -->
<!-- If this were XLST 2, we could use
if ($theFragment) then $theFragment else $theContainedFragments
here (thanks to KN)
-->
<!-- case 3 -->
<xsl:otherwise>
<xsl:apply-templates
select="$theFragment_2/* " mode="dsdl:go" />
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
<xsl:processing-instruction name="DSDL_INCLUDE_END">
<xsl:value-of select="@href" />
</xsl:processing-instruction>
</xsl:template>
<!-- =========================================================== -->
<!-- Handle Schematron 1.6 inclusions: clone of ISO code above -->
<!-- =========================================================== -->
<!-- Extend the URI syntax to allow # references -->
<!-- Add experimental support for simple containers like /xxx:xxx/schold:pattern to allow better includes -->
<xsl:template match="schold:include" mode="dsdl:go">
<xsl:variable name="document-uri"
select="substring-before(concat(@href,'#'), '#')" />
<xsl:variable name="fragment-id"
select="substring-after(@href, '#')" />
<xsl:processing-instruction name="DSDL_INCLUDE_START">
<xsl:value-of select="@href" />
</xsl:processing-instruction>
<xsl:choose>
<xsl:when test="not( $include-schematron = 'true' )">
<xslt:copy>
<xslt:copy-of select="@*" />
<xslt:apply-templates mode="dsdl:go" />
</xslt:copy>
</xsl:when>
<xsl:otherwise>
<xsl:choose>
<xsl:when
test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
<xsl:message>
Error: Impossible URL in Schematron include
</xsl:message>
</xsl:when>
<!-- this case is when there is in embedded schema in the same document elsewhere -->
<xslt:when
test="string-length( $document-uri ) = 0">
<xslt:apply-templates mode="dsdl:go"
select="//schold:*[@xml:id= $fragment-id ]
|id( $fragment-id)
| //schold:*[@id= $fragment-id ]" />
</xslt:when>
<!-- case where there is a fragment in another document (should be an iso: element) -->
<xsl:when
test="string-length( $fragment-id ) &gt; 0">
<xsl:variable name="theDocument_1"
select="document( $document-uri,/ )" />
<xsl:if test="not($theDocument_1)">
<xsl:message terminate="no">
<xsl:text>Unable to open referenced included file: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<!-- use for-each to rebase id() to $theDocument -->
<xsl:for-each select="$theDocument_1">
<xsl:variable name="theFragment_1"
select=" $theDocument_1//schold:*[@xml:id= $fragment-id ] |
id($fragment-id) |
$theDocument_1//schold:*[@id= $fragment-id ]" />
<xsl:if
test=" $theFragment_1/self::schold:schema ">
<xsl:message>
Schema error: Use include to include
fragments, not a whole schema
</xsl:message>
</xsl:if>
<xsl:if test="not($theFragment_1)">
<xsl:message terminate="no">
<xsl:text>Unable to locate id attribute: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<xsl:apply-templates
select=" $theFragment_1[1]" mode="dsdl:go" />
</xsl:for-each>
</xsl:when>
<!-- Case where there is no ID so we include the whole document -->
<!-- Experimental addition: include fragments of children -->
<xsl:otherwise>
<xsl:variable name="theDocument_2"
select="document( $document-uri,/ )" />
<xsl:variable name="theFragment_2"
select="$theDocument_2/iso:*" />
<xsl:variable name="theContainedFragments"
select="$theDocument_2/*/schold:* | $theDocument_2/*/xsl:* | $theDocument_2/*/xhtml:*" />
<xsl:if test="not($theDocument_2)">
<xsl:message terminate="no">
<xsl:text>Unable to open referenced included file: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<xsl:if
test=" $theFragment_2/self::schold:schema or $theContainedFragments/self::schold:schema">
<xsl:message>
Schema error: Use include to include
fragments, not a whole schema
</xsl:message>
</xsl:if>
<xsl:if
test="not($theFragment_2) and not ($theContainedFragments)">
<xsl:message terminate="no">
<xsl:text>Unable to locate id attribute: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<!-- If this were XLST 2, we could use
if ($theFragment) then $theFragment else $theContainedFragments
here (thanks to KN)
-->
<xsl:choose>
<xsl:when test=" $theFragment_2 ">
<xsl:apply-templates
select="$theFragment_2 " mode="dsdl:go" />
</xsl:when>
<xsl:otherwise>
<!-- WARNING! EXPERIMENTAL! Use at your own risk. This may be discontinued! -->
<xsl:apply-templates
select=" $theContainedFragments " mode="dsdl:go" />
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
<xsl:processing-instruction name="DSDL_INCLUDE_END">
<xsl:value-of select="@href" />
</xsl:processing-instruction>
</xsl:template>
<!-- =========================================================== -->
<!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
<!-- Part 5 - DataType Library Language - DTLL -->
<!-- Committee Draft Experimental support only -->
<!-- The <include> element may well be replaced by XInclude in -->
<!-- any final version. -->
<!-- =========================================================== -->
<xslt:template match="dtll:include" mode="dsdl:go">
<!-- Insert subschema -->
<xsl:variable name="document-uri"
select="substring-before(concat(@href,'#'), '#')" />
<xsl:variable name="fragment-id"
select="substring-after(@href, '#')" />
<xsl:processing-instruction name="DSDL_INCLUDE_START">
<xsl:value-of select="@href" />
</xsl:processing-instruction>
<xsl:choose>
<xsl:when test="not( $include-dtll = 'true' )">
<xslt:copy>
<xslt:copy-of select="@*" />
<xslt:apply-templates mode="dsdl:go" />
</xslt:copy>
</xsl:when>
<xsl:otherwise>
<xsl:choose>
<xsl:when
test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
<xsl:message>
Error: Impossible URL in DTLL include
</xsl:message>
</xsl:when>
<!-- this case is when there is in embedded schema in the same document elsewhere -->
<xslt:when
test="string-length( $document-uri ) = 0">
<xslt:apply-templates mode="dsdl:go"
select="//*[@xml:id= $fragment-id ] | id( $fragment-id)
| //*[@id= $fragment-id ]" />
</xslt:when>
<xsl:when
test="string-length( $fragment-id ) &gt; 0">
<xsl:variable name="theDocument_1"
select="document( $document-uri,/ )" />
<xsl:if test="not($theDocument_1)">
<xsl:message terminate="no">
<xsl:text>Unable to open referenced included file: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<!-- use for-each to rebase id() to $theDocument -->
<xsl:for-each select="$theDocument_1">
<xsl:variable name="theFragment_1"
select="$theDocument_1//*[@xml:id= $fragment-id ]
| id( $fragment-id )
| $theDocument_1//*[@id= $fragment-id ]" />
<xsl:if test="not($theFragment_1)">
<xsl:message terminate="no">
<xsl:text>Unable to locate id attribute: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<xsl:apply-templates
select=" $theFragment_1[1]" mode="dsdl:go" />
</xsl:for-each>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="theDocument_2"
select="document( $document-uri,/ )" />
<xsl:variable name="theFragment_2"
select="$theDocument_2/*" />
<xsl:if test="not($theDocument_2)">
<xsl:message terminate="no">
<xsl:text>Unable to open referenced included file: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<xsl:if test="not($theFragment_2)">
<xsl:message terminate="no">
<xsl:text>Unable to locate id attribute: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<xsl:apply-templates select="$theFragment_2 "
mode="dsdl:go" />
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
<xsl:processing-instruction name="DSDL_INCLUDE_END">
<xsl:value-of select="@href" />
</xsl:processing-instruction>
</xslt:template>
<!-- =========================================================== -->
<!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
<!-- Part 7 - Character Repertoire Description Language - CRDL -->
<!-- Final Committee Draft 2008-01-11 Experimental support only -->
<!-- =========================================================== -->
<xslt:template match="crdl:ref" mode="dsdl:go">
<!-- Insert subschema -->
<xsl:variable name="document-uri"
select="substring-before(concat(@href,'#'), '#')" />
<xsl:variable name="fragment-id"
select="substring-after(@href, '#')" />
<xsl:processing-instruction name="DSDL_INCLUDE_START">
<xsl:value-of select="@href" />
</xsl:processing-instruction>
<xsl:choose>
<xsl:when test="not( $include-crdl = 'true' )">
<xslt:copy>
<xslt:copy-of select="@*" />
<xslt:apply-templates mode="dsdl:go" />
</xslt:copy>
</xsl:when>
<xsl:otherwise>
<xsl:choose>
<xsl:when
test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
<xsl:message>
Error: Impossible URL in CRDL include
</xsl:message>
</xsl:when>
<!-- this case is when there is in embedded schema in the same document elsewhere -->
<xslt:when
test="string-length( $document-uri ) = 0">
<xslt:apply-templates mode="dsdl:go"
select="//*[@xml:id= $fragment-id ] | id( $fragment-id)
| //*[@id= $fragment-id ]" />
</xslt:when>
<xsl:when
test="string-length( $fragment-id ) &gt; 0">
<xsl:variable name="theDocument_1"
select="document( $document-uri,/ )" />
<xsl:if test="not($theDocument_1)">
<xsl:message terminate="no">
<xsl:text>Unable to open referenced included file: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<!-- use for-each to rebase id() to $theDocument -->
<xsl:for-each select="$theDocument_1">
<xsl:variable name="theFragment_1"
select="$theDocument_1//*[@xml:id= $fragment-id ]
| id( $fragment-id )
| $theDocument_1//*[@id= $fragment-id ]" />
<xsl:if test="not($theFragment_1)">
<xsl:message terminate="no">
<xsl:text>Unable to locate id attribute: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<xsl:apply-templates select=" $theFragment_1 "
mode="dsdl:go" />
</xsl:for-each>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="theDocument_2"
select="document( $document-uri,/ )" />
<xsl:variable name="theFragment_2"
select="$theDocument_2/*" />
<xsl:if test="not($theDocument_2)">
<xsl:message terminate="no">
<xsl:text>Unable to open referenced included file: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<xsl:if test="not($theFragment_2)">
<xsl:message terminate="no">
<xsl:text>Unable to locate id attribute: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<xsl:apply-templates select="$theFragment_2"
mode="dsdl:go" />
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
<xsl:processing-instruction name="DSDL_INCLUDE_END">
<xsl:value-of select="@href" />
</xsl:processing-instruction>
</xslt:template>
<!-- =========================================================== -->
<!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
<!-- Part 4 - Namespace-based Validation Dispatching Language - NVDL -->
<!-- Note: This does not include schemas referenced for -->
<!-- validation, it merely handles any simple XIncludes -->
<!-- =========================================================== -->
<!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
<!-- Part 8 - Document Schema Renaming Language - DSRL -->
<!-- Note: Final? Committee Draft Experimental support only -->
<!-- =========================================================== -->
<!-- XInclude support for id based references only, with 1 level -->
<!-- of fallback. -->
<!-- =========================================================== -->
<xslt:template mode="dsdl:go"
match="xi:include[@href][not(@parseType) or @parseType ='xml']">
<!-- Simple inclusions only here -->
<xsl:processing-instruction name="DSDL_INCLUDE_START">
<xsl:value-of select="@href" />
</xsl:processing-instruction>
<xsl:choose>
<xsl:when test="not( $include-xinclude = 'true' )">
<xslt:copy>
<xslt:copy-of select="@*" />
<xslt:apply-templates mode="dsdl:go" />
</xslt:copy>
</xsl:when>
<xsl:otherwise>
<xsl:choose>
<xsl:when test="contains( @href, '#')">
<xsl:message terminate="yes">
Fatal error: Xinclude href contains fragment
identifier #
</xsl:message>
</xsl:when>
<xsl:when test="contains( @xpointer, '(')">
<xsl:message terminate="yes">
Fatal error: Sorry, this software only
supports simple ids in XInclude xpointers
</xsl:message>
</xsl:when>
<xsl:when
test="string-length( @href ) = 0 and string-length( @xpointer ) = 0">
<xsl:message terminate="yes">
Fatal Error: Impossible URL in XInclude
include
</xsl:message>
</xsl:when>
<!-- this case is when there is in embedded schema in the same document elsewhere -->
<xslt:when test="string-length( @href ) = 0">
<xslt:apply-templates mode="dsdl:go"
select="//*[@xml:id= current()/@xpointer ] | id( @xpointer)
| //*[@id= current()/@xpointer ]" />
</xslt:when>
<xsl:when
test="string-length( @xpointer ) &gt; 0">
<xsl:variable name="theDocument_1"
select="document( @href,/ )" />
<xsl:variable name="theFragment_1"
select="$theDocument_1//*[@xml:id= current()/@xpointer ]
| $theDocument_1//*[@id= current()/@xpointer ]" />
<!-- removed
| $theDocument_1/id( @xpointer)
because it requires rebasing in XSLT1 and that would mess up the use of current()
-->
<!-- Allow one level of fallback, to another XInclude -->
<xsl:if test="not($theDocument_1)">
<xsl:choose>
<xsl:when test="xi:fallback">
<xsl:variable name="theDocument_2"
select="document( xi:fallback[1]/xi:include[not(@parseType)
or @parseType='xml']/@href,/ )" />
<xsl:variable name="theFragment_2"
select="$theDocument_2//*[@xml:id= current()/xi:fallback[1]/xi:include/@xpointer ]
| $theDocument_2//*[@id= current()/xi:fallback[1]/xi:include/@xpointer ]" />
<!-- removed
| $theDocument_2/id( xi:fallback[1]/xi:include/@xpointer)
because it id() would need rebasing in XSLT1 and that would mess up use of current()
-->
<xsl:if
test="not($theDocument_2)">
<xsl:message terminate="no">
<xsl:text>Unable to open referenced included file and fallback
file: </xsl:text>
<xsl:value-of
select="@href" />
</xsl:message>
</xsl:if>
</xsl:when>
<xsl:otherwise>
<xsl:message terminate="no">
<xsl:text>Unable to open referenced included file: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:otherwise>
</xsl:choose>
</xsl:if>
<xsl:apply-templates select=" $theFragment_1"
mode="dsdl:go" />
</xsl:when>
<!-- Document but no fragment specified -->
<xsl:otherwise>
<xsl:variable name="theDocument_3"
select="document( @href,/ )" />
<xsl:variable name="theFragment_3"
select="$theDocument_3/*" />
<xsl:if test="not($theDocument_3)">
<xsl:message terminate="no">
<xsl:text>Unable to open referenced included file: </xsl:text>
<xsl:value-of select="@href" />
</xsl:message>
</xsl:if>
<xsl:apply-templates select="$theFragment_3 "
mode="dsdl:go" />
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
<xsl:processing-instruction name="DSDL_INCLUDE_END">
<xsl:value-of select="@href" />
</xsl:processing-instruction>
</xslt:template>
<!-- =========================================================== -->
<!-- W3C XLink 1.1 embedded simple links -->
<!-- =========================================================== -->
<xslt:template
match="*[@xlink:href][not(parent::*[@xlink:type='complex'])]
[not(@xlink:type) or (@xlink:type='simple')]
[@xlink:show='embed']
[not(@xlink:actuate) or (@xlink:actuate='onLoad')]"
mode="dsdl:go" priority="1">
<xsl:variable name="document-uri"
select="substring-before(concat(@xlink:href,'#'), '#')" />
<xsl:variable name="fragment-id"
select="substring-after(@xlink:href, '#')" />
<xsl:processing-instruction name="DSDL_INCLUDE_START">
<xsl:value-of select="@xlink:href" />
</xsl:processing-instruction>
<xsl:choose>
<xsl:when test="not( $include-xlink = 'true' )">
<xslt:copy>
<xslt:copy-of select="@*" />
<xslt:apply-templates mode="dsdl:go" />
</xslt:copy>
</xsl:when>
<xsl:otherwise>
<xsl:choose>
<xsl:when
test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
<xsl:message>
Error: Impossible URL in XLink embedding
link
</xsl:message>
</xsl:when>
<!-- this case is when there is in embedded schema in the same document elsewhere -->
<xslt:when
test="string-length( $document-uri ) = 0">
<xslt:apply-templates mode="dsdl:go"
select="//*[@xml:id= $fragment-id ] | id( $fragment-id)
| //*[@id= $fragment-id ]" />
</xslt:when>
<xsl:when
test="string-length( $fragment-id ) &gt; 0">
<xsl:variable name="theDocument_1"
select="document( $document-uri,/ )" />
<xsl:if test="not($theDocument_1)">
<xsl:message terminate="no">
<xsl:text>Unable to open referenced included file: </xsl:text>
<xsl:value-of select="@xlink:href" />
</xsl:message>
</xsl:if>
<!-- use for-each to rebase id() to $theDocument -->
<xsl:for-each select="$theDocument_1">
<xsl:variable name="theFragment_1"
select="$theDocument_1//*[@xml:id= $fragment-id ]
| id( $fragment-id )
| $theDocument_1//*[@id= $fragment-id ]" />
<xsl:if test="not($theFragment_1)">
<xsl:message terminate="no">
<xsl:text>Unable to locate id attribute: </xsl:text>
<xsl:value-of select="@xlink:href" />
</xsl:message>
</xsl:if>
<xsl:apply-templates
select=" $theFragment_1[1]" mode="dsdl:go" />
</xsl:for-each>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="theDocument_2"
select="document( $document-uri,/ )" />
<xsl:variable name="theFragment_2"
select="$theDocument_2/*" />
<xsl:if test="not($theDocument_2)">
<xsl:message terminate="no">
<xsl:text>Unable to open referenced included file: </xsl:text>
<xsl:value-of select="@xlink:href" />
</xsl:message>
</xsl:if>
<xsl:if test="not($theFragment_2)">
<xsl:message terminate="no">
<xsl:text>Unable to locate id attribute: </xsl:text>
<xsl:value-of select="@xlink:href" />
</xsl:message>
</xsl:if>
<xsl:apply-templates select="$theFragment_2 "
mode="dsdl:go" />
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
<xsl:processing-instruction name="DSDL_INCLUDE_END">
<xsl:value-of select="@xlink:href" />
</xsl:processing-instruction>
</xslt:template>
<!-- ================================================================= -->
<!-- UTILITY TEMPLATES -->
<!-- ================================================================= -->
<!-- MESSAGE WHEN XPATH NOT WELL FORMED -->
<xsl:template name="sch-check:xpath-wf-message" >
<xsl:param name="string" />
<xsl:param name="subject" />
<xsl:variable name="xpath-wf-result">
<xsl:call-template name="sch-check:xpath-wf">
<xsl:with-param name="string" select=" $string " />
</xsl:call-template>
</xsl:variable>
<xsl:if test="string-length($xpath-wf-result) > 0">
<xsl:message><xsl:value-of select="$subject"/><xsl:value-of select="$xpath-wf-result" /></xsl:message>
</xsl:if>
</xsl:template>
<!-- XPATH WELL FORMED -->
<xsl:template name="sch-check:xpath-wf" >
<xsl:param name="string" />
<!-- This does some minimal checks to see if a string is well-formed XPath.
It checks
1) String is not empty,
2) equal number of open and close parens
3) equal number of left and right square brackets
4) if there is a predicate open immediately following a step separator
It does not check balancing. It does not check inside string literals in XPaths.
If there is no error, empty content is returned. If there is an error, it is given
as an error message. This is not localized yet.
-->
<xsl:variable name="stripped-contents">
<xsl:call-template name="sch-check:strip-strings" >
<xsl:with-param name="string" select=" $string " />
<xsl:with-param name="mode" select=" 0" />
</xsl:call-template>
</xsl:variable>
<xsl:variable name="paren-result">
<xsl:call-template name="sch-check:test-paren" >
<xsl:with-param name="string" select="$stripped-contents" />
<xsl:with-param name="count" select=" 0" />
</xsl:call-template>
</xsl:variable>
<xsl:variable name="sqb-result">
<xsl:call-template name="sch-check:test-sqb" >
<xsl:with-param name="string" select="$stripped-contents" />
<xsl:with-param name="count" select=" 0" />
</xsl:call-template>
</xsl:variable>
<xsl:choose>
<xsl:when test="string-length( normalize-space($string)) = 0"
>XPath error. No XPath.</xsl:when>
<xsl:when test="contains( $stripped-contents, '/[' )"
>XPath error. Missing location step. Suggestion: remove '/' before '['.
<xsl:value-of select=" normalize-space($string)"/></xsl:when>
<!-- not implemented yet
<xsl:when test=" count () mod 2 = 1"
>XPath syntax error. Odd number of apostrophe characters. Suggestion: check string termination and delimiting.
<xsl:value-of select=" normalize-space($string)"/></xsl:when>
<xsl:when test=" count ( ) mod 2 = 1"
>XPath syntax error. Odd number of quote characters. Suggestion: check string termination and delimiting.
<xsl:value-of select=" normalize-space($string)"/></xsl:when>
-->
<xsl:when test=" $paren-result > 0 "
>XPath syntax error. Unclosed parenthesis. Suggestion: add ')'.
<xsl:value-of select=" normalize-space($string)"/></xsl:when>
<xsl:when test=" $paren-result &lt; 0 "
>XPath syntax error. Extra close parenthesis. Suggestion: remove ')'.
<xsl:value-of select=" normalize-space($string)"/></xsl:when>
<xsl:when test=" $sqb-result > 0 "
>XPath syntax error. Unclosed left square bracket. Suggestion: add ']'.
<xsl:value-of select=" normalize-space($string)"/></xsl:when>
<xsl:when test=" $sqb-result &lt; 0 "
>XPath syntax error. Extra right square bracket. Suggestion: remove ']'.
<xsl:value-of select=" normalize-space($string)"/></xsl:when>
</xsl:choose>
</xsl:template>
<!-- STRIP XPATH STRINGS -->
<xsl:template name="sch-check:strip-strings">
<xsl:param name="string" />
<xsl:param name="mode" />
<!--
mode 0 = outside string
mode 1 = in double quote string
mode 2 = in single quote string
-->
<xsl:choose>
<xsl:when test=" string-length( $string) = 0" />
<xsl:when test="$mode = 1 ">
<xsl:choose>
<xsl:when test="starts-with( $string, '&quot;&quot;') " >
<xsl:call-template name="sch-check:strip-strings">
<xsl:with-param name="string" select=" substring ( $string, 3 )"/>
<xsl:with-param name="mode" select=" $mode" />
</xsl:call-template>
</xsl:when>
<xsl:when test="starts-with( $string, '&quot;') " >
<xsl:call-template name="sch-check:strip-strings">
<xsl:with-param name="string" select=" substring ( $string, 2 )"/>
<xsl:with-param name="mode" select=" 0 " />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="sch-check:strip-strings">
<xsl:with-param name="string" select=" substring ( $string, 2 )"/>
<xsl:with-param name="mode" select=" $mode " />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:when>
<xsl:when test="$mode = 2 ">
<xsl:choose>
<!-- doubled double quote or double apos is an escape -->
<xsl:when test="starts-with( $string, &quot;''&quot;) " >
<xsl:call-template name="sch-check:strip-strings">
<xsl:with-param name="string" select=" substring ( $string, 3 )"/>
<xsl:with-param name="mode" select=" $mode" />
</xsl:call-template>
</xsl:when>
<xsl:when test="starts-with( $string, &quot;'&quot; )" >
<xsl:call-template name="sch-check:strip-strings">
<xsl:with-param name="string" select=" substring ( $string, 2 )"/>
<xsl:with-param name="mode" select=" 0 " />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="sch-check:strip-strings">
<xsl:with-param name="string" select=" substring ( $string, 2 )"/>
<xsl:with-param name="mode" select=" $mode " />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:when>
<xsl:otherwise> <!-- mode = 0 -->
<xsl:choose>
<xsl:when test="starts-with( $string, '&quot;')" >
<xsl:call-template name="sch-check:strip-strings">
<xsl:with-param name="string" select=" substring ( $string, 2 )"/>
<xsl:with-param name="mode" select=" 1 " />
</xsl:call-template>
</xsl:when>
<xsl:when test="starts-with( $string, &quot;'&quot; )" >
<xsl:call-template name="sch-check:strip-strings">
<xsl:with-param name="string" select=" substring ( $string, 2 )"/>
<xsl:with-param name="mode" select=" 2 " />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="substring( $string, 1, 1)" />
<xsl:call-template name="sch-check:strip-strings">
<xsl:with-param name="string" select=" substring ( $string, 2 )"/>
<xsl:with-param name="mode" select=" $mode " />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- COUNT THE NUMBER OF UNMATCHED PARENTHESES -->
<!-- Limitation: Does not check balancing. -->
<xsl:template name="sch-check:test-paren">
<xsl:param name="string" />
<xsl:param name="count" />
<xsl:choose>
<xsl:when test=" string-length( $string) = 0">
<xsl:value-of select=" $count " />
</xsl:when>
<xsl:when test=" starts-with( $string, '(') ">
<xsl:call-template name="sch-check:test-paren">
<xsl:with-param name="string" select=" substring ( $string, 2 )" />
<xsl:with-param name="count" select=" $count + 1 " />
</xsl:call-template>
</xsl:when>
<xsl:when test=" starts-with( $string, ')') ">
<xsl:call-template name="sch-check:test-paren">
<xsl:with-param name="string" select=" substring ( $string, 2 )"/>
<xsl:with-param name="count" select="$count - 1 " />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="sch-check:test-paren">
<xsl:with-param name="string" select=" substring ( $string, 2 )"/>
<xsl:with-param name="count" select=" $count " />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- COUNT THE NUMBER OF SQUARE BRACKETS -->
<!-- Limitation: Does not check balancing. -->
<xsl:template name="sch-check:test-sqb">
<xsl:param name="string" />
<xsl:param name="count" />
<xsl:choose>
<xsl:when test=" string-length( $string) = 0">
<xsl:value-of select=" $count " />
</xsl:when>
<xsl:when test=" starts-with( $string, '[') ">
<xsl:call-template name="sch-check:test-sqb">
<xsl:with-param name="string" select=" substring ( $string, 2 )" />
<xsl:with-param name="count" select=" $count + 1 " />
</xsl:call-template>
</xsl:when>
<xsl:when test=" starts-with( $string, ']') ">
<xsl:call-template name="sch-check:test-sqb">
<xsl:with-param name="string" select=" substring ( $string, 2 )"/>
<xsl:with-param name="count" select="$count - 1 " />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="sch-check:test-sqb">
<xsl:with-param name="string" select=" substring ( $string, 2 )"/>
<xsl:with-param name="count" select=" $count " />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xslt:stylesheet>
\ No newline at end of file
<?xml version="1.0"?><?xar XSLT?>
<!--
OVERVIEW
ASCC/Schematron.com Skeleton Module for ISO Schematron (for XSLT2 systems)
ISO Schematron is a language for making assertion about the presence or absense
of patterns in XML documents. It is typically used for as a schema language, or
to augment existing schema languages, and to check business rules. It is very
powerful, yet quite simple: a developer only need know XPath and about five other
elements.
This is an open source implementation of ISO Schematron in XSLT. Although ISO does
not allow reference implementations which might compete with the text of the
standard, this code has been compiled by Rick Jelliffe, inventor of Schematron
and editor of the ISO standard; so developers can certainly use it as an
unofficial reference implementation for clarification.
This implementation is based on one by Oliver Becker. API documentation is
available separately; try www.schematron.com for this. Funding for this
stylesheet over the years has come from Topologi Pty. Ltd., Geotempo Ltd.,
and ASCC, Tapei.
There are two versions of this skeleton: one is tailored for XSLT1 processors
and the other is tailored for XSLT2 processors. Future versions of the
XSLT2 skeleton may support more features than that the XSLT 1 skeleton.
-->
<!--
Open Source Initiative OSI - The MIT License:Licensing
[OSI Approved License]
This source code was previously available under the zlib/libpng license.
Attribution is polite.
The MIT License
Copyright (c) 2000-2010 Rick Jellife and Academia Sinica Computing Centre, Taiwan.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<!--
TIPS
A tip for new users of Schematron: make your assertions contain positive messages
about what is expected, rather than error messages. For example, use the form
"An X should have a Y, because Z".
Another tip is that Schematron provides an
element <iso:ns> for declaring the namespaces and prefixes used in Xpaths in
attribute values; it does not extend the XML Namespaces mechanism: if a name
in an XPath has a prefix, there must be an <iso:ns> element for that prefix; if
a name in an XPath does not have a prefix, it is always in no namespace.
A tip for implementers of Schematron, either using this API or re-implementing it:
make the value of the diagnostics, flags and richer features available if possible;
Schematron has many of the optional richer features which, if implemented, provide
a compelling alternative approach to validation and business-rules checking compared
to other schema languages and programs.
If you create your own meta-stylesheet to override this one, it is a
good idea to have both in the same directory and to run the stylesheet
from that directory, as many XSLT implementations have ideosyncratic
handling of URLs: keep it simple.
-->
<!--
INVOCATION INFORMATION
The following parameters are available
phase NMTOKEN | "#ALL" (default) Select the phase for validation
allow-foreign "true" | "false" (default) Pass non-Schematron elements to the generated stylesheet
sch.exslt.imports semi-colon delimited string of filenames for some EXSLT implementations
message-newline "true" (default) | "false" Generate an extra newline at the end of messages
debug "true" | "false" (default) Debug mode lets compilation continue despite problems
attributes "true" | "false" (Autodetecting) Use only when the schema has no attributes as the context nodes
only-child-elements "true" | "false" (Autodetecting) Use only when the schema has no comments
or PI as the context nodes
langCode ISO language code language for skeleton errors, if available
terminate= yes | no | true | false | assert Terminate on the first failed assertion or successful report
Note whether any output at all is generated depends on the XSLT implementation.
The following parameters can be specified as Schematron variables in diagnostics, assertions and so on.
fileNameParameter string
fileDirParameter string
archiveNameParameter string In case of ZIP files
archiveDirParameter string In case of ZIP files
Experimental: USE AT YOUR OWN RISK
visit-text "true" "false" Also visist text nodes for context. WARNING: NON_STARDARD.
select-contents '' | 'key' | '//' Select different implementation strategies
Conventions: Meta-stylesheets that override this may use the following parameters
generate-paths=true|false generate the @location attribute with XPaths
full-path-notation = 1|2|3 select the notation for the full paths: 1=computer, 2=human, 3=obsolescent
diagnose= yes | no Add the diagnostics to the assertion test in reports
-->
<!--
XSLT VERSION SUPPORT
XSLT 1:
A schema using the standard XSLT 1 query binding will have a /schema/@queryBinding='xslt' or
nothing.
* Note: XT does not implement key() and will die if given it.
* Add all formal parameters to default templates
* Fix missing apply-templates from process-ns and add params back
EXSLT: Experimental support
A schema using the EXSLT query binding will have a /schema/@queryBinding='exslt'.
It is built on XSLT 1. After experience is gained, this binding is expected to be
formalized as part of ISO Schematron, which currently reserves the "exslt" name for this purpose.
Some EXSLT engines have the extra functions built-in. For these, there is no need to
provide library locations. For engines that require the functions, either hard code
them in this script or provide them on the command-line argument.
XSLT 2: Experimental support
A schema using the XSLT 2 query binding will have a /schema/@queryBinding='xslt2'.
This binding is expected to be formalized as part of ISO
Schematron, which currently reserves the "xslt2" name for this purpose.
The xsl:import-schema, xsl:key and xsl:function elements are allowed as top elements.
XPATH: Experimental support
A schema using the XPATH query binding will have a /schema/@queryBinding='xpath'.
It can run with XSLT 1 and is a strict superset of default ISO Schematron. After
experience is gained, this binding is expected to be formalized as part of ISO
Schematron, which currently reserves the "xpath" name for this purpose.
The intent of this query binding is to support minimal non-XSLT implementations of
Schematron that use simple XPath APIs. These not only have fewer functions available
than the XSLT version of XPath, but some of them do not support variables.
Consequently, in this binding, the <let> element and command-line variables passed
to the schema should not be used?
The xsl:import-schema element is not allowed.
-->
<!--
PROCESS INFORMATION
This stylesheet compiles a Schematron schema (*.sch) into XSLT code (*.xsl).
The generated XSLT code can then be run against an XML file (*.xml, etc) and
will produce validation results.
The output of validation results is performed using named templates (process-*).
These can be overridden easily by making a new XSLT stylesheet that imports this
stylesheet but has its own version of the relevant process-* templates. Several
of these invoking stylesheets are available: "iso_svrl.xsl", for example generates
ISO Schematron Validation Report Language format results.
In this version of the stylesheet, the ISO feature called "abstract patterns" is
implemented using macro processing: a prior XSLT stage to which converts uses
of abstract patterns into normal patterns. If you do not use abstract patterns,
it is not necessary to preprocess the schema.
To summarize, a basic process flow for some commandline processor is like this:
XSLT -input=xxx.sch -output=xxx.xsl -stylesheet=iso_schematron_skeleton.xsl
XSLT -input=document.xml -output=xxx-document.results -stylesheet=xxx.xsl
iso_svrl.xslt is an implementation of Schematron that can use this skeleton and
generate ISO SVRL reports. A process flow for some commandline processor would
be like this:
XSLT -input=xxx.sch -output=xxx.xsl -stylesheet=iso_svrl.xsl
XSLT -input=document.xml -output=xxx-document.results -stylesheet=xxx.xsl
It is not impossible that ultimately a third stage, to handle macro-preprocessing
and inclusion, might be necessary. (The trade-off is in making this XSLT more
complex compared to making the outer process more complex.)
This version has been developed to work with
Saxon 9
For versions for XSLT 1 processors, see www.xml.com
Please note that if you are using SAXON and JAXP, then you should use
System.setProperty("javax.xml.transform.TransformerFactory",
"net.sf.saxon.TransformerFactoryImpl");
rather than
System.setProperty("javax.xml.xpath.TransformerFactory",
"net.sf.saxon.TransformerFactoryImpl");
which is does not work, at least for the versions of SAXON we tried.
-->
<!--
VERSION INFORMATION
2010-04-14
* RJ Reorder call-template in exslt case only, report by BD
* Add command line parameter 'terminate' which will terminate on first failed
assert and (optionally) successful report.
2010-01-24
* RJ Allow let elements to have direct content instead of @value
2009-08020
* RJ Give better scoping to resolution of abstract rules
2009-07-07
* RJ Fix up warning on looking for @* on root TODO CHECK!!!!
2009-05-10
* RJ Fix up incorrect use of tunnel
2009-02-25
* RJ Fix up variable names so none are used twice in same template
2009-02-19
* RJ add experimental support for pattern/@documents
This takes an XPath that returns a sequence of strings, treats them as
relative URI references, and goes through these. It may need to be expanded
to allow absolute paths.
2008-09-19 RJ
* Add mode schematron-select-full-path and param full-path-notation
2008-08-19
* RJ Add experimental property element.
This acts like the diagnostics element. An attribute rule/@properties,
assert/@properties and report/@properties can contain a list of ids
which reference a /schema/proporties/property/@id. This is a property
which will be carried over to the output, eg SVRL. It can have @name,
and the value is @value or the contents. Properties on rules are
properties regardless of validation: they should apply to the subject
element. Properties on asserts and reports only make it through in the
negative case, at the moment, so they are really just a place to hold
structured info, eg. for diagnostics. The properties mechanism addresses
a bother with Schematron, that you have to post-process the document to
get any kind of structured data that might be nice in the output report.
2008-08-14
* RJ move all messages into localization strings, add langCode parameter,
named template to call external file in same directory as this xslt.
The file should be called sch-message-$langCode.xhtml ($langCode example "en")
2008-08-11
* TT report/@flag was missing
2008-08-06
* TT Top-level lets need to be implemented using xsl:param not xsl:variable
* TT xsl:param/@select must have XPath or not be specified
2008-08-04
* RJ add saxon namespace to output to allow extension functions
Version: 2008-07-28
* KH schematron-get-full-path-3 has [index] even on top step
Version: 2008-07-24
* RJ clean out commented out namespace handling code
* RJ allow schema/@queryBinding='xpath2' and warn if variables are
used
Version: 2008-07-14 update for XSLT2 and inclusion experiments
* RJ Clean up zero-length fragment test on include
* RJ Add experimental support for include containers
* RJ Add support for xsl:import-schema (request Paul Hermans)
* RJ Add support for xsl:function
* RJ For path generation, test for //iso:schema not just /iso:schema, for potential embedded Schematron support
* RJ Don't generate double error messages for old namespace elements
* RJ Experimental iso:rule/iso:title just kept as comment (bigger request Uche Ogbuji)
* RJ Fix bug that prevented including patterns in this (report Roger
Costello)
Version: 2007-10-17
Forked out version just to support SAXON 8 and potentially other XSLT2 processors.
* RJ use xsl:namespace element
* RJ use schold as namespace for old schematron, to prevent SAXON complaining
when validating the Schematron schema for Schematron
* RJ fix FULL-PATH for attributes
Version: 2007-07-19
Accept most changes in David Carlisle's fork, but continue as XSLT1 script:
http://dpcarlisle.blogspot.com/search/label/schematron
* DPC Remove "optimize" parameter
* DPC Add autodetecting optimize parameter attribute to skip checking attribute
context
* DPC Add autodetecting optimize parameter only-child-elements turn off checking for
comments and PIs
* DPC (Experimental: NON_STANDARD DANGER!) Add param visit-text to viist text
nodes too for context
* DPC Fix inclusion syntax to allow #
* DPC Priorities count up from 1000 not down from 4000 to allow more rules
* RJ Add new template for titles of schemas, with existing behaviour.
Override process-schema-title for custom processing of title
Version: 2007-04-04
* RJ debug mode param
* RJ alter mixed test to only test mixed branches, so the same document
could have old and new namespaces schemas in it, but each schema must
be distinct, just so as not to overconstrain things.
* KH zero-length include/@href is fatal error, but allow debug mode
* SB add hint on SAXON and JAXP
* DC generate-full-path-1 generates XLST1 code by default
Version: 2007-03-05
* AS Typo for EXSLT randome, improve comment
* KH get-schematron-full-path-2 needs to apply to attributes too
* DP document policy on extensions better
* DC use copy-of not copy for foreign elements
* DC add generate-path-2
* DC don't try to apply templates to attribute axis on attribute nodes, to
stop SAXON warning.
* RJ improve reporting of typos
Version: 2007-02-08
* KH Schematron fullpath implementation: @* handled twice and / missing
* KH Change stylesheetbody from named template to mode to allow implementers more flexibility.
Move process-ns to outside the stylesheet body.
* DP, FG, fix handling of xslt:key
* FG no iso:title/@class
* Experimental optimization 'visit-no-attributes'
* KH Experimental added schematron-get-full-path-2 which gives prefixed version for humans
* DC Move stylesheet/@version generation to after namespace handling
* DC, FG EXSLT namespace handling code
* FG add ref and commented code from FG's page on namespaces
* Start adding normalize-space() to parameter code
* Add a space between diagnostics
Version: 2007-01-22
* DP change = ($start) to = $start and =($phase) to =$phase
to run under Saxon 8.8j
* FG better title section using ( @id | iso:title)[last()]
* Default query language binding is "xslt" not "xslt1"
Version: 2007-01-19
* Simplify message newline code
* Remove termination and xpath appending to message options:
factor out as iso_schematron_terminator.xsl
* Comment out XSLT2 namespace fix temporarily
Version: 2007-01-18 (First beta candidate for comment)
* DC remove xml:space="preserve"
* FG improve comment on import statement
* DC improve comments on invocation section
* Add exploratory support for iso:schema[@queryBinding='xpath']
by allowing it and warning as lets are found
* Be strict about queryBinding spelling errors
* Extra comments on the different queryBindings
* KH Add option "message-paths" to generate XPath from output
* KH Add option "terminate" to halt with an error after the first assertion
* KH refactor paths in schematron-full-path
* Improve (?) namespace handling: no dummy attributes for prefix "xsl" generated
Version: 2007-01-15
* FG fix for calling templates
* Add formal parameters to default templates: may help XSLT 2
* Fix get-schematron-full-path
* Include skeleton1-6 is commented out by default
Version:2007-01-12 (Pre-beta release to Schematron-love-in maillist)
* Add many extra parameters to the process-* calls, so that almost
all the information in the schema can be provided to client programs.
Also, rearrange the parameters to fit in with the ISO schema, which
has "rich" and "linkable" attribute groups.
* Warn on diagnostics with no ID once only
* Improved path reporting, to handle for namespaces
* Add process-title dummy template for API
* Add command-line parameter allow-foreign (true|false) to suppress
warnings one foreign elements and pass them through to the generated
stylesheet
* remove legacy templates for the old ASCC namespace and no namespace,
and use an import statement instead. Much cleaner now!
* patterns use @id not @name
* titles can contain sub-elements
* start change iso:rule to allow attributes, PIs and comments
* the default process-* for inline elements add a leading and trailing
space, to reduce the chance of concatenation.
* add comments to make the generated code clearer
Version:2006-11-07 (ISO: first release private to schematron-love-in maillist for review)
* Duplicate pattern templates, for handling ISO namespace
* Add priority onto default and paragraph templates
* Add namespace checks
* Handle key in xsl namespace not iso
* Add include
* Improve namespace handling
* Preliminary XSLT2 and EXSLT support
* Refactor iso:schema for clarity
Version: 2003-05-26
* Fix bug with key
Version: 2003-04-16
* handle 1.6 let expressions
* make key use XSLT names, and allow anywhere
Version: 2001-06-13
* same skeleton now supports namespace or no namespace
* parameters to handlers updated for all 1.5 attributes
* diagnostic hints supported: command-line option diagnose=yes|no
* phases supported: command-line option phase=#ALL|...
* abstract rules
* compile-time error messages
* add utility routine generate-id-from-path
Contributors: Rick Jelliffe (original), Oliver Becker (architecture, XSLT2),
Miloslav Nic (diagnostic, phase, options), Ludwig Svenonius (abstract)
Uche Ogbuji (misc. bug fixes), Jim Ancona (SAXON workaround),
Francis Norton (generate-id-from-path), Robert Leftwich, Bryan Rasmussen,
Dave Pawson (include, fallback), Florent Georges (namespaces, exslt, attribute
context), Benoit Maisonny (attribute context), John Dumps (process-message newline),
Cliff Stanford (diagnostics and other newlines)
KNOWN TYPICAL LIMITATIONS:
* Don't use <iso:ns prefix="xsl" .../> with a namespace other than the standard
XSLT one. This would be a bizarre thing to do anyway.
* Don't use other prefixes for the XSLT namespace either; some implementations will
not handle it correctly.
EXTENSIONS:
ISO Schematron is designed as a framework with some standard query language
bindings. If you need to support other features, please do so safely by making
up your own @queryLanguage name: this makes it clear that your schema requires
special features. For example, default ISO Schematron does not support user
defined functions; so if you want to use the user defined function feature
in XSLT, you need to have a schema with some queryBinding attribute name like
"XSLT-with-my-functions" or whatever.
-->
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:axsl="http://www.w3.org/1999/XSL/TransformAlias"
xmlns:schold="http://www.ascc.net/xml/schematron"
xmlns:iso="http://purl.oclc.org/dsdl/schematron"
xmlns:exsl="http://exslt.org/common"
xmlns:xhtml="http://www.w3.org/1999/xhtml"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
extension-element-prefixes="exsl"
version="2.0"
>
<!-- This program implements ISO Schematron, except for abstract patterns
which require a preprocess.
-->
<xsl:namespace-alias stylesheet-prefix="axsl" result-prefix="xsl"/>
<!-- Category: top-level-element -->
<xsl:output method="xml" omit-xml-declaration="no" standalone="yes" indent="yes"/>
<xsl:param name="phase">
<xsl:choose>
<xsl:when test="//iso:schema/@defaultPhase">
<xsl:value-of select="//iso:schema/@defaultPhase"/>
</xsl:when>
<xsl:otherwise>#ALL</xsl:otherwise>
</xsl:choose>
</xsl:param>
<xsl:param name="allow-foreign">false</xsl:param>
<xsl:param name="message-newline">true</xsl:param>
<!-- DPC set to true if contexts should be checked on attribute nodes
defaults to true if there is any possibility that a context could match an attribute,
err on the side if caution, a context of *[.='@'] would cause this param to defualt to true
even though @ is in a string
-->
<xsl:param name="attributes">
<xsl:choose>
<xsl:when test="//iso:rule[contains(@context,'@') or contains(@context,'attribute')]">true</xsl:when>
<xsl:otherwise>false</xsl:otherwise>
</xsl:choose>
</xsl:param>
<!-- DPC set to true if contexts should be checked on just elements in the child axis
defaults to true if there is any possibility that a context could match an comment or PI
err on the side if caution, a context of *[.='('] would cause this param to defualt to true
even though ( is in a string, but node() comment() and processing-instruction() all have a (
-->
<xsl:param name="only-child-elements">
<xsl:choose>
<xsl:when test="//iso:rule[contains(@context,'(')]">true</xsl:when>
<xsl:otherwise>false</xsl:otherwise>
</xsl:choose>
</xsl:param>
<!-- DPC set to true if contexts should be checked on text nodes nodes (if only-child-elements is false)
THIS IS NON CONFORMANT BEHAVIOUR JUST FOR DISCUSSION OF A POSSIBLE CHANGE TO THE
SPECIFICATION. THIS PARAM SHOULD GO IF THE FINAL DECISION IS THAT THE SPEC DOES NOT CHANGE.
Always defaults to false
-->
<xsl:param name="visit-text" select="'false'"/>
<!-- DPC
When selecting contexts the specified behaviour is
@*|node()[not(self::text())]
The automatic settings may use
node()[not(self::text())]
@*|*
*
instead for schema for which they are equivalent.
If the params are set explictly the above may be used, and also either if
@*
@*|node()
in all cases the result may not be equivalent, for example if you specify no attributes and the schema
does have attribute contexts they will be silently ignored.
after testing it turns out that
node()[not(self::text())] is slower in saxon than *|comment()|processing-instruction()
which I find a bit surprising but anyway I'll use the longr faster version.
-->
<xsl:variable name="context-xpath">
<xsl:if test="$attributes='true' and parent::node() ">@*|</xsl:if>
<xsl:choose>
<xsl:when test="$only-child-elements='true'">*</xsl:when>
<xsl:when test="$visit-text='true'">node()</xsl:when>
<xsl:otherwise>*|comment()|processing-instruction()</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<!-- DPC if this is set to
'' use recursive templates to iterate over document tree,
'key' select all contexts with a key rather than walking the tree explictly in each mode
'//' select all contexts with // a key rather than walking the tree explictly in each mode (XSLT2 only)
-->
<xsl:param name="select-contexts" select="''"/>
<!-- e.g. saxon file.xml file.xsl "sch.exslt.imports=.../string.xsl;.../math.xsl" -->
<xsl:param name="sch.exslt.imports"/>
<xsl:param name="debug">false</xsl:param>
<!-- Set the language code for messages -->
<xsl:param name="langCode">default</xsl:param>
<!-- Set the default for schematron-select-full-path, i.e. the notation for svrl's @location-->
<xsl:param name="full-path-notation">1</xsl:param>
<xsl:param name="terminate">false</xsl:param>
<!-- Simple namespace check -->
<xsl:template match="/">
<xsl:if test="//schold:*[ancestor::iso:* or descendant::iso:*]">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">1</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:apply-templates />
</xsl:template>
<!-- ============================================================== -->
<!-- ISO SCHEMATRON SCHEMA ELEMENT -->
<!-- Not handled: Abstract patterns. A pre-processor is assumed. -->
<!-- ============================================================== -->
<!-- SCHEMA -->
<!-- Default uses XSLT 1 -->
<xsl:template match="iso:schema[not(@queryBinding) or @queryBinding='xslt'
or @queryBinding='xslt1' or @queryBinding='XSLT' or @queryBinding='XSLT1'
or @queryBinding='xpath']">
<xsl:if test="
@queryBinding='xslt1' or @queryBinding='XSLT' or @queryBinding='XSLT1'">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">2</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<axsl:stylesheet>
<xsl:apply-templates
select="iso:ns" />
<!-- Handle the namespaces before the version attribute: reported to help SAXON -->
<xsl:attribute name="version">1.0</xsl:attribute>
<xsl:apply-templates select="." mode="stylesheetbody"/>
<!-- was xsl:call-template name="stylesheetbody"/ -->
</axsl:stylesheet>
</xsl:template>
<!-- Using EXSLT with all modeles (except function module: not applicable) -->
<xsl:template match="iso:schema[@queryBinding='exslt']" priority="10">
<xsl:comment>This XSLT was automatically generated from a Schematron schema.</xsl:comment>
<axsl:stylesheet
xmlns:date="http://exslt.org/dates-and-times"
xmlns:dyn="http://exslt.org/dynamic"
xmlns:exsl="http://exslt.org/common"
xmlns:math="http://exslt.org/math"
xmlns:random="http://exslt.org/random"
xmlns:regexp="http://exslt.org/regular-expressions"
xmlns:set="http://exslt.org/sets"
xmlns:str="http://exslt.org/strings"
extension-element-prefixes="date dyn exsl math random regexp set str" >
<xsl:apply-templates
select="iso:ns" />
<!-- Handle the namespaces before the version attribute: reported to help SAXON -->
<xsl:attribute name="version">1.0</xsl:attribute>
<xsl:apply-templates select="." mode="stylesheetbody"/>
<!-- was xsl:call-template name="stylesheetbody"/ -->
</axsl:stylesheet>
</xsl:template>
<!-- Using XSLT 2 -->
<xsl:template
match="iso:schema[@queryBinding='xslt2' or @queryBinding ='xpath2']"
priority="10">
<axsl:stylesheet
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:saxon="http://saxon.sf.net/"
>
<xsl:apply-templates
select="iso:ns" />
<!-- Handle the namespaces before the version attribute: reported to help SAXON -->
<xsl:attribute name="version">2.0</xsl:attribute>
<xsl:apply-templates select="." mode="stylesheetbody"/>
<!-- was xsl:call-template name="stylesheetbody"/ -->
</axsl:stylesheet>
</xsl:template>
<!-- Uses unknown query language binding -->
<xsl:template match="iso:schema" priority="-1">
<xsl:message terminate="yes" ><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">3a</xsl:with-param></xsl:call-template>
<xsl:value-of select="@queryBinding"/>
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">3b</xsl:with-param></xsl:call-template></xsl:message>
</xsl:template>
<xsl:template match="*" mode="stylesheetbody">
<!--xsl:template name="stylesheetbody"-->
<xsl:comment>Implementers: please note that overriding process-prolog or process-root is
the preferred method for meta-stylesheets to use where possible. </xsl:comment><xsl:text>&#10;</xsl:text>
<!-- These parameters may contain strings with the name and directory of the file being
validated. For convenience, if the caller only has the information in a single string,
that string could be put in fileDirParameter. The archives parameters are available
for ZIP archives.
-->
<xsl:call-template name="iso:exslt.add.imports" /> <!-- RJ moved report BH -->
<axsl:param name="archiveDirParameter" />
<axsl:param name="archiveNameParameter" />
<axsl:param name="fileNameParameter" />
<axsl:param name="fileDirParameter" />
<axsl:variable name="document-uri"><axsl:value-of select="document-uri(/)" /></axsl:variable>
<xsl:text>&#10;&#10;</xsl:text><xsl:comment>PHASES</xsl:comment><xsl:text>&#10;</xsl:text>
<xsl:call-template name="handle-phase"/>
<xsl:text>&#10;&#10;</xsl:text><xsl:comment>PROLOG</xsl:comment><xsl:text>&#10;</xsl:text>
<xsl:call-template name="process-prolog"/>
<xsl:text>&#10;&#10;</xsl:text><xsl:comment>XSD TYPES FOR XSLT2</xsl:comment><xsl:text>&#10;</xsl:text>
<xsl:apply-templates mode="do-types" select="xsl:import-schema"/>
<xsl:text>&#10;&#10;</xsl:text><xsl:comment>KEYS AND FUNCTIONS</xsl:comment><xsl:text>&#10;</xsl:text>
<xsl:apply-templates mode="do-keys" select="xsl:key | xsl:function "/>
<xsl:text>&#10;&#10;</xsl:text><xsl:comment>DEFAULT RULES</xsl:comment><xsl:text>&#10;</xsl:text>
<xsl:call-template name="generate-default-rules" />
<xsl:text>&#10;&#10;</xsl:text><xsl:comment>SCHEMA SETUP</xsl:comment><xsl:text>&#10;</xsl:text>
<xsl:call-template name="handle-root"/>
<xsl:text>&#10;&#10;</xsl:text><xsl:comment>SCHEMATRON PATTERNS</xsl:comment><xsl:text>&#10;</xsl:text>
<xsl:apply-templates select="*[not(self::iso:ns)] " />
</xsl:template>
<xsl:template name="iso:exslt.add.imports">
<xsl:param name="imports" select="$sch.exslt.imports"/>
<xsl:choose>
<xsl:when test="contains($imports, ';')">
<axsl:import href="{ substring-before($imports, ';') }"/>
<xsl:call-template name="iso:exslt.add.imports">
<xsl:with-param name="imports" select="substring-after($imports, ';')"/>
</xsl:call-template>
</xsl:when>
<xsl:when test="$imports">
<axsl:import href="{ $imports }"/>
</xsl:when>
</xsl:choose>
</xsl:template>
<xsl:template name="handle-phase" >
<!-- This just tests that the phase exists -->
<xsl:if test="not(normalize-space( $phase ) = '#ALL')">
<xsl:if test="not(iso:phase[@id = normalize-space( $phase )])">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">4a</xsl:with-param></xsl:call-template>
<xsl:value-of select="normalize-space( $phase )"/>
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">4b</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
</xsl:if>
</xsl:template>
<xsl:template name="generate-default-rules">
<xsl:text>&#10;&#10;</xsl:text>
<xsl:comment>MODE: SCHEMATRON-SELECT-FULL-PATH</xsl:comment><xsl:text>&#10;</xsl:text>
<xsl:comment>This mode can be used to generate an ugly though full XPath for locators</xsl:comment><xsl:text>&#10;</xsl:text>
<axsl:template match="*" mode="schematron-select-full-path">
<xsl:choose>
<xsl:when test=" $full-path-notation = '1' ">
<!-- Use for computers, but rather unreadable for humans -->
<axsl:apply-templates select="." mode="schematron-get-full-path"/>
</xsl:when>
<xsl:when test=" $full-path-notation = '2' ">
<!-- Use for humans, but no good for paths unless namespaces are known out-of-band -->
<axsl:apply-templates select="." mode="schematron-get-full-path-2"/>
</xsl:when>
<xsl:when test=" $full-path-notation = '3' ">
<!-- Obsolescent. Use for humans, but no good for paths unless namespaces are known out-of-band -->
<axsl:apply-templates select="." mode="schematron-get-full-path-3"/>
</xsl:when>
<xsl:otherwise >
<!-- Use for computers, but rather unreadable for humans -->
<axsl:apply-templates select="." mode="schematron-get-full-path"/>
</xsl:otherwise>
</xsl:choose>
</axsl:template>
<xsl:text>&#10;&#10;</xsl:text>
<xsl:comment>MODE: SCHEMATRON-FULL-PATH</xsl:comment><xsl:text>&#10;</xsl:text>
<xsl:comment>This mode can be used to generate an ugly though full XPath for locators</xsl:comment><xsl:text>&#10;</xsl:text>
<axsl:template match="*" mode="schematron-get-full-path">
<axsl:apply-templates select="parent::*" mode="schematron-get-full-path"/>
<xsl:choose>
<xsl:when test="//iso:schema[@queryBinding='xslt2']">
<!-- XSLT2 syntax -->
<axsl:text>/</axsl:text>
<axsl:choose>
<axsl:when test="namespace-uri()=''"><axsl:value-of select="name()"/></axsl:when>
<axsl:otherwise>
<axsl:text>*:</axsl:text>
<axsl:value-of select="local-name()"/>
<axsl:text>[namespace-uri()='</axsl:text>
<axsl:value-of select="namespace-uri()"/>
<axsl:text>']</axsl:text>
</axsl:otherwise>
</axsl:choose>
<axsl:variable name="preceding" select=
"count(preceding-sibling::*[local-name()=local-name(current())
and namespace-uri() = namespace-uri(current())])" />
<axsl:text>[</axsl:text>
<axsl:value-of select="1+ $preceding"/>
<axsl:text>]</axsl:text>
</xsl:when>
<xsl:otherwise>
<!-- XSLT1 syntax -->
<axsl:text>/</axsl:text>
<axsl:choose>
<axsl:when test="namespace-uri()=''">
<axsl:value-of select="name()"/>
<axsl:variable name="p_1" select="1+
count(preceding-sibling::*[name()=name(current())])" />
<axsl:if test="$p_1&gt;1 or following-sibling::*[name()=name(current())]">
<xsl:text/>[<axsl:value-of select="$p_1"/>]<xsl:text/>
</axsl:if>
</axsl:when>
<axsl:otherwise>
<axsl:text>*[local-name()='</axsl:text>
<axsl:value-of select="local-name()"/>
<axsl:text>']</axsl:text>
<axsl:variable name="p_2" select="1+
count(preceding-sibling::*[local-name()=local-name(current())])" />
<axsl:if test="$p_2&gt;1 or following-sibling::*[local-name()=local-name(current())]">
<xsl:text/>[<axsl:value-of select="$p_2"/>]<xsl:text/>
</axsl:if>
</axsl:otherwise>
</axsl:choose>
</xsl:otherwise>
</xsl:choose>
</axsl:template>
<axsl:template match="@*" mode="schematron-get-full-path">
<xsl:choose>
<xsl:when test="//iso:schema[@queryBinding='xslt2']">
<!-- XSLT2 syntax -->
<axsl:apply-templates select="parent::*" mode="schematron-get-full-path"/>
<axsl:text>/</axsl:text>
<axsl:choose>
<axsl:when test="namespace-uri()=''">@<axsl:value-of select="name()"/></axsl:when>
<axsl:otherwise>
<axsl:text>@*[local-name()='</axsl:text>
<axsl:value-of select="local-name()"/>
<axsl:text>' and namespace-uri()='</axsl:text>
<axsl:value-of select="namespace-uri()"/>
<axsl:text>']</axsl:text>
</axsl:otherwise>
</axsl:choose>
</xsl:when>
<xsl:otherwise>
<!-- XSLT1 syntax -->
<axsl:text>/</axsl:text>
<axsl:choose>
<axsl:when test="namespace-uri()=''">@<axsl:value-of
select="name()"/></axsl:when>
<axsl:otherwise>
<axsl:text>@*[local-name()='</axsl:text>
<axsl:value-of select="local-name()"/>
<axsl:text>' and namespace-uri()='</axsl:text>
<axsl:value-of select="namespace-uri()"/>
<axsl:text>']</axsl:text>
</axsl:otherwise>
</axsl:choose>
</xsl:otherwise>
</xsl:choose>
</axsl:template>
<xsl:text>&#10;&#10;</xsl:text>
<xsl:comment>MODE: SCHEMATRON-FULL-PATH-2</xsl:comment>
<xsl:text>&#10;</xsl:text>
<xsl:comment>This mode can be used to generate prefixed XPath for humans</xsl:comment>
<xsl:text>&#10;</xsl:text>
<!--simplify the error messages by using the namespace prefixes of the
instance rather than the generic namespace-uri-styled qualification-->
<axsl:template match="node() | @*" mode="schematron-get-full-path-2">
<!--report the element hierarchy-->
<axsl:for-each select="ancestor-or-self::*">
<axsl:text>/</axsl:text>
<axsl:value-of select="name(.)"/>
<axsl:if test="preceding-sibling::*[name(.)=name(current())]">
<axsl:text>[</axsl:text>
<axsl:value-of
select="count(preceding-sibling::*[name(.)=name(current())])+1"/>
<axsl:text>]</axsl:text>
</axsl:if>
</axsl:for-each>
<!--report the attribute-->
<axsl:if test="not(self::*)">
<axsl:text/>/@<axsl:value-of select="name(.)"/>
</axsl:if>
</axsl:template>
<xsl:comment>MODE: SCHEMATRON-FULL-PATH-3</xsl:comment>
<xsl:text>&#10;</xsl:text>
<xsl:comment>This mode can be used to generate prefixed XPath for humans
(Top-level element has index)</xsl:comment>
<xsl:text>&#10;</xsl:text>
<!--simplify the error messages by using the namespace prefixes of the
instance rather than the generic namespace-uri-styled qualification-->
<axsl:template match="node() | @*" mode="schematron-get-full-path-3">
<!--report the element hierarchy-->
<axsl:for-each select="ancestor-or-self::*">
<axsl:text>/</axsl:text>
<axsl:value-of select="name(.)"/>
<axsl:if test="parent::*">
<axsl:text>[</axsl:text>
<axsl:value-of
select="count(preceding-sibling::*[name(.)=name(current())])+1"/>
<axsl:text>]</axsl:text>
</axsl:if>
</axsl:for-each>
<!--report the attribute-->
<axsl:if test="not(self::*)">
<axsl:text/>/@<axsl:value-of select="name(.)"/>
</axsl:if>
</axsl:template>
<xsl:text>&#10;&#10;</xsl:text>
<xsl:comment>MODE: GENERATE-ID-FROM-PATH </xsl:comment><xsl:text>&#10;</xsl:text>
<!-- repeatable-id maker derived from Francis Norton's. -->
<!-- use this if you need generate ids in separate passes,
because generate-id() is not guaranteed to produce the same
results each time. These ids are not XML names but closer to paths. -->
<axsl:template match="/" mode="generate-id-from-path"/>
<axsl:template match="text()" mode="generate-id-from-path">
<axsl:apply-templates select="parent::*" mode="generate-id-from-path"/>
<axsl:value-of select="concat('.text-', 1+count(preceding-sibling::text()), '-')"/>
</axsl:template>
<axsl:template match="comment()" mode="generate-id-from-path">
<axsl:apply-templates select="parent::*" mode="generate-id-from-path"/>
<axsl:value-of select="concat('.comment-', 1+count(preceding-sibling::comment()), '-')"/>
</axsl:template>
<axsl:template match="processing-instruction()" mode="generate-id-from-path">
<axsl:apply-templates select="parent::*" mode="generate-id-from-path"/>
<axsl:value-of
select="concat('.processing-instruction-', 1+count(preceding-sibling::processing-instruction()), '-')"/>
</axsl:template>
<axsl:template match="@*" mode="generate-id-from-path">
<axsl:apply-templates select="parent::*" mode="generate-id-from-path"/>
<axsl:value-of select="concat('.@', name())"/>
</axsl:template>
<axsl:template match="*" mode="generate-id-from-path" priority="-0.5">
<axsl:apply-templates select="parent::*" mode="generate-id-from-path"/>
<axsl:text>.</axsl:text>
<!--
<axsl:choose>
<axsl:when test="count(. | ../namespace::*) = count(../namespace::*)">
<axsl:value-of select="concat('.namespace::-',1+count(namespace::*),'-')"/>
</axsl:when>
<axsl:otherwise>
-->
<axsl:value-of
select="concat('.',name(),'-',1+count(preceding-sibling::*[name()=name(current())]),'-')"/>
<!--
</axsl:otherwise>
</axsl:choose>
-->
</axsl:template>
<xsl:text>&#10;&#10;</xsl:text>
<xsl:comment>MODE: GENERATE-ID-2 </xsl:comment><xsl:text>&#10;</xsl:text>
<!-- repeatable-id maker from David Carlisle. -->
<!-- use this if you need generate IDs in separate passes,
because generate-id() is not guaranteed to produce the same
results each time. These IDs are well-formed XML NMTOKENS -->
<axsl:template match="/" mode="generate-id-2">U</axsl:template>
<axsl:template match="*" mode="generate-id-2" priority="2">
<axsl:text>U</axsl:text>
<axsl:number level="multiple" count="*"/>
</axsl:template>
<axsl:template match="node()" mode="generate-id-2">
<axsl:text>U.</axsl:text>
<axsl:number level="multiple" count="*"/>
<axsl:text>n</axsl:text>
<axsl:number count="node()"/>
</axsl:template>
<axsl:template match="@*" mode="generate-id-2">
<axsl:text>U.</axsl:text>
<axsl:number level="multiple" count="*"/>
<axsl:text>_</axsl:text>
<axsl:value-of select="string-length(local-name(.))"/>
<axsl:text>_</axsl:text>
<axsl:value-of select="translate(name(),':','.')"/>
</axsl:template>
<xsl:comment>Strip characters</xsl:comment>
<axsl:template match="text()" priority="-1" />
</xsl:template>
<xsl:template name="handle-root">
<!-- Process the top-level element -->
<axsl:template match="/">
<xsl:call-template name="process-root">
<xsl:with-param
name="title" select="(@id | iso:title)[last()]"/>
<xsl:with-param name="version" select="'iso'" />
<xsl:with-param name="schemaVersion" select="@schemaVersion" />
<xsl:with-param name="queryBinding" select="@queryBinding" />
<xsl:with-param name="contents">
<xsl:apply-templates mode="do-all-patterns"/>
</xsl:with-param>
<!-- "Rich" properties -->
<xsl:with-param name="fpi" select="@fpi"/>
<xsl:with-param name="icon" select="@icon"/>
<xsl:with-param name="id" select="@id"/>
<xsl:with-param name="lang" select="@xml:lang"/>
<xsl:with-param name="see" select="@see" />
<xsl:with-param name="space" select="@xml:space" />
</xsl:call-template>
</axsl:template>
</xsl:template>
<!-- ============================================================== -->
<!-- ISO SCHEMATRON ELEMENTS -->
<!-- ============================================================== -->
<!-- ISO ACTIVE -->
<xsl:template match="iso:active">
<xsl:if test="not(@pattern)">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">5</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:if test="not(../../iso:pattern[@id = current()/@pattern])
and not(../../iso:include)">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">6a</xsl:with-param></xsl:call-template>
<xsl:value-of select="@pattern"/>
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">6b</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
</xsl:template>
<!-- ISO ASSERT and REPORT -->
<xsl:template match="iso:assert">
<xsl:if test="not(@test)">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">7</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:text>&#10;&#10; </xsl:text>
<xsl:comment>ASSERT <xsl:value-of select="@role" /> </xsl:comment><xsl:text>&#10;</xsl:text>
<axsl:choose>
<axsl:when test="{@test}"/>
<axsl:otherwise>
<xsl:call-template name="process-assert">
<xsl:with-param name="test" select="normalize-space(@test)" />
<xsl:with-param name="diagnostics" select="@diagnostics"/>
<xsl:with-param name="flag" select="@flag"/>
<xsl:with-param name="properties" select="@properties" />
<!-- "Rich" properties -->
<xsl:with-param name="fpi" select="@fpi"/>
<xsl:with-param name="icon" select="@icon"/>
<xsl:with-param name="id" select="@id"/>
<xsl:with-param name="lang" select="@xml:lang"/>
<xsl:with-param name="see" select="@see" />
<xsl:with-param name="space" select="@xml:space" />
<!-- "Linking" properties -->
<xsl:with-param name="role" select="@role" />
<xsl:with-param name="subject" select="@subject" />
</xsl:call-template>
</axsl:otherwise>
</axsl:choose>
</xsl:template>
<xsl:template match="iso:report">
<xsl:if test="not(@test)">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">8</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:text>&#10;&#10; </xsl:text>
<xsl:comment>REPORT <xsl:value-of select="@role" /> </xsl:comment><xsl:text>&#10;</xsl:text>
<axsl:if test="{@test}">
<xsl:call-template name="process-report">
<xsl:with-param name="test" select="normalize-space(@test)" />
<xsl:with-param name="diagnostics" select="@diagnostics"/>
<xsl:with-param name="flag" select="@flag"/>
<xsl:with-param name="properties" select="@properties" />
<!-- "Rich" properties -->
<xsl:with-param name="fpi" select="@fpi"/>
<xsl:with-param name="icon" select="@icon"/>
<xsl:with-param name="id" select="@id"/>
<xsl:with-param name="lang" select="@xml:lang"/>
<xsl:with-param name="see" select="@see" />
<xsl:with-param name="space" select="@xml:space" />
<!-- "Linking" properties -->
<xsl:with-param name="role" select="@role" />
<xsl:with-param name="subject" select="@subject" />
</xsl:call-template>
</axsl:if>
</xsl:template>
<!-- ISO DIAGNOSTIC -->
<!-- We use a mode here to maintain backwards compatability, instead of adding it
to the other mode.
-->
<xsl:template match="iso:diagnostic" mode="check-diagnostics">
<xsl:if test="not(@id)">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">9</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
</xsl:template>
<xsl:template match="iso:diagnostic" >
<xsl:call-template name="process-diagnostic">
<!-- "Rich" properties -->
<xsl:with-param name="fpi" select="@fpi"/>
<xsl:with-param name="icon" select="@icon"/>
<xsl:with-param name="id" select="@id"/>
<xsl:with-param name="lang" select="@xml:lang"/>
<xsl:with-param name="see" select="@see" />
<xsl:with-param name="space" select="@xml:space" />
</xsl:call-template>
</xsl:template>
<!-- ISO DIAGNOSTICS -->
<xsl:template match="iso:diagnostics" >
<xsl:apply-templates mode="check-diagnostics" select="*" />
</xsl:template>
<!-- ISO DIR -->
<xsl:template match="iso:dir" mode="text" >
<xsl:call-template name="process-dir">
<xsl:with-param name="value" select="@value"/>
</xsl:call-template>
</xsl:template>
<!-- ISO EMPH -->
<xsl:template match="iso:emph" mode="text">
<xsl:call-template name="process-emph"/>
</xsl:template>
<!-- ISO EXTENDS -->
<xsl:template match="iso:extends">
<xsl:if test="not(@rule)">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">10</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:if test="not(//iso:rule[@abstract='true'][@id= current()/@rule] )">
<xsl:message>
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">11a</xsl:with-param></xsl:call-template>
<xsl:value-of select="@rule"/>
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">11b</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:call-template name="IamEmpty" />
<xsl:choose>
<!-- prefer to use a locally declared rule -->
<xsl:when test="parent::*/parent::*/iso:rule[@id=current()/@rule]">
<xsl:apply-templates select="parent::*/parent::*/iso:rule[@id=current()/@rule]"
mode="extends"/>
</xsl:when>
<!-- otherwise use a global one: this is not in the 2006 standard -->
<xsl:when test="//iso:rule[@id=current()/@rule]">
<xsl:apply-templates select="//iso:rule[@id=current()/@rule]"
mode="extends"/>
</xsl:when>
</xsl:choose>
</xsl:template>
<!-- KEY: ISO has no KEY -->
<!-- NOTE:
Key has had a checkered history. Schematron 1.0 allowed it in certain places, but
users came up with a different location, which has now been adopted.
XT, the early XSLT processor, did not implement key and died when it was present.
So there are some versions of the Schematron skeleton for XT that strip out all
key elements.
Xalan (e.g. Xalan4C 1.0 and a Xalan4J) also had a funny. A fix involved making
a top-level parameter called $hiddenKey and then using that instead of matching
"key". This has been removed.
Keys and functions are the same mode, to allow their declaration to be mixed up.
-->
<xsl:template match="xsl:key" mode="do-keys" >
<xsl:if test="not(@name)">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">12</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:if test="not(@path) and not(@use)">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">13</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:choose>
<xsl:when test="parent::iso:rule ">
<xsl:call-template name="IamEmpty" />
<xsl:choose>
<xsl:when test="@path">
<axsl:key match="{../@context}" name="{@name}" use="{@path}"/>
</xsl:when>
<xsl:otherwise>
<axsl:key match="{../@context}" name="{@name}" use="{@use}"/>
</xsl:otherwise>
</xsl:choose>
</xsl:when>
<xsl:otherwise>
<xsl:if test="not(@match) ">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">14</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<axsl:key>
<xsl:copy-of select="@*"/>
</axsl:key>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="xsl:key " /><!-- swallow -->
<xsl:template match="iso:key " >
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">15</xsl:with-param></xsl:call-template></xsl:message>
</xsl:template>
<!-- XSL FUNCTION -->
<xsl:template match="xsl:function" mode="do-keys" >
<xsl:if test="not(@name)">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">16</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:copy-of select="."/>
</xsl:template>
<xsl:template match="xsl:function " /><!-- swallow -->
<xsl:template match="iso:function " >
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">17</xsl:with-param></xsl:call-template></xsl:message>
</xsl:template>
<!-- ISO INCLUDE -->
<!-- This is only a fallback. Include really needs to have been done before this as a separate pass.-->
<xsl:template match="iso:include[not(normalize-space(@href))]"
priority="1">
<xsl:if test=" $debug = 'false' ">
<xsl:message terminate="yes"><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">18</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
</xsl:template>
<!-- Extend the URI syntax to allow # refererences -->
<!-- Note that XSLT2 actually already allows # references, but we override them because it
looks unreliable -->
<xsl:template match="iso:include">
<xsl:variable name="document-uri" select="substring-before(concat(@href,'#'), '#')"/>
<xsl:variable name="fragment-id" select="substring-after(@href, '#')"/>
<xsl:choose>
<xsl:when test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0" >
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">19</xsl:with-param></xsl:call-template></xsl:message>
</xsl:when>
<xsl:when test="string-length( $fragment-id ) &gt; 0">
<xsl:variable name="theDocument_1" select="document( $document-uri,/ )" />
<xsl:variable name="theFragment_1" select="$theDocument_1//iso:*[@id= $fragment-id]" />
<xsl:if test="not($theDocument_1)">
<xsl:message terminate="no">
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">20a</xsl:with-param></xsl:call-template>
<xsl:value-of select="@href"/>
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">20b</xsl:with-param></xsl:call-template>
</xsl:message>
</xsl:if>
<xsl:if test=" $theFragment_1/self::iso:schema ">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">21</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:apply-templates select=" $theFragment_1"/>
</xsl:when>
<xsl:otherwise>
<!-- Import the top-level element if it is in schematron namespace,
or its children otherwise, to allow a simple containment mechanism. -->
<xsl:variable name="theDocument_2" select="document( $document-uri,/ )" />
<xsl:variable name="theFragment_2" select="$theDocument_2/iso:*" />
<xsl:variable name="theContainedFragments" select="$theDocument_2/*/iso:*" />
<xsl:if test="not($theDocument_2)">
<xsl:message terminate="no">
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">20a</xsl:with-param></xsl:call-template>
<xsl:value-of select="@href"/>
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">20b</xsl:with-param></xsl:call-template>
</xsl:message>
</xsl:if>
<xsl:if test=" $theFragment_2/self::iso:schema or $theContainedFragments/self::iso:schema">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">21</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:apply-templates select="$theFragment_2 | $theContainedFragments "/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- This is to handle the particular case of including patterns -->
<xsl:template match="iso:include" mode="do-all-patterns">
<xsl:variable name="document-uri" select="substring-before(concat(@href,'#'), '#')"/>
<xsl:variable name="fragment-id" select="substring-after(@href, '#')"/>
<xsl:choose>
<xsl:when test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0" >
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">19</xsl:with-param></xsl:call-template></xsl:message>
</xsl:when>
<xsl:when test="string-length( $fragment-id ) &gt; 0">
<xsl:variable name="theDocument_1" select="document( $document-uri,/ )" />
<xsl:variable name="theFragment_1" select="$theDocument_1//iso:*[@id= $fragment-id ]" />
<xsl:if test=" $theFragment_1/self::iso:schema ">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">21</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:apply-templates select=" $theFragment_1" mode="do-all-patterns"/>
</xsl:when>
<xsl:otherwise>
<!-- Import the top-level element if it is in schematron namespace,
or its children otherwise, to allow a simple containment mechanism. -->
<xsl:variable name="theDocument_2" select="document( $document-uri,/ )" />
<xsl:variable name="theFragment_2" select="$theDocument_2/iso:*" />
<xsl:variable name="theContainedFragments" select="$theDocument_2/*/iso:*" />
<xsl:if test=" $theFragment_2/self::iso:schema or $theContainedFragments/self::iso:schema">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">21</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:apply-templates select="$theFragment_2 | $theContainedFragments "
mode="do-all-patterns" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- XSL IMPORT-SCHEMA -->
<!-- Importing an XSD schema allows the variour type operations to be available. -->
<xsl:template match="xsl:import-schema" mode="do-types" >
<xsl:choose>
<xsl:when test="ancestor::iso:schema[@queryBinding='xslt2']">
<xsl:copy-of select="." />
</xsl:when>
<xsl:otherwise>
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">22</xsl:with-param></xsl:call-template></xsl:message>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- swallow -->
<xsl:template match="xsl:import-schema" />
<xsl:template match="iso:import-schema " >
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">23</xsl:with-param></xsl:call-template></xsl:message>
</xsl:template>
<!-- ISO LET -->
<xsl:template match="iso:let" >
<xsl:if test="ancestor::iso:schema[@queryBinding='xpath']">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">24</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:if test="ancestor::iso:schema[@queryBinding='xpath2']">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">25</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<!-- lets at the top-level are implemented as parameters unless they have contents -->
<xsl:choose>
<xsl:when test="parent::iso:schema">
<!-- it is an error to have an empty param/@select because an XPath is expected -->
<xsl:choose>
<xsl:when test="@value">
<axsl:param name="{@name}" select="{@value}">
<xsl:if test="string-length(@value) &gt; 0">
<xsl:attribute name="select"><xsl:value-of select="@value"/></xsl:attribute>
</xsl:if>
</axsl:param>
</xsl:when>
<xsl:otherwise>
<axsl:variable name="{@name}" >
<xsl:copy-of select="child::node()" />
</axsl:variable>
</xsl:otherwise>
</xsl:choose>
</xsl:when>
<xsl:otherwise>
<xsl:choose>
<xsl:when test="@value">
<axsl:variable name="{@name}" select="{@value}"/>
</xsl:when>
<xsl:otherwise>
<axsl:variable name="{@name}" >
<xsl:copy-of select="child::node()" />
</axsl:variable>
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- ISO NAME -->
<xsl:template match="iso:name" mode="text">
<xsl:if test="@path">
<xsl:call-template name="process-name">
<xsl:with-param name="name" select="concat('name(',@path,')')"/>
</xsl:call-template>
</xsl:if>
<xsl:if test="not(@path)">
<xsl:call-template name="process-name">
<xsl:with-param name="name" select="'name(.)'"/>
</xsl:call-template>
</xsl:if>
<xsl:call-template name="IamEmpty" />
</xsl:template>
<!-- ISO NS -->
<!-- Namespace handling is XSLT is quite tricky and implementation dependent -->
<xsl:template match="iso:ns">
<xsl:call-template name="handle-namespace" />
</xsl:template>
<!-- This template is just to provide the API hook -->
<xsl:template match="iso:ns" mode="do-all-patterns" >
<xsl:if test="not(@uri)">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">26</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:if test="not(@prefix)">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">27</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:call-template name="IamEmpty" />
<xsl:call-template name="process-ns" >
<xsl:with-param name="prefix" select="@prefix"/>
<xsl:with-param name="uri" select="@uri"/>
</xsl:call-template>
</xsl:template>
<!-- ISO P -->
<xsl:template match="iso:schema/iso:p " mode="do-schema-p" >
<xsl:call-template name="process-p">
<xsl:with-param name="class" select="@class"/>
<xsl:with-param name="icon" select="@icon"/>
<xsl:with-param name="id" select="@id"/>
<xsl:with-param name="lang" select="@xml:lang"/>
</xsl:call-template>
</xsl:template>
<xsl:template match="iso:pattern/iso:p " mode="do-pattern-p" >
<xsl:call-template name="process-p">
<xsl:with-param name="class" select="@class"/>
<xsl:with-param name="icon" select="@icon"/>
<xsl:with-param name="id" select="@id"/>
<xsl:with-param name="lang" select="@xml:lang"/>
</xsl:call-template>
</xsl:template>
<!-- Currently, iso:p in other position are not passed through to the API -->
<xsl:template match="iso:phase/iso:p" />
<xsl:template match="iso:p " priority="-1" />
<!-- ISO PATTERN -->
<xsl:template match="iso:pattern" mode="do-all-patterns">
<xsl:if test="($phase = '#ALL')
or (../iso:phase[@id= $phase]/iso:active[@pattern= current()/@id])">
<!-- Extension to allow validation in multiple documents -->
<xsl:choose>
<xsl:when test="string-length(normalize-space(@documents))=0" >
<xsl:call-template name="handle-pattern" />
</xsl:when>
<xsl:otherwise>
<axsl:variable name="thePath"
select="{@documents}"
as="xs:string*" />
<axsl:for-each select="$thePath">
<axsl:choose>
<axsl:when test="starts-with( ., 'http:') or starts-with(., 'file:' )
or starts-with(., '/')"><!-- try as absolute path -->
<axsl:for-each select="document(.)">
<xsl:call-template name="handle-pattern" />
</axsl:for-each>
</axsl:when>
<axsl:otherwise><!-- is relative path -->
<axsl:for-each select="document(concat( $document-uri , '/../', .))">
<xsl:call-template name="handle-pattern" />
</axsl:for-each>
</axsl:otherwise>
</axsl:choose>
</axsl:for-each>
</xsl:otherwise>
</xsl:choose>
</xsl:if>
</xsl:template>
<xsl:template name="handle-pattern">
<xsl:call-template name="process-pattern">
<!-- the following select statement assumes that
@id | iso:title returns node-set in document order:
we want the title if it is there, otherwise the @id attribute -->
<xsl:with-param name="name" select="(@id | iso:title )[last()]"/>
<xsl:with-param name="is-a" select="''"/>
<!-- "Rich" properties -->
<xsl:with-param name="fpi" select="@fpi"/>
<xsl:with-param name="icon" select="@icon"/>
<xsl:with-param name="id" select="@id"/>
<xsl:with-param name="lang" select="@xml:lang"/>
<xsl:with-param name="see" select="@see" />
<xsl:with-param name="space" select="@xml:space" />
</xsl:call-template>
<xsl:choose>
<!-- Use the key method -->
<xsl:when test="$select-contexts='key'">
<axsl:apply-templates select="key('M','M{count(preceding-sibling::*)}')" mode="M{count(preceding-sibling::*)}"/>
</xsl:when>
<!-- Use the // method -->
<xsl:when test="$select-contexts='//'">
<xsl:choose>
<xsl:when test="@document">
<!-- External document -->
<axsl:for-each select="{@document}">
<!-- same code as next block, but run from different context -->
<axsl:apply-templates mode="M{count(preceding-sibling::*)}" >
<xsl:attribute name="select">
<xsl:text>//(</xsl:text>
<xsl:for-each select="iso:rule/@context">
<xsl:text>(</xsl:text>
<xsl:value-of select="."/>
<xsl:text>)</xsl:text>
<xsl:if test="position()!=last()">|</xsl:if>
</xsl:for-each>
<xsl:text>)</xsl:text>
<xsl:if test="$visit-text='false'">[not(self::text())]</xsl:if>
</xsl:attribute>
</axsl:apply-templates>
</axsl:for-each>
</xsl:when>
<xsl:otherwise>
<axsl:apply-templates mode="M{count(preceding-sibling::*)}" >
<xsl:attribute name="select">
<xsl:text>//(</xsl:text>
<xsl:for-each select="iso:rule/@context">
<xsl:text>(</xsl:text>
<xsl:value-of select="."/>
<xsl:text>)</xsl:text>
<xsl:if test="position()!=last()">|</xsl:if>
</xsl:for-each>
<xsl:text>)</xsl:text>
<xsl:if test="$visit-text='false'">[not(self::text())]</xsl:if>
</xsl:attribute>
</axsl:apply-templates>
</xsl:otherwise>
</xsl:choose>
</xsl:when>
<!-- Use complete tree traversal -->
<xsl:when test="@document">
<!-- External document -->
<axsl:for-each select="{@document}">
<axsl:apply-templates select="." mode="M{count(preceding-sibling::*)}"/>
</axsl:for-each>
</xsl:when>
<xsl:otherwise>
<axsl:apply-templates select="/" mode="M{count(preceding-sibling::*)}"/>
</xsl:otherwise>
</xsl:choose>
<!--/xsl:if-->
</xsl:template>
<xsl:template match="iso:pattern[@abstract='true']">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">28</xsl:with-param></xsl:call-template></xsl:message>
</xsl:template>
<!-- Here is the template for the normal case of patterns -->
<xsl:template match="iso:pattern[not(@abstract='true')]">
<xsl:if test="($phase = '#ALL')
or (../iso:phase[@id= $phase]/iso:active[@pattern= current()/@id])">
<xsl:text>&#10;&#10;</xsl:text>
<xsl:comment>PATTERN <xsl:value-of select="@id" /> <xsl:value-of select="iso:title" /> </xsl:comment><xsl:text>&#10;</xsl:text>
<xsl:apply-templates />
<!-- DPC select-contexts test -->
<xsl:if test="not($select-contexts)">
<axsl:template match="text()" priority="-1" mode="M{count(preceding-sibling::*)}">
<!-- strip characters -->
</axsl:template>
<!-- DPC introduce context-xpath variable -->
<axsl:template match="@*|node()"
priority="-2"
mode="M{ count(preceding-sibling::*) }">
<axsl:apply-templates select="{$context-xpath}" mode="M{count(preceding-sibling::*)}"/>
</axsl:template>
</xsl:if>
</xsl:if>
</xsl:template>
<!-- ISO PHASE -->
<xsl:template match="iso:phase" >
<xsl:if test="not(@id)">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">29</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:apply-templates/>
</xsl:template>
<!-- PROPERTY Experiemental -->
<!-- We use a mode here to maintain backwards compatability, instead of adding it
to the other mode.
-->
<xsl:template match="iso:property" mode="check-property">
<xsl:if test="not(@id)">
<xsl:message>No property found with that ID</xsl:message>
</xsl:if>
</xsl:template>
<xsl:template match="iso:property" >
<xsl:call-template name="process-property">
<xsl:with-param name="id" select="@id"/>
<xsl:with-param name="name" select="@name"/>
<xsl:with-param name="value" select="@value" />
<xsl:with-param name="contents" select="*|text()" />
</xsl:call-template>
</xsl:template>
<!-- PROPERTIES experimental extension -->
<xsl:template match="iso:properties" >
<xsl:apply-templates mode="check-properties" select="property" />
</xsl:template>
<!-- ISO RULE -->
<xsl:template match="iso:rule[not(@abstract='true')] ">
<xsl:if test="not(@context)">
<xsl:message ><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">30</xsl:with-param></xsl:call-template></xsl:message>
<xsl:message terminate="yes" />
</xsl:if>
<xsl:text>&#10;&#10; </xsl:text>
<xsl:comment>RULE <xsl:value-of select="@id" /> </xsl:comment><xsl:text>&#10;</xsl:text>
<xsl:if test="iso:title">
<xsl:comment><xsl:value-of select="iso:title" /></xsl:comment>
</xsl:if>
<!-- DPC select-contexts -->
<xsl:if test="$select-contexts='key'">
<axsl:key name="M"
match="{@context}"
use="'M{count(../preceding-sibling::*)}'"/>
</xsl:if>
<!-- DPC priorities count up from 1000 not down from 4000 (templates in same priority order as before) -->
<axsl:template match="{@context}"
priority="{1000 + count(following-sibling::*)}" mode="M{count(../preceding-sibling::*)}">
<xsl:call-template name="process-rule">
<xsl:with-param name="context" select="@context"/>
<xsl:with-param name="properties" select="@properties" />
<!-- "Rich" properties -->
<xsl:with-param name="fpi" select="@fpi"/>
<xsl:with-param name="icon" select="@icon"/>
<xsl:with-param name="id" select="@id"/>
<xsl:with-param name="lang" select="@xml:lang"/>
<xsl:with-param name="see" select="@see" />
<xsl:with-param name="space" select="@xml:space" />
<!-- "Linking" properties -->
<xsl:with-param name="role" select="@role" />
<xsl:with-param name="subject" select="@subject" />
</xsl:call-template>
<xsl:apply-templates/>
<!-- DPC introduce context-xpath and select-contexts variables -->
<xsl:if test="not($select-contexts)">
<axsl:apply-templates select="{$context-xpath}" mode="M{count(../preceding-sibling::*)}"/>
</xsl:if>
</axsl:template>
</xsl:template>
<!-- ISO ABSTRACT RULE -->
<xsl:template match="iso:rule[@abstract='true'] " >
<xsl:if test=" not(@id)">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">31</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:if test="@context">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">32</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
</xsl:template>
<xsl:template match="iso:rule[@abstract='true']"
mode="extends" >
<xsl:if test="@context">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">33</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:apply-templates/>
</xsl:template>
<!-- ISO SPAN -->
<xsl:template match="iso:span" mode="text">
<xsl:call-template name="process-span">
<xsl:with-param name="class" select="@class"/>
</xsl:call-template>
</xsl:template>
<!-- ISO TITLE -->
<xsl:template match="iso:schema/iso:title" priority="1">
<xsl:call-template name="process-schema-title" />
</xsl:template>
<xsl:template match="iso:title" >
<xsl:call-template name="process-title" />
</xsl:template>
<!-- ISO VALUE-OF -->
<xsl:template match="iso:value-of" mode="text" >
<xsl:if test="not(@select)">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">34</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:call-template name="IamEmpty" />
<xsl:choose>
<xsl:when test="@select">
<xsl:call-template name="process-value-of">
<xsl:with-param name="select" select="@select"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise >
<xsl:call-template name="process-value-of">
<xsl:with-param name="select" select="'.'"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- ============================================================== -->
<!-- DEFAULT TEXT HANDLING -->
<!-- ============================================================== -->
<xsl:template match="text()" priority="-1" mode="do-keys">
<!-- strip characters -->
</xsl:template>
<xsl:template match="text()" priority="-1" mode="do-all-patterns">
<!-- strip characters -->
</xsl:template>
<xsl:template match="text()" priority="-1" mode="do-schema-p">
<!-- strip characters -->
</xsl:template>
<xsl:template match="text()" priority="-1" mode="do-pattern-p">
<!-- strip characters -->
</xsl:template>
<xsl:template match="text()" priority="-1">
<!-- Strip characters -->
</xsl:template>
<xsl:template match="text()" mode="text">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="text()" mode="inline-text">
<xsl:value-of select="."/>
</xsl:template>
<!-- ============================================================== -->
<!-- UTILITY TEMPLATES -->
<!-- ============================================================== -->
<xsl:template name="IamEmpty">
<xsl:if test="count( * )">
<xsl:message>
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">35a</xsl:with-param></xsl:call-template>
<xsl:value-of select="name(.)"/>
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">35b</xsl:with-param></xsl:call-template>
</xsl:message>
</xsl:if>
</xsl:template>
<xsl:template name="diagnosticsSplit">
<!-- Process at the current point the first of the <diagnostic> elements
referred to parameter str, and then recurse -->
<xsl:param name="str"/>
<xsl:variable name="start">
<xsl:choose>
<xsl:when test="contains($str,' ')">
<xsl:value-of select="substring-before($str,' ')"/>
</xsl:when>
<xsl:otherwise><xsl:value-of select="$str"/></xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:variable name="end">
<xsl:if test="contains($str,' ')">
<xsl:value-of select="substring-after($str,' ')"/>
</xsl:if>
</xsl:variable>
<!-- This works with all namespaces -->
<xsl:if test="not(string-length(normalize-space($start)) = 0)
and not(//iso:diagnostic[@id = $start])
and not(//schold:diagnostic[@id = $start])
and not(//diagnostic[@id = $start])">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">36a</xsl:with-param></xsl:call-template>
<xsl:value-of select="string($start)"/>
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">36b</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:if test="string-length(normalize-space($start)) > 0">
<xsl:text> </xsl:text>
<xsl:apply-templates
select="//iso:diagnostic[@id = $start ]
| //schold:diagnostic[@id = $start ]
| //diagnostic[@id= $start ]"/>
</xsl:if>
<xsl:if test="not($end='')">
<xsl:call-template name="diagnosticsSplit">
<xsl:with-param name="str" select="$end"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
<xsl:template name="propertiesSplit">
<!-- Process at the current point the first of the <property> elements
referred to parameter str, and then recurse -->
<xsl:param name="str"/>
<xsl:variable name="start">
<xsl:choose>
<xsl:when test="contains($str,' ')">
<xsl:value-of select="substring-before($str,' ')"/>
</xsl:when>
<xsl:otherwise><xsl:value-of select="$str"/></xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:variable name="end">
<xsl:if test="contains($str,' ')">
<xsl:value-of select="substring-after($str,' ')"/>
</xsl:if>
</xsl:variable>
<!-- This works with all namespaces -->
<xsl:if test="not(string-length(normalize-space($start)) = 0)
and not(//iso:property[@id = $start])">
<xsl:message><xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">36a</xsl:with-param></xsl:call-template>
<xsl:value-of select="string($start)"/>
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">36b</xsl:with-param></xsl:call-template></xsl:message>
</xsl:if>
<xsl:if test="string-length(normalize-space($start)) > 0">
<xsl:text> </xsl:text>
<xsl:apply-templates
select="//iso:property[@id = $start ] "/>
</xsl:if>
<xsl:if test="not($end='')">
<xsl:call-template name="propertiesSplit">
<xsl:with-param name="str" select="$end"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
<!-- It would be nice to use this but xsl:namespace does not
allow a fallback -->
<!--xsl:template name="handle-namespace" version="2.0">
<xsl:namespace name="{@prefix}" select="@uri">
</xsl:template-->
<xsl:template name="handle-namespace">
<!-- experimental code from http://eccnet.eccnet.com/pipermail/schematron-love-in/2006-June/000104.html -->
<!-- Handle namespaces differently for exslt systems, and default, only using XSLT1 syntax -->
<!-- For more info see http://fgeorges.blogspot.com/2007/01/creating-namespace-nodes-in-xslt-10.html -->
<xsl:choose>
<!-- The following code workds for XSLT2 -->
<xsl:when test="element-available('xsl:namespace')">
<xsl:namespace name="{@prefix}" select="@uri" />
</xsl:when>
<xsl:when use-when="not(element-available('xsl:namespace'))"
test="function-available('exsl:node-set')">
<xsl:variable name="ns-dummy-elements">
<xsl:element name="{@prefix}:dummy" namespace="{@uri}"/>
</xsl:variable>
<xsl:variable name="p" select="@prefix"/>
<xsl:copy-of select="exsl:node-set($ns-dummy-elements)
/*/namespace::*[local-name()=$p]"/>
</xsl:when>
<!-- end XSLT2 code -->
<xsl:when test="@prefix = 'xsl' ">
<!-- Do not generate dummy attributes with the xsl: prefix, as these
are errors against XSLT, because we presume that the output
stylesheet uses the xsl prefix. In any case, there would already
be a namespace declaration for the XSLT namespace generated
automatically, presumably using "xsl:".
-->
</xsl:when>
<xsl:when test="@uri = 'http://www.w3.org/1999/XSL/Transform'">
<xsl:message terminate="yes">
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">37a</xsl:with-param></xsl:call-template>
<xsl:value-of select="system-property('xsl:vendor')"/>
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">37b</xsl:with-param></xsl:call-template>
</xsl:message>
</xsl:when>
<xsl:otherwise>
<xsl:attribute name="{concat(@prefix,':dummy-for-xmlns')}" namespace="{@uri}" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- ============================================================== -->
<!-- UNEXPECTED ELEMENTS -->
<!-- ============================================================== -->
<xsl:template match="iso:*" priority="-2">
<xsl:message>
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">38a</xsl:with-param></xsl:call-template>
<xsl:value-of select="name(.)"/>
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">38b</xsl:with-param></xsl:call-template>
</xsl:message>
</xsl:template>
<!-- Swallow old namespace elements: there is an upfront test for them elsewhere -->
<xsl:template match="schold:*" priority="-2" />
<xsl:template match="*" priority="-3">
<xsl:choose>
<xsl:when test=" $allow-foreign = 'false' ">
<xsl:message>
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">39a</xsl:with-param></xsl:call-template>
<xsl:value-of select="name(.)"/>
<xsl:call-template name="outputLocalizedMessage" ><xsl:with-param name="number">39b</xsl:with-param></xsl:call-template>
</xsl:message>
</xsl:when>
<xsl:otherwise>
<xsl:copy-of select="." />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="iso:*" mode="text" priority="-2" />
<xsl:template match="*" mode="text" priority="-3">
<xsl:if test=" not( $allow-foreign = 'false') ">
<xsl:copy-of select="." />
</xsl:if>
</xsl:template>
<!-- ============================================================== -->
<!-- DEFAULT NAMED TEMPLATES -->
<!-- These are the actions that are performed unless overridden -->
<!-- ============================================================== -->
<xsl:template name="process-prolog"/>
<!-- no params -->
<xsl:template name="process-root">
<xsl:param name="contents"/>
<xsl:param name="id" />
<xsl:param name="version" />
<xsl:param name="schemaVersion" />
<xsl:param name="queryBinding" />
<xsl:param name="title" />
<!-- "Rich" parameters -->
<xsl:param name="fpi" />
<xsl:param name="icon" />
<xsl:param name="lang" />
<xsl:param name="see" />
<xsl:param name="space" />
<xsl:copy-of select="$contents"/>
</xsl:template>
<xsl:template name="process-assert">
<xsl:param name="test"/>
<xsl:param name="diagnostics" />
<xsl:param name="id" />
<xsl:param name="flag" />
<xsl:param name="properties" />
<!-- "Linkable" parameters -->
<xsl:param name="role"/>
<xsl:param name="subject"/>
<!-- "Rich" parameters -->
<xsl:param name="fpi" />
<xsl:param name="icon" />
<xsl:param name="lang" />
<xsl:param name="see" />
<xsl:param name="space" />
<xsl:call-template name="process-message">
<xsl:with-param name="pattern" select="$test"/>
<xsl:with-param name="role" select="$role"/>
</xsl:call-template>
<xsl:if test=" $terminate = 'yes' or $terminate = 'true' ">
<axsl:message terminate="yes">TERMINATING</axsl:message>
</xsl:if>
<xsl:if test=" $terminate = 'assert' ">
<axsl:message terminate="yes">TERMINATING</axsl:message>
</xsl:if>
</xsl:template>
<xsl:template name="process-report">
<xsl:param name="test"/>
<xsl:param name="diagnostics" />
<xsl:param name="id" />
<xsl:param name="flag" />
<xsl:param name="properties" />
<!-- "Linkable" parameters -->
<xsl:param name="role"/>
<xsl:param name="subject"/>
<!-- "Rich" parameters -->
<xsl:param name="fpi" />
<xsl:param name="icon" />
<xsl:param name="lang" />
<xsl:param name="see" />
<xsl:param name="space" />
<xsl:call-template name="process-message">
<xsl:with-param name="pattern" select="$test"/>
<xsl:with-param name="role" select="$role"/>
</xsl:call-template>
<xsl:if test=" $terminate = 'yes' or $terminate = 'true' ">
<axsl:message terminate="yes">TERMINATING</axsl:message>
</xsl:if>
</xsl:template>
<xsl:template name="process-diagnostic">
<xsl:param name="id" />
<!-- "Rich" parameters -->
<xsl:param name="fpi" />
<xsl:param name="icon" />
<xsl:param name="lang" />
<xsl:param name="see" />
<xsl:param name="space" />
<!-- We generate too much whitespace rather than risking concatenation -->
<axsl:text> </axsl:text>
<xsl:apply-templates mode="text"/>
<axsl:text> </axsl:text>
</xsl:template>
<xsl:template name="process-dir">
<xsl:param name="value" />
<!-- We generate too much whitespace rather than risking concatenation -->
<axsl:text> </axsl:text>
<xsl:apply-templates mode="inline-text"/>
<axsl:text> </axsl:text>
</xsl:template>
<xsl:template name="process-emph">
<!-- We generate too much whitespace rather than risking concatenation -->
<axsl:text> </axsl:text>
<xsl:apply-templates mode="inline-text"/>
<axsl:text> </axsl:text>
</xsl:template>
<xsl:template name="process-name">
<xsl:param name="name"/>
<!-- We generate too much whitespace rather than risking concatenation -->
<axsl:text> </axsl:text>
<axsl:value-of select="{$name}"/>
<axsl:text> </axsl:text>
</xsl:template>
<xsl:template name="process-ns" >
<!-- Note that process-ns is for reporting. The iso:ns elements are
independently used in the iso:schema template to provide namespace bindings -->
<xsl:param name="prefix"/>
<xsl:param name="uri" />
</xsl:template>
<xsl:template name="process-p">
<xsl:param name="id" />
<xsl:param name="class" />
<xsl:param name="icon" />
<xsl:param name="lang" />
</xsl:template>
<xsl:template name="process-pattern">
<xsl:param name="id" />
<xsl:param name="name" />
<xsl:param name="is-a" />
<!-- "Rich" parameters -->
<xsl:param name="fpi" />
<xsl:param name="icon" />
<xsl:param name="lang" />
<xsl:param name="see" />
<xsl:param name="space" />
</xsl:template>
<xsl:template name="process-rule">
<xsl:param name="context" />
<xsl:param name="id" />
<xsl:param name="flag" />
<xsl:param name="properties" />
<!-- "Linkable" parameters -->
<xsl:param name="role"/>
<xsl:param name="subject"/>
<!-- "Rich" parameters -->
<xsl:param name="fpi" />
<xsl:param name="icon" />
<xsl:param name="lang" />
<xsl:param name="see" />
<xsl:param name="space" />
</xsl:template>
<xsl:template name="process-span" >
<xsl:param name="class" />
<!-- We generate too much whitespace rather than risking concatenation -->
<axsl:text> </axsl:text>
<xsl:apply-templates mode="inline-text"/>
<axsl:text> </axsl:text>
</xsl:template>
<xsl:template name="process-title" >
<xsl:param name="class" />
<xsl:call-template name="process-p">
<xsl:with-param name="class">title</xsl:with-param>
</xsl:call-template>
</xsl:template>
<xsl:template name="process-schema-title" >
<xsl:param name="class" />
<xsl:call-template name="process-title">
<xsl:with-param name="class">schema-title</xsl:with-param>
</xsl:call-template>
</xsl:template>
<xsl:template name="process-value-of">
<xsl:param name="select"/>
<!-- We generate too much whitespace rather than risking concatenation -->
<axsl:text> </axsl:text>
<axsl:value-of select="{$select}"/>
<axsl:text> </axsl:text>
</xsl:template>
<!-- default output action: the simplest customization is to just override this -->
<xsl:template name="process-message">
<xsl:param name="pattern" />
<xsl:param name="role" />
<xsl:apply-templates mode="text"/>
<xsl:if test=" $message-newline = 'true'" >
<axsl:value-of select="string('&#10;')"/>
</xsl:if>
</xsl:template>
<!-- ===================================================== -->
<!-- Extension API: default rules -->
<!-- This allows the transmission of extra attributes on -->
<!-- rules, asserts, reports, diagnostics. -->
<!-- ===================================================== -->
<xsl:template name="process-property">
<xsl:param name="id" />
<xsl:param name="name"/>
<xsl:param name="value"/>
<xsl:param name="contents"/>
</xsl:template>
<!-- ===================================================== -->
<!-- Localization -->
<!-- ===================================================== -->
<!--
All messages generated by the skeleton during processing are localized.
(This does not apply to the text that comes from Schematron schemas
themselves, of course. Nor does it apply to messages in metastylesheets.)
Stylesheets have a parameter $langCode which can be used to select the
language code (e.g. from the command line)
The default value of $langCode is "default". When this is used, the
message text is taken from the strings below. We use XHTML, to provide
the namespace.
If the $langCode is somethign else, then the XSLT engine will try to
find a file called sch-messages-$langCode.xhtml in the same directory
as this stylesheet. Expect a fatal error if the file does not exist.
The file should contain XHTML elements, with the text translated.
The strings are located by using ids on each xhtml:p element.
The ids are formed by sch-message-$number-$langCode such as
sch-message-1-en
If there is no match in a localization file for a message, then the
default will be used. This allows this XSLT to be developed with new
messages added without requiring that any localization files be updated.
In many cases, there are actually two localization strings per message.
This happens whenever a message has an embedded value that is dynamically
generated (using <value-of>). Having two strings, preceding and following,
allows the translator to make idiomatic error messages. When there are
two message for a single message, they have numbers like 30a and 30b:
translators should check the reference to them in the XSLT above to
see what the dynamically generated information is.
-->
<xsl:template name="outputLocalizedMessage">
<xsl:param name="number" />
<xsl:choose>
<xsl:when test="string-length( $langCode ) = 0 or $langCode = 'default'" >
<xsl:value-of select='document("")//xhtml:p[@id=concat("sch-message-", $number)]/text()' />
</xsl:when>
<xsl:otherwise>
<xsl:variable name="localizationDocumentFilename" >
<xsl:value-of select="concat('sch-messages-', $langCode, '.xhtml')" />
</xsl:variable>
<xsl:variable name="theLocalizedMessage" >
<xsl:value-of select=
'document( $localizationDocumentFilename, /)//xhtml:p[@id=concat("sch-message-", $number, "-", $langCode)]/text()' />
</xsl:variable>
<xsl:choose>
<!-- if we found any external message with that id, use it -->
<xsl:when test=" string-length($theLocalizedMessage) &gt; 0">
<xsl:value-of select="$theLocalizedMessage" />
</xsl:when>
<xsl:otherwise>
<!-- otherwise use the default strings -->
<xsl:value-of select='document("")//xhtml:p[@id=concat("sch-message-", $number)]/text()' />
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xhtml:div class="ErrorMessages">
<!-- Where the error message contains dynamic information, the message has been split into an "a" and a "b" section.
This has been done even when the English does not require it, in order to accomodate different language grammars
that might position the dynamic information differently.
-->
<xhtml:p id="sch-message-1">Schema error: Schematron elements in old and new namespaces found</xhtml:p>
<xhtml:p id="sch-message-2">Schema error: in the queryBinding attribute, use 'xslt'</xhtml:p>
<xhtml:p id="sch-message-3a">Fail: This implementation of ISO Schematron does not work with schemas using the query language </xhtml:p>
<xhtml:p id="sch-message-3b"/>
<xhtml:p id="sch-message-4a">Phase Error: no phase has been defined with name </xhtml:p>
<xhtml:p id="sch-message-4b" />
<xhtml:p id="sch-message-5">Markup Error: no pattern attribute in &lt;active></xhtml:p>
<xhtml:p id="sch-message-6a">Reference Error: the pattern "</xhtml:p>
<xhtml:p id="sch-message-6b">" has been activated but is not declared</xhtml:p>
<xhtml:p id="sch-message-7">Markup Error: no test attribute in &lt;assert</xhtml:p>
<xhtml:p id="sch-message-8">Markup Error: no test attribute in &lt;report></xhtml:p>
<xhtml:p id="sch-message-9">Markup Error: no id attribute in &lt;diagnostic></xhtml:p>
<xhtml:p id="sch-message-10">Markup Error: no rule attribute in &lt;extends></xhtml:p>
<xhtml:p id="sch-message-11a">Reference Error: the abstract rule "</xhtml:p>
<xhtml:p id="sch-message-11b">" has been referenced but is not declared</xhtml:p>
<xhtml:p id="sch-message-12">Markup Error: no name attribute in &lt;key></xhtml:p>
<xhtml:p id="sch-message-13">Markup Error: no path or use attribute in &lt;key></xhtml:p>
<xhtml:p id="sch-message-14">Markup Error: no path or use attribute in &lt;key></xhtml:p>
<xhtml:p id="sch-message-15">Schema error: The key element is not in the ISO Schematron namespace. Use the XSLT namespace.</xhtml:p>
<xhtml:p id="sch-message-16">Markup Error: no name attribute in &lt;function></xhtml:p>
<xhtml:p id="sch-message-17">Schema error: The function element is not in the ISO Schematron namespace. Use the XSLT namespace.</xhtml:p>
<xhtml:p id="sch-message-18">Schema error: Empty href= attribute for include directive.</xhtml:p>
<xhtml:p id="sch-message-19">Error: Impossible URL in Schematron include</xhtml:p>
<xhtml:p id="sch-message-20a">Unable to open referenced included file: </xhtml:p>
<xhtml:p id="sch-message-20b" />
<xhtml:p id="sch-message-21">Schema error: Use include to include fragments, not a whole schema</xhtml:p>
<xhtml:p id="sch-message-22">Schema error: XSD schemas may only be imported if you are using the 'xslt2' query language binding</xhtml:p>
<xhtml:p id="sch-message-23">Schema error: The import-schema element is not available in the ISO Schematron namespace. Use the XSLT namespace.</xhtml:p>
<xhtml:p id="sch-message-24">Warning: Variables should not be used with the "xpath" query language binding.</xhtml:p>
<xhtml:p id="sch-message-25">Warning: Variables should not be used with the "xpath2" query language binding.</xhtml:p>
<xhtml:p id="sch-message-26">Markup Error: no uri attribute in &lt;ns></xhtml:p>
<xhtml:p id="sch-message-27">Markup Error: no prefix attribute in &lt;ns></xhtml:p>
<xhtml:p id="sch-message-28">Schema implementation error: This schema has abstract patterns, yet they are supposed to be preprocessed out already</xhtml:p>
<xhtml:p id="sch-message-29">Markup Error: no id attribute in &lt;phase></xhtml:p>
<xhtml:p id="sch-message-30">Markup Error: no context attribute in &lt;rule></xhtml:p>
<xhtml:p id="sch-message-31">Markup Error: no id attribute on abstract &lt;rule></xhtml:p>
<xhtml:p id="sch-message-32">Markup Error: (2) context attribute on abstract &lt;rule></xhtml:p>
<xhtml:p id="sch-message-33">Markup Error: context attribute on abstract &lt;rule></xhtml:p>
<xhtml:p id="sch-message-34">Markup Error: no select attribute in &lt;value-of></xhtml:p>
<xhtml:p id="sch-message-35a">Warning: </xhtml:p>
<xhtml:p id="sch-message-35b"> must not contain any child elements</xhtml:p>
<xhtml:p id="sch-message-36a">Reference error: A diagnostic "</xhtml:p>
<xhtml:p id="sch-message-36b">" has been referenced but is not declared</xhtml:p>
<xhtml:p id="sch-message-37a">Using the XSLT namespace with a prefix other than "xsl" in Schematron rules is not supported in this processor:</xhtml:p>
<xhtml:p id="sch-message-37b" />
<xhtml:p id="sch-message-38a">Error: unrecognized element in ISO Schematron namespace: check spelling and capitalization</xhtml:p>
<xhtml:p id="sch-message-38b" />
<xhtml:p id="sch-message-39a">Warning: unrecognized element </xhtml:p>
<xhtml:p id="sch-message-39b" />
</xhtml:div>
</xsl:stylesheet>
<?xml version="1.0" ?>
<!--
ISO_SVRL.xsl
Implementation of Schematron Validation Report Language from ISO Schematron
ISO/IEC 19757 Document Schema Definition Languages (DSDL)
Part 3: Rule-based validation Schematron
Annex D: Schematron Validation Report Language
This ISO Standard is available free as a Publicly Available Specification in PDF from ISO.
Also see www.schematron.com for drafts and other information.
This implementation of SVRL is designed to run with the "Skeleton" implementation
of Schematron which Oliver Becker devised. The skeleton code provides a
Schematron implementation but with named templates for handling all output;
the skeleton provides basic templates for output using this API, but client
validators can be written to import the skeleton and override the default output
templates as required. (In order to understand this, you must understand that
a named template such as "process-assert" in this XSLT stylesheet overrides and
replaces any template with the same name in the imported skeleton XSLT file.)
The other important thing to understand in this code is that there are different
versions of the Schematron skeleton. These track the development of Schematron through
Schematron 1.5, Schematron 1.6 and now ISO Schematron. One only skeleton must be
imported. The code has templates for the different skeletons commented out for
convenience. ISO Schematron has a different namespace than Schematron 1.5 and 1.6;
so the ISO Schematron skeleton has been written itself with an optional import
statement to in turn import the Schematron 1.6 skeleton. This will allow you to
validate with schemas from either namespace.
History:
2010-07-10
* MIT license
2010-04-14
* Add command line parameter 'terminate' which will terminate on first failed
assert and (optionally) successful report.
2009-03-18
* Fix atrribute with space "see " which generates wrong name in some processors
* rename allow-foreign to allow-rich
2009-02-19
* RJ add experimental non-standard attribute active-pattern/@document which says which
document is being validated from that point to the next similar. This is to cope with the
experimental multi-document validation in the XSLT2 skeleton.
2008-08-19
* RJ Experimental: Handle property elements. NOTE: signature change for process-assert,
process-report and process-rule to add property.
2008-08-11
* RJ Fix attribute/@select which saxon allows in XSLT 1
2008-08-07
* RJ Add output-encoding attribute to specify final encoding to use
* Alter allow-foreign functionality so that Schematron span, emph and dir elements make
it to the output, for better formatting and because span can be used to mark up
semantically interesting information embedded in diagnostics, which reduces the
need to extend SVRL itself
* Diagnostic-reference had an invalid attribute @id that duplicated @diagnostic: removed
2008-08-06
* RJ Fix invalid output: svrl:diagnostic-reference is not contained in an svrl:text
* Output comment to SVRL file giving filename if available (from command-line parameter)
2008-08-04
* RJ move sch: prefix to schold: prefix to prevent confusion (we want people to
be able to switch from old namespace to new namespace without changing the
sch: prefix, so it is better to keep that prefix completely out of the XSLT)
* Extra signature fixes (PH)
2008-08-03
* Repair missing class parameter on process-p
2008-07-31
* Update skeleton names
2007-04-03
* Add option generate-fired-rule (RG)
2007-02-07
* Prefer true|false for parameters. But allow yes|no on some old for compatability
* DP Diagnostics output to svrl:text. Diagnosis put out after assertion text.
* Removed non-SVRL elements and attributes: better handled as an extra layer that invokes this one
* Add more formal parameters
* Correct confusion between $schemaVersion and $queryBinding
* Indent
* Validate against RNC schemas for XSLT 1 and 2 (with regex tests removed)
* Validate output with UniversalTest.sch against RNC schema for ISO SVRL
2007-02-01
* DP. Update formal parameters of overriding named templates to handle more attributes.
* DP. Refactor handling of rich and linkable parameters to a named template.
2007-01-22
* DP change svrl:ns to svrl:ns-in-attribute-value
* Change default when no queryBinding from "unknown" to "xslt"
2007-01-18:
* Improve documentation
* KH Add command-line options to generate paths or not
* Use axsl:attribute rather than xsl:attribute to shut XSLT2 up
* Add extra command-line options to pass to the iso_schematron_skeleton
2006-12-01: iso_svrl.xsl Rick Jelliffe,
* update namespace,
* update phase handling,
* add flag param to process-assert and process-report & @ flag on output
2001: Conformance1-5.xsl Rick Jelliffe,
* Created, using the skeleton code contributed by Oliver Becker
-->
<!--
Open Source Initiative OSI - The MIT License:Licensing
[OSI Approved License]
This source code was previously available under the zlib/libpng license.
Attribution is polite.
The MIT License
Copyright (c) 2004-2010 Rick Jellife and Academia Sinica Computing Centre, Taiwan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<!-- Ideas nabbed from schematrons by Francis N., Miloslav N. and David C. -->
<!-- The command-line parameters are:
phase NMTOKEN | "#ALL" (default) Select the phase for validation
allow-foreign "true" | "false" (default) Pass non-Schematron elements and rich markup to the generated stylesheet
diagnose= true | false|yes|no Add the diagnostics to the assertion test in reports (yes|no are obsolete)
property= true | false Experimental: Add properties to the assertion test in reports
generate-paths=true|false|yes|no generate the @location attribute with XPaths (yes|no are obsolete)
sch.exslt.imports semi-colon delimited string of filenames for some EXSLT implementations
optimize "visit-no-attributes" Use only when the schema has no attributes as the context nodes
generate-fired-rule "true"(default) | "false" Generate fired-rule elements
terminate= yes | no | true | false | assert Terminate on the first failed assertion or successful report
Note: whether any output at all is generated depends on the XSLT implementation.
-->
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:axsl="http://www.w3.org/1999/XSL/TransformAlias"
xmlns:schold="http://www.ascc.net/xml/schematron"
xmlns:iso="http://purl.oclc.org/dsdl/schematron"
xmlns:svrl="http://purl.oclc.org/dsdl/svrl"
>
<!-- Select the import statement and adjust the path as
necessary for your system.
-->
<xsl:import href="iso_schematron_skeleton_for_saxon.xsl"/>
<!--
<xsl:import href="iso_schematron_skeleton_for_xslt1.xsl"/>
<xsl:import href="iso_schematron_skeleton.xsl"/>
<xsl:import href="skeleton1-5.xsl"/>
<xsl:import href="skeleton1-6.xsl"/>
-->
<xsl:param name="diagnose">true</xsl:param>
<xsl:param name="property">true</xsl:param>
<xsl:param name="phase">
<xsl:choose>
<!-- Handle Schematron 1.5 and 1.6 phases -->
<xsl:when test="//schold:schema/@defaultPhase">
<xsl:value-of select="//schold:schema/@defaultPhase"/>
</xsl:when>
<!-- Handle ISO Schematron phases -->
<xsl:when test="//iso:schema/@defaultPhase">
<xsl:value-of select="//iso:schema/@defaultPhase"/>
</xsl:when>
<xsl:otherwise>#ALL</xsl:otherwise>
</xsl:choose>
</xsl:param>
<xsl:param name="allow-foreign">false</xsl:param>
<xsl:param name="generate-paths">true</xsl:param>
<xsl:param name="generate-fired-rule">true</xsl:param>
<xsl:param name="optimize" />
<!-- e.g. saxon file.xml file.xsl "sch.exslt.imports=.../string.xsl;.../math.xsl" -->
<xsl:param name="sch.exslt.imports" />
<xsl:param name="terminate" >false</xsl:param>
<!-- Set the language code for messages -->
<xsl:param name="langCode">default</xsl:param>
<xsl:param name="output-encoding"/>
<!-- Set the default for schematron-select-full-path, i.e. the notation for svrl's @location-->
<xsl:param name="full-path-notation">1</xsl:param>
<!-- Experimental: If this file called, then must be generating svrl -->
<xsl:variable name="svrlTest" select="true()" />
<!-- ================================================================ -->
<xsl:template name="process-prolog">
<axsl:output method="xml" omit-xml-declaration="no" standalone="yes"
indent="yes">
<xsl:if test=" string-length($output-encoding) &gt; 0">
<xsl:attribute name="encoding"><xsl:value-of select=" $output-encoding" /></xsl:attribute>
</xsl:if>
</axsl:output>
</xsl:template>
<!-- Overrides skeleton.xsl -->
<xsl:template name="process-root">
<xsl:param name="title"/>
<xsl:param name="contents" />
<xsl:param name="queryBinding" >xslt1</xsl:param>
<xsl:param name="schemaVersion" />
<xsl:param name="id" />
<xsl:param name="version"/>
<!-- "Rich" parameters -->
<xsl:param name="fpi" />
<xsl:param name="icon" />
<xsl:param name="lang" />
<xsl:param name="see" />
<xsl:param name="space" />
<svrl:schematron-output title="{$title}" schemaVersion="{$schemaVersion}" >
<xsl:if test=" string-length( normalize-space( $phase )) &gt; 0 and
not( normalize-space( $phase ) = '#ALL') ">
<axsl:attribute name="phase">
<xsl:value-of select=" $phase " />
</axsl:attribute>
</xsl:if>
<axsl:comment><axsl:value-of select="$archiveDirParameter"/> &#xA0;
<axsl:value-of select="$archiveNameParameter"/> &#xA0;
<axsl:value-of select="$fileNameParameter"/> &#xA0;
<axsl:value-of select="$fileDirParameter"/></axsl:comment>
<xsl:apply-templates mode="do-schema-p" />
<xsl:copy-of select="$contents" />
</svrl:schematron-output>
</xsl:template>
<xsl:template name="process-assert">
<xsl:param name="test"/>
<xsl:param name="diagnostics" />
<xsl:param name="properties" />
<xsl:param name="id" />
<xsl:param name="flag" />
<!-- "Linkable" parameters -->
<xsl:param name="role"/>
<xsl:param name="subject"/>
<!-- "Rich" parameters -->
<xsl:param name="fpi" />
<xsl:param name="icon" />
<xsl:param name="lang" />
<xsl:param name="see" />
<xsl:param name="space" />
<svrl:failed-assert test="{$test}" >
<xsl:if test="string-length( $id ) &gt; 0">
<axsl:attribute name="id">
<xsl:value-of select=" $id " />
</axsl:attribute>
</xsl:if>
<xsl:if test=" string-length( $flag ) &gt; 0">
<axsl:attribute name="flag">
<xsl:value-of select=" $flag " />
</axsl:attribute>
</xsl:if>
<!-- Process rich attributes. -->
<xsl:call-template name="richParms">
<xsl:with-param name="fpi" select="$fpi"/>
<xsl:with-param name="icon" select="$icon"/>
<xsl:with-param name="lang" select="$lang"/>
<xsl:with-param name="see" select="$see" />
<xsl:with-param name="space" select="$space" />
</xsl:call-template>
<xsl:call-template name='linkableParms'>
<xsl:with-param name="role" select="$role" />
<xsl:with-param name="subject" select="$subject"/>
</xsl:call-template>
<xsl:if test=" $generate-paths = 'true' or $generate-paths= 'yes' ">
<!-- true/false is the new way -->
<axsl:attribute name="location">
<axsl:apply-templates select="." mode="schematron-select-full-path"/>
</axsl:attribute>
</xsl:if>
<svrl:text>
<xsl:apply-templates mode="text" />
</svrl:text>
<xsl:if test="$diagnose = 'yes' or $diagnose= 'true' ">
<!-- true/false is the new way -->
<xsl:call-template name="diagnosticsSplit">
<xsl:with-param name="str" select="$diagnostics"/>
</xsl:call-template>
</xsl:if>
<xsl:if test="$property= 'yes' or $property= 'true' ">
<!-- true/false is the new way -->
<xsl:call-template name="propertiesSplit">
<xsl:with-param name="str" select="$properties"/>
</xsl:call-template>
</xsl:if>
</svrl:failed-assert>
<xsl:if test=" $terminate = 'yes' or $terminate = 'true' ">
<axsl:message terminate="yes">TERMINATING</axsl:message>
</xsl:if>
<xsl:if test=" $terminate = 'assert' ">
<axsl:message terminate="yes">TERMINATING</axsl:message>
</xsl:if>
</xsl:template>
<xsl:template name="process-report">
<xsl:param name="id"/>
<xsl:param name="test"/>
<xsl:param name="diagnostics"/>
<xsl:param name="flag" />
<xsl:param name="properties"/>
<!-- "Linkable" parameters -->
<xsl:param name="role"/>
<xsl:param name="subject"/>
<!-- "Rich" parameters -->
<xsl:param name="fpi" />
<xsl:param name="icon" />
<xsl:param name="lang" />
<xsl:param name="see" />
<xsl:param name="space" />
<svrl:successful-report test="{$test}" >
<xsl:if test=" string-length( $id ) &gt; 0">
<axsl:attribute name="id">
<xsl:value-of select=" $id " />
</axsl:attribute>
</xsl:if>
<xsl:if test=" string-length( $flag ) &gt; 0">
<axsl:attribute name="flag">
<xsl:value-of select=" $flag " />
</axsl:attribute>
</xsl:if>
<!-- Process rich attributes. -->
<xsl:call-template name="richParms">
<xsl:with-param name="fpi" select="$fpi"/>
<xsl:with-param name="icon" select="$icon"/>
<xsl:with-param name="lang" select="$lang"/>
<xsl:with-param name="see" select="$see" />
<xsl:with-param name="space" select="$space" />
</xsl:call-template>
<xsl:call-template name='linkableParms'>
<xsl:with-param name="role" select="$role" />
<xsl:with-param name="subject" select="$subject"/>
</xsl:call-template>
<xsl:if test=" $generate-paths = 'yes' or $generate-paths = 'true' ">
<!-- true/false is the new way -->
<axsl:attribute name="location">
<axsl:apply-templates select="." mode="schematron-select-full-path"/>
</axsl:attribute>
</xsl:if>
<svrl:text>
<xsl:apply-templates mode="text" />
</svrl:text>
<xsl:if test="$diagnose = 'yes' or $diagnose='true' ">
<!-- true/false is the new way -->
<xsl:call-template name="diagnosticsSplit">
<xsl:with-param name="str" select="$diagnostics"/>
</xsl:call-template>
</xsl:if>
<xsl:if test="$property = 'yes' or $property='true' ">
<!-- true/false is the new way -->
<xsl:call-template name="propertiesSplit">
<xsl:with-param name="str" select="$properties"/>
</xsl:call-template>
</xsl:if>
</svrl:successful-report>
<xsl:if test=" $terminate = 'yes' or $terminate = 'true' ">
<axsl:message terminate="yes" >TERMINATING</axsl:message>
</xsl:if>
</xsl:template>
<xsl:template name="process-diagnostic">
<xsl:param name="id"/>
<!-- Rich parameters -->
<xsl:param name="fpi" />
<xsl:param name="icon" />
<xsl:param name="lang" />
<xsl:param name="see" />
<xsl:param name="space" />
<svrl:diagnostic-reference diagnostic="{$id}" >
<!--xsl:if test="string($id)">
<xsl:attribute name="id">
<xsl:value-of select="$id"/>
</xsl:attribute>
</xsl:if-->
<xsl:call-template name="richParms">
<xsl:with-param name="fpi" select="$fpi"/>
<xsl:with-param name="icon" select="$icon"/>
<xsl:with-param name="lang" select="$lang"/>
<xsl:with-param name="see" select="$see" />
<xsl:with-param name="space" select="$space" />
</xsl:call-template>
<xsl:text>
</xsl:text>
<xsl:apply-templates mode="text"/>
</svrl:diagnostic-reference>
</xsl:template>
<!-- Overrides skeleton -->
<xsl:template name="process-dir" >
<xsl:param name="value" />
<xsl:choose>
<xsl:when test=" $allow-foreign = 'true'">
<xsl:copy-of select="."/>
</xsl:when>
<xsl:otherwise>
<!-- We generate too much whitespace rather than risking concatenation -->
<axsl:text> </axsl:text>
<xsl:apply-templates mode="inline-text"/>
<axsl:text> </axsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- Overrides skeleton -->
<xsl:template name="process-emph" >
<xsl:param name="class" />
<xsl:choose>
<xsl:when test=" $allow-foreign = 'true'">
<xsl:copy-of select="."/>
</xsl:when>
<xsl:otherwise>
<!-- We generate too much whitespace rather than risking concatenation -->
<axsl:text> </axsl:text>
<xsl:apply-templates mode="inline-text"/>
<axsl:text> </axsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="process-rule">
<xsl:param name="id"/>
<xsl:param name="context"/>
<xsl:param name="flag"/>
<xsl:param name="properties" />
<!-- "Linkable" parameters -->
<xsl:param name="role"/>
<xsl:param name="subject"/>
<!-- "Rich" parameters -->
<xsl:param name="fpi" />
<xsl:param name="icon" />
<xsl:param name="lang" />
<xsl:param name="see" />
<xsl:param name="space" />
<xsl:if test=" $generate-fired-rule = 'true'">
<svrl:fired-rule context="{$context}" >
<xsl:if test=" string( $id )">
<xsl:attribute name="id">
<xsl:value-of select=" $id " />
</xsl:attribute>
</xsl:if>
<xsl:if test=" string-length( $role ) &gt; 0">
<xsl:attribute name="role">
<xsl:value-of select=" $role " />
</xsl:attribute>
</xsl:if>
<!-- Process rich attributes. -->
<xsl:call-template name="richParms">
<xsl:with-param name="fpi" select="$fpi"/>
<xsl:with-param name="icon" select="$icon"/>
<xsl:with-param name="lang" select="$lang"/>
<xsl:with-param name="see" select="$see" />
<xsl:with-param name="space" select="$space" />
</xsl:call-template>
<xsl:if test="$property= 'yes' or $property= 'true' ">
<!-- true/false is the new way -->
<xsl:call-template name="propertiesSplit">
<xsl:with-param name="str" select="$properties"/>
</xsl:call-template>
</xsl:if>
</svrl:fired-rule>
</xsl:if>
</xsl:template>
<xsl:template name="process-ns">
<xsl:param name="prefix"/>
<xsl:param name="uri"/>
<svrl:ns-prefix-in-attribute-values uri="{$uri}" prefix="{$prefix}" />
</xsl:template>
<xsl:template name="process-p">
<xsl:param name="icon"/>
<xsl:param name="class"/>
<xsl:param name="id"/>
<xsl:param name="lang"/>
<svrl:text>
<xsl:apply-templates mode="text"/>
</svrl:text>
</xsl:template>
<xsl:template name="process-pattern">
<xsl:param name="name"/>
<xsl:param name="id"/>
<xsl:param name="is-a"/>
<!-- "Rich" parameters -->
<xsl:param name="fpi" />
<xsl:param name="icon" />
<xsl:param name="lang" />
<xsl:param name="see" />
<xsl:param name="space" />
<svrl:active-pattern >
<axsl:attribute name="document">
<axsl:value-of select="document-uri(/)" />
</axsl:attribute><!-- If XSLT1 remove this -->
<xsl:if test=" string( $id )">
<axsl:attribute name="id">
<xsl:value-of select=" $id " />
</axsl:attribute>
</xsl:if>
<xsl:if test=" string( $name )">
<axsl:attribute name="name">
<xsl:value-of select=" $name " />
</axsl:attribute>
</xsl:if>
<xsl:call-template name='richParms'>
<xsl:with-param name="fpi" select="$fpi"/>
<xsl:with-param name="icon" select="$icon"/>
<xsl:with-param name="lang" select="$lang"/>
<xsl:with-param name="see" select="$see" />
<xsl:with-param name="space" select="$space" />
</xsl:call-template>
<!-- ?? report that this screws up iso:title processing -->
<xsl:apply-templates mode="do-pattern-p"/>
<!-- ?? Seems that this apply-templates is never triggered DP -->
<axsl:apply-templates />
</svrl:active-pattern>
</xsl:template>
<!-- Overrides skeleton -->
<xsl:template name="process-message" >
<xsl:param name="pattern"/>
<xsl:param name="role"/>
</xsl:template>
<!-- Overrides skeleton -->
<xsl:template name="process-span" >
<xsl:param name="class" />
<xsl:choose>
<xsl:when test=" $allow-foreign = 'true'">
<xsl:copy-of select="."/>
</xsl:when>
<xsl:otherwise>
<!-- We generate too much whitespace rather than risking concatenation -->
<axsl:text> </axsl:text>
<xsl:apply-templates mode="inline-text"/>
<axsl:text> </axsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- =========================================================================== -->
<!-- processing rich parameters. -->
<xsl:template name='richParms'>
<!-- "Rich" parameters -->
<xsl:param name="fpi" />
<xsl:param name="icon" />
<xsl:param name="lang" />
<xsl:param name="see" />
<xsl:param name="space" />
<!-- Process rich attributes. -->
<xsl:if test=" $allow-foreign = 'true'">
<xsl:if test="string($fpi)">
<axsl:attribute name="fpi">
<xsl:value-of select="$fpi "/>
</axsl:attribute>
</xsl:if>
<xsl:if test="string($icon)">
<axsl:attribute name="icon">
<xsl:value-of select="$icon"/>
</axsl:attribute>
</xsl:if>
<xsl:if test="string($see)">
<axsl:attribute name="see">
<xsl:value-of select="$see" />
</axsl:attribute>
</xsl:if>
</xsl:if>
<xsl:if test="string($space)">
<axsl:attribute name="xml:space">
<xsl:value-of select="$space"/>
</axsl:attribute>
</xsl:if>
<xsl:if test="string($lang)">
<axsl:attribute name="xml:lang">
<xsl:value-of select="$lang"/>
</axsl:attribute>
</xsl:if>
</xsl:template>
<!-- processing linkable parameters. -->
<xsl:template name='linkableParms'>
<xsl:param name="role"/>
<xsl:param name="subject"/>
<!-- ISO SVRL has a role attribute to match the Schematron role attribute -->
<xsl:if test=" string($role )">
<axsl:attribute name="role">
<xsl:value-of select=" $role " />
</axsl:attribute>
</xsl:if>
<!-- ISO SVRL does not have a subject attribute to match the Schematron subject attribute.
Instead, the Schematron subject attribute is folded into the location attribute -->
</xsl:template>
<!-- ===================================================== -->
<!-- Extension API: -->
<!-- This allows the transmission of extra attributes on -->
<!-- rules, asserts, reports, diagnostics. -->
<!-- ===================================================== -->
<!-- Overrides skeleton EXPERIMENTAL -->
<!-- The $contents is for static contents, the $value is for dynamic contents -->
<xsl:template name="process-property">
<xsl:param name="id"/>
<xsl:param name="name"/>
<xsl:param name="value"/>
<xsl:param name="contents"/>
<svrl:property id="{$id}" >
<xsl:if test="$name">
<xsl:attribute name="name"><xsl:value-of select="$name"/></xsl:attribute>
</xsl:if>
<xsl:if test="$value">
<xsl:attribute name="value"><xsl:value-of select="$value"/></xsl:attribute>
</xsl:if>
<xsl:if test="$contents">
<xsl:copy-of select="$contents"/>
</xsl:if>
</svrl:property>
</xsl:template>
</xsl:stylesheet>
/*-
* Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
*
* This file is part of CityDoctor2.
*
* CityDoctor2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CityDoctor2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CityDoctor2. If not, see <https://www.gnu.org/licenses/>.
*/
package de.hft.stuttgart.citydoctor2.check;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import de.hft.stuttgart.citydoctor2.CityDoctorValidation;
import de.hft.stuttgart.citydoctor2.datastructure.Building;
import de.hft.stuttgart.citydoctor2.datastructure.CityDoctorModel;
import de.hft.stuttgart.citydoctor2.parser.CityGmlParseException;
import de.hft.stuttgart.citydoctor2.parser.CityGmlParser;
import de.hft.stuttgart.citydoctor2.parser.InvalidGmlFileException;
/**
*
* @author Matthias Betz
*
*/
public class CheckerTest {
@Test
public void testSchematron() throws CityGmlParseException, InvalidGmlFileException {
ValidationConfiguration config = ValidationConfiguration.loadStandardValidationConfig();
config.getChecks().get(CheckId.C_SEM_BS_ROOF_NOT_FRAGMENTED).setEnabled(false);
config.setSchematronFilePath("src/test/resources/schematronTest.xml");
CityDoctorModel model = CityGmlParser.parseCityGmlFile(
"src/test/resources/SimpleSolid_SrefBS_SchematronTest.gml", config.getParserConfiguration());
Checker checker = new Checker(config, model);
checker.runChecks();
for (Building b : model.getBuildings()) {
if (!b.getGmlId().getGmlString().startsWith("UUID")) {
// if it starts with UUID the gml id was generated by citygml4j, but the file
// does not actually contain that gml id
// the schematron errors cannot be assigned to buildings without gml id, so they
// are excluded here
assertTrue(b.containsAnyError());
}
}
assertFalse(model.getGlobalErrors().isEmpty());
}
@Test
public void testChecker() throws CityGmlParseException, IOException, InterruptedException, InvalidGmlFileException {
String[] args = new String[6];
args[0] = "-in";
args[1] = "src/test/resources/QA-CS-CONCOMP.gml";
args[2] = "-xmlReport";
args[3] = "test.xml";
args[4] = "-pdfReport";
args[5] = "test.pdf";
CityDoctorValidation.main(args);
File f = new File("test.xml");
assertTrue(f.exists());
f.delete();
File f2 = new File("test.pdf");
assertTrue(f2.exists());
f2.delete();
}
@Test
public void testStreaming()
throws CityGmlParseException, IOException, InterruptedException, InvalidGmlFileException {
String[] args = new String[8];
args[0] = "-in";
args[1] = "src/test/resources/testarea.gml";
args[2] = "-config";
args[3] = "src/test/resources/testConfigWithStreaming.yml";
args[4] = "-pdfReport";
args[5] = "test.pdf";
args[6] = "-xmlReport";
args[7] = "test.xml";
CityDoctorValidation.main(args);
File f = new File("test.pdf");
assertTrue(f.exists());
f.delete();
File f2 = new File("test.xml");
assertTrue(f2.exists());
f2.delete();
}
}
/*-
* Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
*
* This file is part of CityDoctor2.
*
* CityDoctor2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CityDoctor2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CityDoctor2. If not, see <https://www.gnu.org/licenses/>.
*/
package de.hft.stuttgart.citydoctor2.check;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.junit.Test;
import de.hft.stuttgart.citydoctor2.datastructure.Building;
import de.hft.stuttgart.citydoctor2.datastructure.CityDoctorModel;
import de.hft.stuttgart.citydoctor2.datastructure.Geometry;
import de.hft.stuttgart.citydoctor2.datastructure.TransportationObject;
import de.hft.stuttgart.citydoctor2.parser.CityGmlParseException;
import de.hft.stuttgart.citydoctor2.parser.CityGmlParser;
import de.hft.stuttgart.citydoctor2.parser.InvalidGmlFileException;
import de.hft.stuttgart.citydoctor2.parser.ParserConfiguration;
public class FilterTest {
@Test
public void testFilterExclude() throws CityGmlParseException, IOException, InvalidGmlFileException {
ValidationConfiguration config = ValidationConfiguration
.loadValidationConfig("src/test/resources/testConfigWithExclude.yml");
CityDoctorModel model = CityGmlParser.parseCityGmlFile("src/test/resources/testarea.gml",
new ParserConfiguration(8, false));
Checker c = new Checker(config, model);
c.runChecks();
Building b = model.getBuildings().get(0);
Geometry geom = b.getGeometries().get(0);
assertFalse(geom.hasCheckResults());
TransportationObject to = model.getTransportation().get(0);
Geometry geom2 = to.getGeometries().get(0);
assertTrue(geom2.getPolygons().get(0).hasCheckResults());
}
@Test
public void testFilterInclude() throws CityGmlParseException, IOException, InvalidGmlFileException {
ValidationConfiguration config = ValidationConfiguration
.loadValidationConfig("src/test/resources/testConfigWithInclude.yml");
CityDoctorModel model = CityGmlParser.parseCityGmlFile("src/test/resources/testarea.gml",
new ParserConfiguration(8, false));
Checker c = new Checker(config, model);
c.runChecks();
Building b = model.getBuildings().get(0);
Geometry geom = b.getGeometries().get(0);
assertFalse(geom.hasCheckResults());
TransportationObject to = model.getTransportation().get(0);
Geometry geom2 = to.getGeometries().get(0);
assertTrue(geom2.getPolygons().get(0).hasCheckResults());
}
}
/*-
* Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
*
* This file is part of CityDoctor2.
*
* CityDoctor2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CityDoctor2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CityDoctor2. If not, see <https://www.gnu.org/licenses/>.
*/
package de.hft.stuttgart.citydoctor2.check;
import static org.junit.Assert.*;
import java.io.FileNotFoundException;
import org.junit.Test;
import de.hft.stuttgart.citydoctor2.datastructure.FeatureType;
public class ValidationConfigurationTest {
@Test
public void testLoadingConfig() throws FileNotFoundException {
String file = "src/test/resources/testConfig.yml";
ValidationConfiguration config = ValidationConfiguration.loadValidationConfig(file);
assertEquals(8, config.getNumberOfRoundingPlaces());
assertTrue(config.getChecks().containsKey(CheckId.C_GE_R_TOO_FEW_POINTS));
assertTrue(config.getChecks().get(CheckId.C_GE_P_NON_PLANAR).isEnabled());
assertNull(config.getFilter());
}
@Test
public void testLoadingConfigWithFilter() throws FileNotFoundException {
String file = "src/test/resources/testConfigWithFilter.yml";
ValidationConfiguration config = ValidationConfiguration.loadValidationConfig(file);
assertEquals(8, config.getNumberOfRoundingPlaces());
assertTrue(config.getChecks().containsKey(CheckId.C_GE_R_TOO_FEW_POINTS));
assertTrue(config.getChecks().get(CheckId.C_GE_P_NON_PLANAR).isEnabled());
FilterConfiguration filterConfig = config.getFilter();
assertNotNull(filterConfig);
ExcludeFilterConfiguration excludeFilter = filterConfig.getExclude();
assertNotNull(excludeFilter);
assertTrue(excludeFilter.getIds().contains("UUID-8972-kghf-asgv"));
assertTrue(excludeFilter.getIds().contains("UUID.*"));
assertTrue(excludeFilter.getTypes().contains(FeatureType.BUILDING));
assertTrue(excludeFilter.getTypes().contains(FeatureType.VEGETATION));
IncludeFilterConfiguration includeFilter = filterConfig.getInclude();
assertNotNull(includeFilter);
assertTrue(includeFilter.getIds().contains(".*"));
assertTrue(includeFilter.getTypes().contains(FeatureType.BUILDING));
assertTrue(includeFilter.getTypes().contains(FeatureType.VEGETATION));
}
}
/*-
* Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
*
* This file is part of CityDoctor2.
*
* CityDoctor2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CityDoctor2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CityDoctor2. If not, see <https://www.gnu.org/licenses/>.
*/
package de.hft.stuttgart.citydoctor2.checks;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import de.hft.stuttgart.citydoctor2.check.Check;
import de.hft.stuttgart.citydoctor2.check.CheckId;
import de.hft.stuttgart.citydoctor2.check.CheckResult;
import de.hft.stuttgart.citydoctor2.check.CheckType;
import de.hft.stuttgart.citydoctor2.check.Checkable;
import de.hft.stuttgart.citydoctor2.check.ErrorId;
import de.hft.stuttgart.citydoctor2.check.ResultStatus;
import de.hft.stuttgart.citydoctor2.datastructure.AbstractBuilding;
import de.hft.stuttgart.citydoctor2.datastructure.Building;
public class CheckContainerTest {
@Test
public void testExceptionCheck() {
Check c = new Check(CheckId.C_GE_P_HOLE_OUTSIDE) {
@Override
public List<Class<? extends Checkable>> getApplicableToClasses() {
return null;
}
@Override
public void check(AbstractBuilding ab) {
throw new RuntimeException();
}
@Override
public CheckType getType() {
return null;
}
@Override
public Check createNewInstance() {
return null;
}
};
CheckContainer cc = new CheckContainer(c);
AbstractBuilding ab = new Building();
cc.check(ab);
CheckResult cr = ab.getCheckResult(c.getCheckId());
assertEquals(ResultStatus.ERROR, cr.getResultStatus());
assertEquals(ErrorId.UNKNOWN_ERROR, cr.getError().getErrorId());
}
}
/*-
* Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
*
* This file is part of CityDoctor2.
*
* CityDoctor2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CityDoctor2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CityDoctor2. If not, see <https://www.gnu.org/licenses/>.
*/
package de.hft.stuttgart.citydoctor2.checks.geometry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import org.junit.Test;
import de.hft.stuttgart.citydoctor2.check.CheckResult;
import de.hft.stuttgart.citydoctor2.check.ErrorId;
import de.hft.stuttgart.citydoctor2.check.ResultStatus;
import de.hft.stuttgart.citydoctor2.datastructure.ConcretePolygon;
import de.hft.stuttgart.citydoctor2.datastructure.Geometry;
import de.hft.stuttgart.citydoctor2.datastructure.GeometryType;
import de.hft.stuttgart.citydoctor2.datastructure.LinearRing;
import de.hft.stuttgart.citydoctor2.datastructure.LinearRing.LinearRingType;
import de.hft.stuttgart.citydoctor2.datastructure.Lod;
import de.hft.stuttgart.citydoctor2.datastructure.Polygon;
import de.hft.stuttgart.citydoctor2.datastructure.Vertex;
/**
*
* @author Matthias Betz
*
*/
public class DuplicatePointsCheckTest {
@Test
public void testCheckOK() {
Polygon p = new ConcretePolygon();
LinearRing lr = new LinearRing(LinearRingType.EXTERIOR);
p.setExteriorRing(lr);
Vertex v0 = new Vertex(0, 0, 0);
Vertex v1 = new Vertex(1, 0, 0);
Vertex v2 = new Vertex(1, 1, 0);
lr.addVertex(v0);
lr.addVertex(v1);
lr.addVertex(v2);
lr.addVertex(v0);
DuplicatePointsCheck dpc = new DuplicatePointsCheck();
dpc.check(lr);
CheckResult cr = lr.getCheckResult(dpc);
assertSame(ResultStatus.OK, cr.getResultStatus());
}
@Test
public void testCheckConsecutivePointSame() {
Polygon p = new ConcretePolygon();
LinearRing lr = new LinearRing(LinearRingType.EXTERIOR);
p.setExteriorRing(lr);
Vertex v0 = new Vertex(0, 0, 0);
Vertex v1 = new Vertex(10, 0, 0);
Vertex v2 = new Vertex(10, 10, 0);
lr.addVertex(v0);
lr.addVertex(v1);
lr.addVertex(v2);
lr.addVertex(v2);
lr.addVertex(v0);
DuplicatePointsCheck dpc = new DuplicatePointsCheck();
dpc.check(lr);
CheckResult cr = lr.getCheckResult(dpc);
assertSame(ResultStatus.ERROR, cr.getResultStatus());
assertEquals(ErrorId.GE_R_CONSECUTIVE_POINTS_SAME, cr.getError().getErrorId());
}
@Test
public void testCheckSelfInt() {
Geometry geom = new Geometry(GeometryType.MULTI_SURFACE, Lod.LOD1);
Vertex v0 = new Vertex(1, 1, 1);
Vertex v1 = new Vertex(2, 2, 2);
Vertex v2 = new Vertex(3, 3, 3);
Polygon p = new ConcretePolygon();
p.setParent(geom);
LinearRing lr = new LinearRing(LinearRingType.EXTERIOR);
lr.setParent(p);
lr.addVertex(v0);
lr.addVertex(v1);
lr.addVertex(v2);
lr.addVertex(v1);
lr.addVertex(v0);
geom.updateEdges();
DuplicatePointsCheck dpc = new DuplicatePointsCheck();
dpc.check(lr);
CheckResult cr = lr.getCheckResult(dpc);
assertSame(ResultStatus.ERROR, cr.getResultStatus());
assertEquals(ErrorId.GE_R_SELF_INTERSECTION, cr.getError().getErrorId());
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment