001/*
002 * Portions of this software was developed by employees of the National Institute
003 * of Standards and Technology (NIST), an agency of the Federal Government and is
004 * being made available as a public service. Pursuant to title 17 United States
005 * Code Section 105, works of NIST employees are not subject to copyright
006 * protection in the United States. This software may be subject to foreign
007 * copyright. Permission in the United States and in foreign countries, to the
008 * extent that NIST may hold copyright, to use, copy, modify, create derivative
009 * works, and distribute this software and its documentation without fee is hereby
010 * granted on a non-exclusive basis, provided that this notice and disclaimer
011 * of warranty appears in all copies.
012 *
013 * THE SOFTWARE IS PROVIDED 'AS IS' WITHOUT ANY WARRANTY OF ANY KIND, EITHER
014 * EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY
015 * THAT THE SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF
016 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND FREEDOM FROM
017 * INFRINGEMENT, AND ANY WARRANTY THAT THE DOCUMENTATION WILL CONFORM TO THE
018 * SOFTWARE, OR ANY WARRANTY THAT THE SOFTWARE WILL BE ERROR FREE.  IN NO EVENT
019 * SHALL NIST BE LIABLE FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, DIRECT,
020 * INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM,
021 * OR IN ANY WAY CONNECTED WITH THIS SOFTWARE, WHETHER OR NOT BASED UPON WARRANTY,
022 * CONTRACT, TORT, OR OTHERWISE, WHETHER OR NOT INJURY WAS SUSTAINED BY PERSONS OR
023 * PROPERTY OR OTHERWISE, AND WHETHER OR NOT LOSS WAS SUSTAINED FROM, OR AROSE OUT
024 * OF THE RESULTS OF, OR USE OF, THE SOFTWARE OR SERVICES PROVIDED HEREUNDER.
025 */
026
027package gov.nist.secauto.oscal.lib.profile.resolver.policy;
028
029import com.vladsch.flexmark.ast.InlineLinkNode;
030import com.vladsch.flexmark.util.sequence.BasedSequence;
031import com.vladsch.flexmark.util.sequence.CharSubSequence;
032
033import gov.nist.secauto.metaschema.model.common.metapath.format.IPathFormatter;
034import gov.nist.secauto.metaschema.model.common.metapath.item.IRequiredValueModelNodeItem;
035import gov.nist.secauto.metaschema.model.common.util.CustomCollectors;
036import gov.nist.secauto.oscal.lib.profile.resolver.support.IEntityItem;
037
038import org.apache.logging.log4j.LogManager;
039import org.apache.logging.log4j.Logger;
040
041import java.net.URI;
042import java.util.List;
043import java.util.Locale;
044
045import edu.umd.cs.findbugs.annotations.NonNull;
046
047public class AnchorReferencePolicy
048    extends AbstractCustomReferencePolicy<InlineLinkNode> {
049  private static final Logger LOGGER = LogManager.getLogger(AnchorReferencePolicy.class);
050
051  public AnchorReferencePolicy() {
052    super(IIdentifierParser.FRAGMENT_PARSER);
053  }
054
055  @SuppressWarnings("null")
056  @Override
057  protected List<IEntityItem.ItemType> getEntityItemTypes(@NonNull InlineLinkNode link) {
058    return List.of(
059        IEntityItem.ItemType.RESOURCE,
060        IEntityItem.ItemType.CONTROL,
061        IEntityItem.ItemType.GROUP,
062        IEntityItem.ItemType.PART);
063  }
064
065  @Override
066  public String getReferenceText(@NonNull InlineLinkNode link) {
067    return link.getUrl().toString();
068  }
069
070  @Override
071  public void setReferenceText(@NonNull InlineLinkNode link, @NonNull String newValue) {
072    link.setUrl(BasedSequence.of(newValue));
073  }
074
075  @Override
076  protected void handleUnselected(
077      @NonNull IRequiredValueModelNodeItem contextItem,
078      @NonNull InlineLinkNode link,
079      @NonNull IEntityItem item,
080      @NonNull ReferenceCountingVisitor.Context visitorContext) {
081    URI linkHref = URI.create(link.getUrl().toString());
082    URI sourceUri = item.getSource();
083
084    URI resolved = sourceUri.resolve(linkHref);
085    if (LOGGER.isTraceEnabled()) {
086      LOGGER.atTrace().log("At path '{}', remapping orphaned URI '{}' to '{}'",
087          contextItem.toPath(IPathFormatter.METAPATH_PATH_FORMATER),
088          linkHref.toString(),
089          resolved.toString());
090    }
091    link.setUrl(CharSubSequence.of(resolved.toString()));
092  }
093
094  @Override
095  protected boolean handleIndexMiss(
096      @NonNull IRequiredValueModelNodeItem contextItem,
097      @NonNull InlineLinkNode reference,
098      @NonNull List<IEntityItem.ItemType> itemTypes,
099      @NonNull String identifier,
100      @NonNull ReferenceCountingVisitor.Context visitorContext) {
101    if (LOGGER.isErrorEnabled()) {
102      LOGGER.atError().log(
103          "The anchor at '{}' should reference a {} identified by '{}', but the identifier was not found in the index.",
104          contextItem.toPath(IPathFormatter.METAPATH_PATH_FORMATER),
105          itemTypes.stream()
106              .map(en -> en.name().toLowerCase(Locale.ROOT))
107              .collect(CustomCollectors.joiningWithOxfordComma("or")),
108          identifier);
109    }
110    return true;
111  }
112
113  @Override
114  protected boolean handleIdentifierNonMatch(
115      @NonNull IRequiredValueModelNodeItem contextItem,
116      @NonNull InlineLinkNode reference,
117      @NonNull ReferenceCountingVisitor.Context visitorContext) {
118    if (LOGGER.isDebugEnabled()) {
119      LOGGER.atDebug().log("Ignoring URI '{}' at '{}'",
120          reference.getUrl().toStringOrNull(),
121          contextItem.toPath(IPathFormatter.METAPATH_PATH_FORMATER));
122    }
123
124    return true;
125  }
126}