001/*
002 * SPDX-FileCopyrightText: none
003 * SPDX-License-Identifier: CC0-1.0
004 */
005
006package gov.nist.secauto.metaschema.databind.io.xml;
007
008import gov.nist.secauto.metaschema.core.model.IBoundObject;
009import gov.nist.secauto.metaschema.core.model.util.XmlEventUtil;
010import gov.nist.secauto.metaschema.core.util.ObjectUtils;
011import gov.nist.secauto.metaschema.databind.io.AbstractProblemHandler;
012import gov.nist.secauto.metaschema.databind.model.IBoundDefinitionModelComplex;
013
014import org.apache.logging.log4j.LogManager;
015import org.apache.logging.log4j.Logger;
016
017import java.util.HashSet;
018import java.util.Set;
019
020import javax.xml.namespace.QName;
021import javax.xml.stream.events.Attribute;
022
023/**
024 * Handles problems identified in the parsed XML.
025 * <p>
026 * The default problem handler will report unknown attributes, and provide empty
027 * collections for multi-valued model items and default values for flags and
028 * single valued fields.
029 */
030public class DefaultXmlProblemHandler
031    extends AbstractProblemHandler
032    implements IXmlProblemHandler {
033  private static final Logger LOGGER = LogManager.getLogger(DefaultXmlProblemHandler.class);
034
035  private static final QName XSI_SCHEMA_LOCATION
036      = new QName("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation");
037  private static final Set<QName> IGNORED_QNAMES;
038
039  static {
040    IGNORED_QNAMES = new HashSet<>();
041    IGNORED_QNAMES.add(XSI_SCHEMA_LOCATION);
042  }
043
044  @Override
045  public boolean handleUnknownAttribute(
046      IBoundDefinitionModelComplex parentDefinition,
047      IBoundObject targetObject,
048      Attribute attribute,
049      IXmlParsingContext parsingContext) {
050    QName qname = attribute.getName();
051    // check if warning is needed
052    if (LOGGER.isWarnEnabled() && !IGNORED_QNAMES.contains(qname)) {
053      LOGGER.atWarn().log("Skipping unrecognized attribute '{}'{}.",
054          qname,
055          XmlEventUtil.generateLocationMessage(ObjectUtils.notNull(attribute.getLocation())));
056    }
057    // always ignore
058    return true;
059  }
060}