001/*
002 * Copyright 2008-2022 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2008-2022 Ping Identity Corporation
007 *
008 * Licensed under the Apache License, Version 2.0 (the "License");
009 * you may not use this file except in compliance with the License.
010 * You may obtain a copy of the License at
011 *
012 *    http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing, software
015 * distributed under the License is distributed on an "AS IS" BASIS,
016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017 * See the License for the specific language governing permissions and
018 * limitations under the License.
019 */
020/*
021 * Copyright (C) 2008-2022 Ping Identity Corporation
022 *
023 * This program is free software; you can redistribute it and/or modify
024 * it under the terms of the GNU General Public License (GPLv2 only)
025 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
026 * as published by the Free Software Foundation.
027 *
028 * This program is distributed in the hope that it will be useful,
029 * but WITHOUT ANY WARRANTY; without even the implied warranty of
030 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
031 * GNU General Public License for more details.
032 *
033 * You should have received a copy of the GNU General Public License
034 * along with this program; if not, see <http://www.gnu.org/licenses>.
035 */
036package com.unboundid.ldap.sdk.controls;
037
038
039
040import java.util.ArrayList;
041import java.util.List;
042
043import com.unboundid.asn1.ASN1Element;
044import com.unboundid.asn1.ASN1OctetString;
045import com.unboundid.asn1.ASN1Sequence;
046import com.unboundid.ldap.sdk.Control;
047import com.unboundid.ldap.sdk.Filter;
048import com.unboundid.ldap.sdk.JSONControlDecodeHelper;
049import com.unboundid.ldap.sdk.LDAPException;
050import com.unboundid.ldap.sdk.ResultCode;
051import com.unboundid.util.Debug;
052import com.unboundid.util.NotMutable;
053import com.unboundid.util.NotNull;
054import com.unboundid.util.ThreadSafety;
055import com.unboundid.util.ThreadSafetyLevel;
056import com.unboundid.util.Validator;
057import com.unboundid.util.json.JSONArray;
058import com.unboundid.util.json.JSONField;
059import com.unboundid.util.json.JSONObject;
060import com.unboundid.util.json.JSONString;
061import com.unboundid.util.json.JSONValue;
062
063import static com.unboundid.ldap.sdk.controls.ControlMessages.*;
064
065
066
067/**
068 * This class provides an implementation of the matched values request control
069 * as defined in <A HREF="http://www.ietf.org/rfc/rfc3876.txt">RFC 3876</A>.  It
070 * should only be used with a search request, in which case it indicates that
071 * only attribute values matching at least one of the provided
072 * {@link MatchedValuesFilter}s should be included in matching entries.  That
073 * is, this control may be used to restrict the set of values included in the
074 * entries that are returned.  This is particularly useful for multivalued
075 * attributes with a large number of values when only a small number of values
076 * are of interest to the client.
077 * <BR><BR>
078 * There are no corresponding response controls included in the search result
079 * entry, search result reference, or search result done messages returned for
080 * the associated search request.
081 * <BR><BR>
082 * <H2>Example</H2>
083 * The following example demonstrates the use of the matched values request
084 * control.  It will cause only values of the "{@code description}" attribute
085 * to be returned in which those values start with the letter f:
086 * <PRE>
087 * // Ensure that a test user has multiple description values.
088 * LDAPResult modifyResult = connection.modify(
089 *      "uid=test.user,ou=People,dc=example,dc=com",
090 *      new Modification(ModificationType.REPLACE,
091 *           "description", // Attribute name
092 *           "first", "second", "third", "fourth")); // Attribute values.
093 * assertResultCodeEquals(modifyResult, ResultCode.SUCCESS);
094 *
095 * // Perform a search to retrieve the test user entry without using the
096 * // matched values request control.  This should return all four description
097 * // values.
098 * SearchRequest searchRequest = new SearchRequest(
099 *      "uid=test.user,ou=People,dc=example,dc=com", // Base DN
100 *      SearchScope.BASE, // Scope
101 *      Filter.createPresenceFilter("objectClass"), // Filter
102 *      "description"); // Attributes to return.
103 * SearchResultEntry entryRetrievedWithoutControl =
104 *      connection.searchForEntry(searchRequest);
105 * Attribute fullDescriptionAttribute =
106 *      entryRetrievedWithoutControl.getAttribute("description");
107 * int numFullDescriptionValues = fullDescriptionAttribute.size();
108 *
109 * // Update the search request to include a matched values control that will
110 * // only return values that start with the letter "f".  In our test entry,
111 * // this should just match two values ("first" and "fourth").
112 * searchRequest.addControl(new MatchedValuesRequestControl(
113 *      MatchedValuesFilter.createSubstringFilter("description", // Attribute
114 *           "f", // subInitial component
115 *           null, // subAny components
116 *           null))); // subFinal component
117 * SearchResultEntry entryRetrievedWithControl =
118 *      connection.searchForEntry(searchRequest);
119 * Attribute partialDescriptionAttribute =
120 *      entryRetrievedWithControl.getAttribute("description");
121 * int numPartialDescriptionValues = partialDescriptionAttribute.size();
122 * </PRE>
123 */
124@NotMutable()
125@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
126public final class MatchedValuesRequestControl
127       extends Control
128{
129  /**
130   * The OID (1.2.826.0.1.3344810.2.3) for the matched values request control.
131   */
132  @NotNull public static final String MATCHED_VALUES_REQUEST_OID =
133       "1.2.826.0.1.3344810.2.3";
134
135
136
137  /**
138   * The name of the field used to hold the matched values filters in the JSON
139   * representation of this control.
140   */
141  @NotNull private static final String JSON_FIELD_FILTERS = "filters";
142
143
144
145  /**
146   * The serial version UID for this serializable class.
147   */
148  private static final long serialVersionUID = 6799850686547208774L;
149
150
151
152  // The set of matched values filters for this control.
153  @NotNull private final MatchedValuesFilter[] filters;
154
155
156
157  /**
158   * Creates a new matched values request control with the provided set of
159   * filters.  It will not be be marked as critical.
160   *
161   * @param  filters  The set of filters to use for this control.  At least one
162   *                  filter must be provided.
163   */
164  public MatchedValuesRequestControl(
165              @NotNull final MatchedValuesFilter... filters)
166  {
167    this(false, filters);
168  }
169
170
171
172  /**
173   * Creates a new matched values request control with the provided set of
174   * filters.  It will not be be marked as critical.
175   *
176   * @param  filters  The set of filters to use for this control.  At least one
177   *                  filter must be provided.
178   */
179  public MatchedValuesRequestControl(
180              @NotNull final List<MatchedValuesFilter> filters)
181  {
182    this(false, filters);
183  }
184
185
186
187  /**
188   * Creates a new matched values request control with the provided criticality
189   * and set of filters.
190   *
191   * @param  isCritical  Indicates whether this control should be marked
192   *                     critical.
193   * @param  filters     The set of filters to use for this control.  At least
194   *                     one filter must be provided.
195   */
196  public MatchedValuesRequestControl(final boolean isCritical,
197              @NotNull final MatchedValuesFilter... filters)
198  {
199    super(MATCHED_VALUES_REQUEST_OID, isCritical,  encodeValue(filters));
200
201    this.filters = filters;
202  }
203
204
205
206  /**
207   * Creates a new matched values request control with the provided criticality
208   * and set of filters.
209   *
210   * @param  isCritical  Indicates whether this control should be marked
211   *                     critical.
212   * @param  filters     The set of filters to use for this control.  At least
213   *                     one filter must be provided.
214   */
215  public MatchedValuesRequestControl(final boolean isCritical,
216              @NotNull final List<MatchedValuesFilter> filters)
217  {
218    this(isCritical, filters.toArray(new MatchedValuesFilter[filters.size()]));
219  }
220
221
222
223  /**
224   * Creates a new matched values request control which is decoded from the
225   * provided generic control.
226   *
227   * @param  control  The generic control to be decoded as a matched values
228   *                  request control.
229   *
230   * @throws  LDAPException  If the provided control cannot be decoded as a
231   *                         matched values request control.
232   */
233  public MatchedValuesRequestControl(@NotNull final Control control)
234         throws LDAPException
235  {
236    super(control);
237
238    final ASN1OctetString value = control.getValue();
239    if (value == null)
240    {
241      throw new LDAPException(ResultCode.DECODING_ERROR,
242                              ERR_MV_REQUEST_NO_VALUE.get());
243    }
244
245    try
246    {
247      final ASN1Element valueElement = ASN1Element.decode(value.getValue());
248      final ASN1Element[] filterElements =
249           ASN1Sequence.decodeAsSequence(valueElement).elements();
250      filters = new MatchedValuesFilter[filterElements.length];
251      for (int i=0; i < filterElements.length; i++)
252      {
253        filters[i] = MatchedValuesFilter.decode(filterElements[i]);
254      }
255    }
256    catch (final Exception e)
257    {
258      Debug.debugException(e);
259      throw new LDAPException(ResultCode.DECODING_ERROR,
260                              ERR_MV_REQUEST_CANNOT_DECODE.get(e), e);
261    }
262  }
263
264
265
266  /**
267   * Encodes the provided set of filters into a value appropriate for use with
268   * the matched values control.
269   *
270   * @param  filters  The set of filters to include in the value.  It must not
271   *                  be {@code null} or empty.
272   *
273   * @return  The ASN.1 octet string containing the encoded control value.
274   */
275  @NotNull()
276  private static ASN1OctetString encodeValue(
277                      @NotNull final MatchedValuesFilter[] filters)
278  {
279    Validator.ensureNotNull(filters);
280    Validator.ensureTrue(filters.length > 0,
281         "MatchedValuesRequestControl.filters must not be empty.");
282
283    final ASN1Element[] elements = new ASN1Element[filters.length];
284    for (int i=0; i < filters.length; i++)
285    {
286      elements[i] = filters[i].encode();
287    }
288
289    return new ASN1OctetString(new ASN1Sequence(elements).encode());
290  }
291
292
293
294  /**
295   * Retrieves the set of filters for this matched values request control.
296   *
297   * @return  The set of filters for this matched values request control.
298   */
299  @NotNull()
300  public MatchedValuesFilter[] getFilters()
301  {
302    return filters;
303  }
304
305
306
307  /**
308   * {@inheritDoc}
309   */
310  @Override()
311  @NotNull()
312  public String getControlName()
313  {
314    return INFO_CONTROL_NAME_MATCHED_VALUES_REQUEST.get();
315  }
316
317
318
319  /**
320   * Retrieves a representation of this matched values request control as a JSON
321   * object.  The JSON object uses the following fields:
322   * <UL>
323   *   <LI>
324   *     {@code oid} -- A mandatory string field whose value is the object
325   *     identifier for this control.  For the matched values request control,
326   *     the OID is "1.2.826.0.1.3344810.2.3".
327   *   </LI>
328   *   <LI>
329   *     {@code control-name} -- An optional string field whose value is a
330   *     human-readable name for this control.  This field is only intended for
331   *     descriptive purposes, and when decoding a control, the {@code oid}
332   *     field should be used to identify the type of control.
333   *   </LI>
334   *   <LI>
335   *     {@code criticality} -- A mandatory Boolean field used to indicate
336   *     whether this control is considered critical.
337   *   </LI>
338   *   <LI>
339   *     {@code value-base64} -- An optional string field whose value is a
340   *     base64-encoded representation of the raw value for this matched values
341   *     request control.  Exactly one of the {@code value-base64} and
342   *     {@code value-json} fields must be present.
343   *   </LI>
344   *   <LI>
345   *     {@code value-json} -- An optional JSON object field whose value is a
346   *     user-friendly representation of the value for this matched values
347   *     request control.  Exactly one of the {@code value-base64} and
348   *     {@code value-json} fields must be present, and if the
349   *     {@code value-json} field is used, then it will use the following
350   *     fields:
351   *     <UL>
352   *       <LI>
353   *         {@code filters} -- A mandatory, non-empty array field whose values
354   *         are the string representations  of the matched values filters to
355   *         use.
356   *       </LI>
357   *     </UL>
358   *   </LI>
359   * </UL>
360   *
361   * @return  A JSON object that contains a representation of this control.
362   */
363  @Override()
364  @NotNull()
365  public JSONObject toJSONControl()
366  {
367    final List<JSONValue> filterValues = new ArrayList<>(filters.length);
368    for (final MatchedValuesFilter filter : filters)
369    {
370      filterValues.add(new JSONString(filter.toString()));
371    }
372
373    return new JSONObject(
374         new JSONField(JSONControlDecodeHelper.JSON_FIELD_OID,
375              MATCHED_VALUES_REQUEST_OID),
376         new JSONField(JSONControlDecodeHelper.JSON_FIELD_CONTROL_NAME,
377              INFO_CONTROL_NAME_MATCHED_VALUES_REQUEST.get()),
378         new JSONField(JSONControlDecodeHelper.JSON_FIELD_CRITICALITY,
379              isCritical()),
380         new JSONField(JSONControlDecodeHelper.JSON_FIELD_VALUE_JSON,
381              new JSONObject(
382                   new JSONField(JSON_FIELD_FILTERS,
383                        new JSONArray(filterValues)))));
384  }
385
386
387
388  /**
389   * Attempts to decode the provided object as a JSON representation of a
390   * matched values request control.
391   *
392   * @param  controlObject  The JSON object to be decoded.  It must not be
393   *                        {@code null}.
394   * @param  strict         Indicates whether to use strict mode when decoding
395   *                        the provided JSON object.  If this is {@code true},
396   *                        then this method will throw an exception if the
397   *                        provided JSON object contains any unrecognized
398   *                        fields.  If this is {@code false}, then unrecognized
399   *                        fields will be ignored.
400   *
401   * @return  The matched values request control that was decoded from the
402   *          provided JSON object.
403   *
404   * @throws  LDAPException  If the provided JSON object cannot be parsed as a
405   *                         valid matched values request control.
406   */
407  @NotNull()
408  public static MatchedValuesRequestControl decodeJSONControl(
409              @NotNull final JSONObject controlObject,
410              final boolean strict)
411         throws LDAPException
412  {
413    final JSONControlDecodeHelper jsonControl = new JSONControlDecodeHelper(
414         controlObject, strict, true, true);
415
416    final ASN1OctetString rawValue = jsonControl.getRawValue();
417    if (rawValue != null)
418    {
419      return new MatchedValuesRequestControl(new Control(jsonControl.getOID(),
420           jsonControl.getCriticality(), rawValue));
421    }
422
423
424    final JSONObject valueObject = jsonControl.getValueObject();
425
426    final List<JSONValue> filterValues =
427         valueObject.getFieldAsArray(JSON_FIELD_FILTERS);
428    if (filterValues == null)
429    {
430      throw new LDAPException(ResultCode.DECODING_ERROR,
431           ERR_MV_REQUEST_JSON_NO_FILTERS.get(
432                controlObject.toSingleLineString(), JSON_FIELD_FILTERS));
433    }
434
435    if (filterValues.isEmpty())
436    {
437      throw new LDAPException(ResultCode.DECODING_ERROR,
438           ERR_MV_REQUEST_JSON_EMPTY_FILTERS.get(
439                controlObject.toSingleLineString(), JSON_FIELD_FILTERS));
440    }
441
442
443    final List<MatchedValuesFilter> filters =
444         new ArrayList<>(filterValues.size());
445    for (final JSONValue filterValue : filterValues)
446    {
447      if (filterValue instanceof JSONString)
448      {
449        final String filterString = ((JSONString) filterValue).stringValue();
450
451        try
452        {
453          final Filter filter = Filter.create(filterString);
454          filters.add(MatchedValuesFilter.create(filter));
455        }
456        catch (final LDAPException e)
457        {
458          Debug.debugException(e);
459          throw new LDAPException(ResultCode.DECODING_ERROR,
460               ERR_MV_REQUEST_JSON_INVALID_FILTER.get(
461                    controlObject.toSingleLineString(),
462                    JSON_FIELD_FILTERS, filterString, e.getMessage()),
463               e);
464        }
465      }
466      else
467      {
468        throw new LDAPException(ResultCode.DECODING_ERROR,
469             ERR_MV_REQUEST_JSON_FILTER_NOT_STRING.get(
470                  controlObject.toSingleLineString(), JSON_FIELD_FILTERS));
471      }
472    }
473
474
475    if (strict)
476    {
477      final List<String> unrecognizedFields =
478           JSONControlDecodeHelper.getControlObjectUnexpectedFields(
479                valueObject, JSON_FIELD_FILTERS);
480      if (! unrecognizedFields.isEmpty())
481      {
482        throw new LDAPException(ResultCode.DECODING_ERROR,
483             ERR_MV_REQUEST_JSON_UNRECOGNIZED_FIELD.get(
484                  controlObject.toSingleLineString(),
485                  unrecognizedFields.get(0)));
486      }
487    }
488
489
490    return new MatchedValuesRequestControl(jsonControl.getCriticality(),
491         filters);
492  }
493
494
495
496  /**
497   * {@inheritDoc}
498   */
499  @Override()
500  public void toString(@NotNull final StringBuilder buffer)
501  {
502    buffer.append("MatchedValuesRequestControl(filters={");
503
504    for (int i=0; i < filters.length; i++)
505    {
506      if (i > 0)
507      {
508        buffer.append(", ");
509      }
510
511      buffer.append('\'');
512      filters[i].toString(buffer);
513      buffer.append('\'');
514    }
515
516    buffer.append("}, isCritical=");
517    buffer.append(isCritical());
518    buffer.append(')');
519  }
520}