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.selection;
028
029import gov.nist.secauto.metaschema.model.common.metapath.MetapathExpression;
030import gov.nist.secauto.metaschema.model.common.metapath.format.IPathFormatter;
031import gov.nist.secauto.metaschema.model.common.metapath.item.IRequiredValueAssemblyNodeItem;
032import gov.nist.secauto.metaschema.model.common.metapath.item.IRequiredValueModelNodeItem;
033import gov.nist.secauto.metaschema.model.common.util.ObjectUtils;
034import gov.nist.secauto.oscal.lib.model.CatalogGroup;
035import gov.nist.secauto.oscal.lib.model.Control;
036import gov.nist.secauto.oscal.lib.profile.resolver.support.IIndexer;
037
038import org.apache.commons.lang3.tuple.Pair;
039
040import java.util.Map;
041import java.util.concurrent.ConcurrentHashMap;
042
043import edu.umd.cs.findbugs.annotations.NonNull;
044import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
045
046public class ControlSelectionState implements IControlSelectionState {
047  private static final MetapathExpression GROUP_CHILDREN = MetapathExpression.compile("group|descendant::control");
048
049  @NonNull
050  private final IIndexer index;
051  @NonNull
052  private final IControlFilter filter;
053  @NonNull
054  private final Map<IRequiredValueModelNodeItem, SelectionState> itemSelectionState = new ConcurrentHashMap<>();
055
056  @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "provides intentional access to index state")
057  public ControlSelectionState(@NonNull IIndexer index, @NonNull IControlFilter filter) {
058    this.index = index;
059    this.filter = filter;
060  }
061
062  @Override
063  @SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "provides intentional access to index state")
064  public IIndexer getIndex() {
065    return index;
066  }
067
068  @NonNull
069  public IControlFilter getFilter() {
070    return filter;
071  }
072
073  @Override
074  public boolean isSelected(@NonNull IRequiredValueModelNodeItem item) {
075    return getSelectionState(item).isSelected();
076  }
077
078  @NonNull
079  protected SelectionState getSelectionState(@NonNull IRequiredValueModelNodeItem item) {
080    SelectionState retval = itemSelectionState.get(item);
081    if (retval == null) {
082      Object itemValue = ObjectUtils.requireNonNull(item.getValue());
083
084      if (itemValue instanceof Control) {
085        Control control = (Control) itemValue;
086
087        // get the parent control if the parent is a control
088        IRequiredValueAssemblyNodeItem parentItem = ObjectUtils.requireNonNull(item.getParentContentNodeItem());
089        Object parentValue = parentItem.getValue();
090        Control parentControl = parentValue instanceof Control ? (Control) parentValue : null;
091
092        boolean defaultMatch = false;
093        if (parentControl != null) {
094          SelectionState parentSelectionState = getSelectionState(parentItem);
095          defaultMatch = parentSelectionState.isSelected() && parentSelectionState.isWithChildren();
096        }
097
098        Pair<Boolean, Boolean> matchResult = getFilter().match(control, defaultMatch);
099        boolean selected = matchResult.getLeft();
100        boolean withChildren = matchResult.getRight();
101
102        retval = new SelectionState(selected, withChildren);
103
104      } else if (itemValue instanceof CatalogGroup) {
105        // get control selection status
106        boolean selected = GROUP_CHILDREN.evaluate(item).asStream()
107            .map(child -> {
108              return getSelectionState((IRequiredValueModelNodeItem) ObjectUtils.requireNonNull(child)).isSelected();
109            })
110            .reduce(false, (first, second) -> first || second);
111
112        retval = new SelectionState(selected, false);
113      } else {
114        throw new IllegalStateException(
115            String.format("Selection not supported for type '%s' at path '%s'",
116                itemValue.getClass().getName(),
117                item.toPath(IPathFormatter.METAPATH_PATH_FORMATER)));
118      }
119      itemSelectionState.put(item, retval);
120    }
121    return retval;
122  }
123
124  private static final class SelectionState {
125    private final boolean selected;
126    private final boolean withChildren;
127
128    private SelectionState(boolean selected, boolean withChildren) {
129      this.selected = selected;
130      this.withChildren = withChildren;
131    }
132
133    public boolean isSelected() {
134      return selected;
135    }
136
137    public boolean isWithChildren() {
138      return selected && withChildren;
139    }
140  }
141}