001/*
002 * Copyright 2012-2024 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2012-2024 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) 2012-2024 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.unboundidds.extensions;
037
038
039
040import java.util.ArrayList;
041import java.util.Collections;
042import java.util.Iterator;
043import java.util.List;
044
045import com.unboundid.asn1.ASN1Element;
046import com.unboundid.asn1.ASN1Enumerated;
047import com.unboundid.asn1.ASN1OctetString;
048import com.unboundid.asn1.ASN1Sequence;
049import com.unboundid.ldap.protocol.AddResponseProtocolOp;
050import com.unboundid.ldap.protocol.DeleteResponseProtocolOp;
051import com.unboundid.ldap.protocol.ExtendedResponseProtocolOp;
052import com.unboundid.ldap.protocol.LDAPMessage;
053import com.unboundid.ldap.protocol.ModifyDNResponseProtocolOp;
054import com.unboundid.ldap.protocol.ModifyResponseProtocolOp;
055import com.unboundid.ldap.sdk.Control;
056import com.unboundid.ldap.sdk.ExtendedResult;
057import com.unboundid.ldap.sdk.LDAPException;
058import com.unboundid.ldap.sdk.LDAPResult;
059import com.unboundid.ldap.sdk.OperationType;
060import com.unboundid.ldap.sdk.ResultCode;
061import com.unboundid.util.Debug;
062import com.unboundid.util.NotMutable;
063import com.unboundid.util.NotNull;
064import com.unboundid.util.Nullable;
065import com.unboundid.util.ObjectPair;
066import com.unboundid.util.StaticUtils;
067import com.unboundid.util.ThreadSafety;
068import com.unboundid.util.ThreadSafetyLevel;
069
070import static com.unboundid.ldap.sdk.unboundidds.extensions.ExtOpMessages.*;
071
072
073
074/**
075 * This class provides an implementation of an extended result that can be used
076 * to provide information about the processing for a
077 * {@link MultiUpdateExtendedRequest}.  The OID for this result is
078 * 1.3.6.1.4.1.30221.2.6.18, and the value (if present) should have the
079 * following encoding:
080 * <BR>
081 * <BLOCKQUOTE>
082 *   <B>NOTE:</B>  This class, and other classes within the
083 *   {@code com.unboundid.ldap.sdk.unboundidds} package structure, are only
084 *   supported for use against Ping Identity, UnboundID, and
085 *   Nokia/Alcatel-Lucent 8661 server products.  These classes provide support
086 *   for proprietary functionality or for external specifications that are not
087 *   considered stable or mature enough to be guaranteed to work in an
088 *   interoperable way with other types of LDAP servers.
089 * </BLOCKQUOTE>
090 * <BR>
091 * <PRE>
092 *   MultiUpdateResultValue ::= SEQUENCE {
093 *        changesApplied     ENUMERATED {
094 *             none        (0),
095 *             all         (1),
096 *             partial     (2),
097 *             ... },
098 *        responses     SEQUENCE OF SEQUENCE {
099 *             responseOp     CHOICE {
100 *                  modifyResponse     ModifyResponse,
101 *                  addResponse        AddResponse,
102 *                  delResponse        DelResponse,
103 *                  modDNResponse      ModifyDNResponse,
104 *                  extendedResp       ExtendedResponse,
105 *                  ... },
106 *             controls       [0] Controls OPTIONAL,
107 *             ... },
108 *        ... }
109 * </PRE>
110 *
111 * @see MultiUpdateChangesApplied
112 * @see MultiUpdateExtendedRequest
113 */
114@NotMutable()
115@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
116public final class MultiUpdateExtendedResult
117       extends ExtendedResult
118{
119  /**
120   * The OID (1.3.6.1.4.1.30221.2.6.18) for the multi-update extended result.
121   */
122  @NotNull public static final String MULTI_UPDATE_RESULT_OID =
123       "1.3.6.1.4.1.30221.2.6.18";
124
125
126
127  /**
128   * The serial version UID for this serializable class.
129   */
130  private static final long serialVersionUID = -2529988892013489969L;
131
132
133
134  // The set of results for the operations that were processed.
135  @NotNull private final List<ObjectPair<OperationType,LDAPResult>> results;
136
137  // The changes applied value for this result.
138  @Nullable private final MultiUpdateChangesApplied changesApplied;
139
140
141
142  /**
143   * Creates a new multi-update extended result from the provided extended
144   * result.
145   *
146   * @param  extendedResult  The extended result to be decoded as a multi-update
147   *                         result.
148   *
149   * @throws  LDAPException  If a problem is encountered while attempting to
150   *                         decode the provided extended result as a
151   *                         multi-update result.
152   */
153  public MultiUpdateExtendedResult(@NotNull final ExtendedResult extendedResult)
154         throws LDAPException
155  {
156    super(extendedResult);
157
158    final ASN1OctetString value = extendedResult.getValue();
159    if (value == null)
160    {
161      changesApplied = MultiUpdateChangesApplied.NONE;
162      results        = Collections.emptyList();
163      return;
164    }
165
166    try
167    {
168      final ASN1Element[] outerSequenceElements =
169           ASN1Sequence.decodeAsSequence(value.getValue()).elements();
170
171      final int cav = ASN1Enumerated.decodeAsEnumerated(
172           outerSequenceElements[0]).intValue();
173      changesApplied = MultiUpdateChangesApplied.valueOf(cav);
174      if (changesApplied == null)
175      {
176        throw new LDAPException(ResultCode.DECODING_ERROR,
177             ERR_MULTI_UPDATE_RESULT_INVALID_CHANGES_APPLIED.get(cav));
178      }
179
180      final ASN1Element[] responseSetElements =
181           ASN1Sequence.decodeAsSequence(outerSequenceElements[1]).elements();
182      final ArrayList<ObjectPair<OperationType,LDAPResult>> rl =
183           new ArrayList<>(responseSetElements.length);
184      for (final ASN1Element rse : responseSetElements)
185      {
186        final ASN1Element[] elements =
187             ASN1Sequence.decodeAsSequence(rse).elements();
188        final Control[] controls;
189        if (elements.length == 2)
190        {
191          controls = Control.decodeControls(
192               ASN1Sequence.decodeAsSequence(elements[1]));
193        }
194        else
195        {
196          controls = null;
197        }
198
199        switch (elements[0].getType())
200        {
201          case LDAPMessage.PROTOCOL_OP_TYPE_ADD_RESPONSE:
202            rl.add(new ObjectPair<>(OperationType.ADD,
203                 AddResponseProtocolOp.decodeProtocolOp(elements[0]).
204                      toLDAPResult(controls)));
205            break;
206          case LDAPMessage.PROTOCOL_OP_TYPE_DELETE_RESPONSE:
207            rl.add(new ObjectPair<>(OperationType.DELETE,
208                 DeleteResponseProtocolOp.decodeProtocolOp(elements[0]).
209                      toLDAPResult(controls)));
210            break;
211          case LDAPMessage.PROTOCOL_OP_TYPE_EXTENDED_RESPONSE:
212            rl.add(new ObjectPair<OperationType,LDAPResult>(
213                 OperationType.EXTENDED,
214                 ExtendedResponseProtocolOp.decodeProtocolOp(elements[0]).
215                      toExtendedResult(controls)));
216            break;
217          case LDAPMessage.PROTOCOL_OP_TYPE_MODIFY_RESPONSE:
218            rl.add(new ObjectPair<>(OperationType.MODIFY,
219                 ModifyResponseProtocolOp.decodeProtocolOp(elements[0]).
220                      toLDAPResult(controls)));
221            break;
222          case LDAPMessage.PROTOCOL_OP_TYPE_MODIFY_DN_RESPONSE:
223            rl.add(new ObjectPair<>(OperationType.MODIFY_DN,
224                 ModifyDNResponseProtocolOp.decodeProtocolOp(elements[0]).
225                      toLDAPResult(controls)));
226            break;
227          default:
228            throw new LDAPException(ResultCode.DECODING_ERROR,
229                 ERR_MULTI_UPDATE_RESULT_DECODE_INVALID_OP_TYPE.get(
230                      StaticUtils.toHex(elements[0].getType())));
231        }
232      }
233
234      results = Collections.unmodifiableList(rl);
235    }
236    catch (final LDAPException le)
237    {
238      Debug.debugException(le);
239      throw le;
240    }
241    catch (final Exception e)
242    {
243      Debug.debugException(e);
244      throw new LDAPException(ResultCode.DECODING_ERROR,
245           ERR_MULTI_UPDATE_RESULT_CANNOT_DECODE_VALUE.get(
246                StaticUtils.getExceptionMessage(e)),
247           e);
248    }
249  }
250
251
252
253  /**
254   * Creates a new multi-update extended request with the provided information.
255   *
256   * @param  messageID          The message ID for this extended result.
257   * @param  resultCode         The result code for this result.  It must not be
258   *                            {@code null}.
259   * @param  diagnosticMessage  The diagnostic message to include in the result.
260   *                            It may be {@code null} if no diagnostic message
261   *                            should be included.
262   * @param  matchedDN          The matched DN to include in the result.  It may
263   *                            be {@code null} if no matched DN should be
264   *                            included.
265   * @param  referralURLs       The set of referral URLs to include in the
266   *                            result.  It may be {@code null} or empty if no
267   *                            referral URLs should be included.
268   * @param  changesApplied     The value which indicates whether any or all of
269   *                            the changes from the request were successfully
270   *                            applied.
271   * @param  results            The set of operation results to be included in
272   *                            the extended result value.  It may be
273   *                            {@code null} or empty if no operation results
274   *                            should be included.
275   * @param  controls           The set of controls to include in the
276   *                            multi-update result.  It may be {@code null} or
277   *                            empty if no controls should be included.
278   *
279   * @throws  LDAPException  If any of the results are for an inappropriate
280   *                         operation type.
281   */
282  public MultiUpdateExtendedResult(final int messageID,
283       @NotNull final ResultCode resultCode,
284       @Nullable final String diagnosticMessage,
285       @Nullable final String matchedDN,
286       @Nullable final String[] referralURLs,
287       @Nullable final MultiUpdateChangesApplied changesApplied,
288       @Nullable final List<ObjectPair<OperationType,LDAPResult>> results,
289       @Nullable final Control... controls)
290       throws LDAPException
291  {
292    super(messageID, resultCode, diagnosticMessage, matchedDN, referralURLs,
293         MULTI_UPDATE_RESULT_OID, encodeValue(changesApplied, results),
294         controls);
295
296    this.changesApplied = changesApplied;
297
298    if (results == null)
299    {
300      this.results = Collections.emptyList();
301    }
302    else
303    {
304      this.results = Collections.unmodifiableList(results);
305    }
306  }
307
308
309
310  /**
311   * Encodes the information from the provided set of results into a form
312   * suitable for use as the value of a multi-update extended result.
313   *
314   * @param  changesApplied  The value which indicates whether any or all of the
315   *                         changes from the request were successfully applied.
316   * @param  results         The set of operation results to be included in the
317   *                         extended result value.  It may be {@code null} or
318   *                         empty if no operation results should be included.
319   *
320   * @return  An ASN.1 element suitable for use as the value of a multi-update
321   *          extended result.
322   *
323   * @throws  LDAPException  If any of the results are for an inappropriate
324   *                         operation type.
325   */
326  @Nullable()
327  private static ASN1OctetString encodeValue(
328       @Nullable final MultiUpdateChangesApplied changesApplied,
329       @Nullable final List<ObjectPair<OperationType,LDAPResult>> results)
330       throws LDAPException
331  {
332    if ((results == null) || results.isEmpty())
333    {
334      return null;
335    }
336
337    final ArrayList<ASN1Element> opElements = new ArrayList<>(results.size());
338    for (final ObjectPair<OperationType,LDAPResult> p : results)
339    {
340      final OperationType t = p.getFirst();
341      final LDAPResult    r = p.getSecond();
342
343      final ASN1Element protocolOpElement;
344      switch (t)
345      {
346        case ADD:
347          protocolOpElement = new AddResponseProtocolOp(r).encodeProtocolOp();
348          break;
349        case DELETE:
350          protocolOpElement =
351               new DeleteResponseProtocolOp(r).encodeProtocolOp();
352          break;
353        case EXTENDED:
354          protocolOpElement =
355               new ExtendedResponseProtocolOp(r).encodeProtocolOp();
356          break;
357        case MODIFY:
358          protocolOpElement =
359               new ModifyResponseProtocolOp(r).encodeProtocolOp();
360          break;
361        case MODIFY_DN:
362          protocolOpElement =
363               new ModifyDNResponseProtocolOp(r).encodeProtocolOp();
364          break;
365        default:
366          throw new LDAPException(ResultCode.PARAM_ERROR,
367               ERR_MULTI_UPDATE_RESULT_INVALID_OP_TYPE.get(t.name()));
368      }
369
370      final Control[] controls = r.getResponseControls();
371      if ((controls == null) || (controls.length == 0))
372      {
373        opElements.add(new ASN1Sequence(protocolOpElement));
374      }
375      else
376      {
377        opElements.add(new ASN1Sequence(
378             protocolOpElement,
379             Control.encodeControls(controls)));
380
381      }
382    }
383
384    final ASN1Sequence valueSequence = new ASN1Sequence(
385         new ASN1Enumerated(changesApplied.intValue()),
386         new ASN1Sequence(opElements));
387    return new ASN1OctetString(valueSequence.encode());
388  }
389
390
391
392  /**
393   * Retrieves the value that indicates whether any or all changes from the
394   * multi-update request were successfully applied.
395   *
396   * @return  The value that indicates whether any or all changes from the
397   *          multi-update request were successfully applied.
398   */
399  @Nullable()
400  public MultiUpdateChangesApplied getChangesApplied()
401  {
402    return changesApplied;
403  }
404
405
406
407  /**
408   * Retrieves a list of the results for operations processed as part of the
409   * multi-update operation, with each result paired with its corresponding
410   * operation type.
411   *
412   * @return  A list of the results for operations processed as part of the
413   *          multi-update operation.  The returned list may be empty if no
414   *          operation results were available.
415   */
416  @NotNull()
417  public List<ObjectPair<OperationType,LDAPResult>> getResults()
418  {
419    return results;
420  }
421
422
423
424  /**
425   * {@inheritDoc}
426   */
427  @Override()
428  @NotNull()
429  public String getExtendedResultName()
430  {
431    return INFO_EXTENDED_RESULT_NAME_MULTI_UPDATE.get();
432  }
433
434
435
436  /**
437   * Appends a string representation of this extended result to the provided
438   * buffer.
439   *
440   * @param  buffer  The buffer to which a string representation of this
441   *                 extended result will be appended.
442   */
443  @Override()
444  public void toString(@NotNull final StringBuilder buffer)
445  {
446    buffer.append("MultiUpdateExtendedResult(resultCode=");
447    buffer.append(getResultCode());
448
449    final int messageID = getMessageID();
450    if (messageID >= 0)
451    {
452      buffer.append(", messageID=");
453      buffer.append(messageID);
454    }
455
456    buffer.append(", changesApplied=");
457    buffer.append(changesApplied.name());
458    buffer.append(", results={");
459
460    final Iterator<ObjectPair<OperationType,LDAPResult>> resultIterator =
461         results.iterator();
462    while (resultIterator.hasNext())
463    {
464      resultIterator.next().getSecond().toString(buffer);
465      if (resultIterator.hasNext())
466      {
467        buffer.append(", ");
468      }
469    }
470
471    final String diagnosticMessage = getDiagnosticMessage();
472    if (diagnosticMessage != null)
473    {
474      buffer.append(", diagnosticMessage='");
475      buffer.append(diagnosticMessage);
476      buffer.append('\'');
477    }
478
479    final String matchedDN = getMatchedDN();
480    if (matchedDN != null)
481    {
482      buffer.append(", matchedDN='");
483      buffer.append(matchedDN);
484      buffer.append('\'');
485    }
486
487    final String[] referralURLs = getReferralURLs();
488    if (referralURLs.length > 0)
489    {
490      buffer.append(", referralURLs={");
491      for (int i=0; i < referralURLs.length; i++)
492      {
493        if (i > 0)
494        {
495          buffer.append(", ");
496        }
497
498        buffer.append('\'');
499        buffer.append(referralURLs[i]);
500        buffer.append('\'');
501      }
502      buffer.append('}');
503    }
504
505    final Control[] responseControls = getResponseControls();
506    if (responseControls.length > 0)
507    {
508      buffer.append(", responseControls={");
509      for (int i=0; i < responseControls.length; i++)
510      {
511        if (i > 0)
512        {
513          buffer.append(", ");
514        }
515
516        buffer.append(responseControls[i]);
517      }
518      buffer.append('}');
519    }
520
521    buffer.append(')');
522  }
523}