Search in sources :

Example 1 with StartAdministrativeSessionPostConnectProcessor

use of com.unboundid.ldap.sdk.unboundidds.extensions.StartAdministrativeSessionPostConnectProcessor in project ldapsdk by pingidentity.

the class LDAPModify method doToolProcessing.

/**
 * {@inheritDoc}
 */
@Override()
@NotNull()
public ResultCode doToolProcessing() {
    // Examine the arguments to determine the sets of controls to use for each
    // type of request.
    final ArrayList<Control> addControls = new ArrayList<>(10);
    final ArrayList<Control> deleteControls = new ArrayList<>(10);
    final ArrayList<Control> modifyControls = new ArrayList<>(10);
    final ArrayList<Control> modifyDNControls = new ArrayList<>(10);
    final ArrayList<Control> searchControls = new ArrayList<>(10);
    try {
        createRequestControls(addControls, deleteControls, modifyControls, modifyDNControls, searchControls);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        for (final String line : ResultUtils.formatResult(le, true, 0, WRAP_COLUMN)) {
            err(line);
        }
        return le.getResultCode();
    }
    // If an encryption passphrase file was specified, then read its value.
    String encryptionPassphrase = null;
    if (encryptionPassphraseFile.isPresent()) {
        try {
            encryptionPassphrase = ToolUtils.readEncryptionPassphraseFromFile(encryptionPassphraseFile.getValue());
        } catch (final LDAPException e) {
            Debug.debugException(e);
            wrapErr(0, WRAP_COLUMN, e.getMessage());
            return e.getResultCode();
        }
    }
    LDAPConnectionPool connectionPool = null;
    LDIFReader ldifReader = null;
    LDIFWriter rejectWriter = null;
    try {
        // before performing the bind.
        try {
            final StartAdministrativeSessionPostConnectProcessor p;
            if (useAdministrativeSession.isPresent()) {
                p = new StartAdministrativeSessionPostConnectProcessor(new StartAdministrativeSessionExtendedRequest(getToolName(), true));
            } else {
                p = null;
            }
            if (!dryRun.isPresent()) {
                connectionPool = getConnectionPool(1, 2, 0, p, null, true, new ReportBindResultLDAPConnectionPoolHealthCheck(this, true, verbose.isPresent()));
            }
        } catch (final LDAPException le) {
            Debug.debugException(le);
            // If the failure was something else, then display that failure result.
            if (le.getResultCode() != ResultCode.INVALID_CREDENTIALS) {
                for (final String line : ResultUtils.formatResult(le, true, 0, WRAP_COLUMN)) {
                    err(line);
                }
            }
            return le.getResultCode();
        }
        if (connectionPool != null) {
            connectionPool.setRetryFailedOperationsDueToInvalidConnections((!neverRetry.isPresent()));
        }
        // Report that the connection was successfully established.
        if (connectionPool != null) {
            try {
                final LDAPConnection connection = connectionPool.getConnection();
                final String hostPort = connection.getHostPort();
                connectionPool.releaseConnection(connection);
                commentToOut(INFO_LDAPMODIFY_CONNECTION_ESTABLISHED.get(hostPort));
                out();
            } catch (final LDAPException le) {
                Debug.debugException(le);
            // This should never happen.
            }
        }
        // If we should process the operations in a transaction, then start that
        // now.
        final ASN1OctetString txnID;
        if (useTransaction.isPresent()) {
            final Control[] startTxnControls;
            if (proxyAs.isPresent()) {
                // In a transaction, the proxied authorization control must only be
                // used in the start transaction request and not in any of the
                // subsequent operation requests.
                startTxnControls = new Control[] { new ProxiedAuthorizationV2RequestControl(proxyAs.getValue()) };
            } else if (proxyV1As.isPresent()) {
                // In a transaction, the proxied authorization control must only be
                // used in the start transaction request and not in any of the
                // subsequent operation requests.
                startTxnControls = new Control[] { new ProxiedAuthorizationV1RequestControl(proxyV1As.getValue()) };
            } else {
                startTxnControls = StaticUtils.NO_CONTROLS;
            }
            try {
                final StartTransactionExtendedResult startTxnResult = (StartTransactionExtendedResult) connectionPool.processExtendedOperation(new StartTransactionExtendedRequest(startTxnControls));
                if (startTxnResult.getResultCode() == ResultCode.SUCCESS) {
                    txnID = startTxnResult.getTransactionID();
                    final TransactionSpecificationRequestControl c = new TransactionSpecificationRequestControl(txnID);
                    addControls.add(c);
                    deleteControls.add(c);
                    modifyControls.add(c);
                    modifyDNControls.add(c);
                    final String txnIDString;
                    if (StaticUtils.isPrintableString(txnID.getValue())) {
                        txnIDString = txnID.stringValue();
                    } else {
                        final StringBuilder hexBuffer = new StringBuilder();
                        StaticUtils.toHex(txnID.getValue(), ":", hexBuffer);
                        txnIDString = hexBuffer.toString();
                    }
                    commentToOut(INFO_LDAPMODIFY_STARTED_TXN.get(txnIDString));
                } else {
                    commentToErr(ERR_LDAPMODIFY_CANNOT_START_TXN.get(startTxnResult.getResultString()));
                    return startTxnResult.getResultCode();
                }
            } catch (final LDAPException le) {
                Debug.debugException(le);
                commentToErr(ERR_LDAPMODIFY_CANNOT_START_TXN.get(StaticUtils.getExceptionMessage(le)));
                return le.getResultCode();
            }
        } else {
            txnID = null;
        }
        // Create an LDIF reader that will be used to read the changes to process.
        try {
            final InputStream ldifInputStream;
            if (ldifFile.isPresent()) {
                ldifInputStream = ToolUtils.getInputStreamForLDIFFiles(ldifFile.getValues(), encryptionPassphrase, getOut(), getErr()).getFirst();
            } else {
                ldifInputStream = in;
            }
            ldifReader = new LDIFReader(ldifInputStream, 0, null, null, characterSet.getValue());
        } catch (final Exception e) {
            commentToErr(ERR_LDAPMODIFY_CANNOT_CREATE_LDIF_READER.get(StaticUtils.getExceptionMessage(e)));
            return ResultCode.LOCAL_ERROR;
        }
        if (stripTrailingSpaces.isPresent()) {
            ldifReader.setTrailingSpaceBehavior(TrailingSpaceBehavior.STRIP);
        }
        // If appropriate, create a reject writer.
        if (rejectFile.isPresent()) {
            try {
                rejectWriter = new LDIFWriter(rejectFile.getValue());
                // Set the maximum allowed wrap column.  This is better than setting a
                // wrap column of zero because it will ensure that comments don't get
                // wrapped either.
                rejectWriter.setWrapColumn(Integer.MAX_VALUE);
            } catch (final Exception e) {
                Debug.debugException(e);
                commentToErr(ERR_LDAPMODIFY_CANNOT_CREATE_REJECT_WRITER.get(rejectFile.getValue().getAbsolutePath(), StaticUtils.getExceptionMessage(e)));
                return ResultCode.LOCAL_ERROR;
            }
        }
        // If appropriate, create a rate limiter.
        final FixedRateBarrier rateLimiter;
        if (ratePerSecond.isPresent()) {
            rateLimiter = new FixedRateBarrier(1000L, ratePerSecond.getValue());
        } else {
            rateLimiter = null;
        }
        // Iterate through the set of changes to process.
        boolean commitTransaction = true;
        ResultCode resultCode = null;
        final ArrayList<LDAPRequest> multiUpdateRequests = new ArrayList<>(10);
        final boolean isBulkModify = modifyEntriesMatchingFilter.isPresent() || modifyEntriesMatchingFiltersFromFile.isPresent() || modifyEntryWithDN.isPresent() || modifyEntriesWithDNsFromFile.isPresent();
        readChangeRecordLoop: while (true) {
            // If there is a rate limiter, then use it to sleep if necessary.
            if ((rateLimiter != null) && (!isBulkModify)) {
                rateLimiter.await();
            }
            // Read the next LDIF change record.  If we get an error then handle it
            // and abort if appropriate.
            final LDIFChangeRecord changeRecord;
            try {
                changeRecord = ldifReader.readChangeRecord(defaultAdd.isPresent());
            } catch (final IOException ioe) {
                Debug.debugException(ioe);
                final String message = ERR_LDAPMODIFY_IO_ERROR_READING_CHANGE.get(StaticUtils.getExceptionMessage(ioe));
                commentToErr(message);
                writeRejectedChange(rejectWriter, message, null);
                commitTransaction = false;
                resultCode = ResultCode.LOCAL_ERROR;
                break;
            } catch (final LDIFException le) {
                Debug.debugException(le);
                final StringBuilder buffer = new StringBuilder();
                if (le.mayContinueReading() && (!useTransaction.isPresent())) {
                    buffer.append(ERR_LDAPMODIFY_RECOVERABLE_LDIF_ERROR_READING_CHANGE.get(le.getLineNumber(), StaticUtils.getExceptionMessage(le)));
                } else {
                    buffer.append(ERR_LDAPMODIFY_UNRECOVERABLE_LDIF_ERROR_READING_CHANGE.get(le.getLineNumber(), StaticUtils.getExceptionMessage(le)));
                }
                if ((resultCode == null) || (resultCode == ResultCode.SUCCESS)) {
                    resultCode = ResultCode.LOCAL_ERROR;
                }
                if ((le.getDataLines() != null) && (!le.getDataLines().isEmpty())) {
                    buffer.append(StaticUtils.EOL);
                    buffer.append(StaticUtils.EOL);
                    buffer.append(ERR_LDAPMODIFY_INVALID_LINES.get());
                    buffer.append(StaticUtils.EOL);
                    for (final String s : le.getDataLines()) {
                        buffer.append(s);
                        buffer.append(StaticUtils.EOL);
                    }
                }
                final String message = buffer.toString();
                commentToErr(message);
                writeRejectedChange(rejectWriter, message, null);
                if (le.mayContinueReading() && (!useTransaction.isPresent())) {
                    continue;
                } else {
                    commitTransaction = false;
                    resultCode = ResultCode.LOCAL_ERROR;
                    break;
                }
            }
            // type.
            if (changeRecord == null) {
                break;
            }
            // the change record into a set of modifications.
            if (modifyEntriesMatchingFilter.isPresent()) {
                for (final Filter filter : modifyEntriesMatchingFilter.getValues()) {
                    final ResultCode rc = handleModifyMatchingFilter(connectionPool, changeRecord, modifyEntriesMatchingFilter.getIdentifierString(), filter, searchControls, modifyControls, rateLimiter, rejectWriter);
                    if (rc != ResultCode.SUCCESS) {
                        if ((resultCode == null) || (resultCode == ResultCode.SUCCESS) || (resultCode == ResultCode.NO_OPERATION)) {
                            resultCode = rc;
                        }
                    }
                }
            }
            if (modifyEntriesMatchingFiltersFromFile.isPresent()) {
                for (final File f : modifyEntriesMatchingFiltersFromFile.getValues()) {
                    final FilterFileReader filterReader;
                    try {
                        filterReader = new FilterFileReader(f);
                    } catch (final Exception e) {
                        Debug.debugException(e);
                        commentToErr(ERR_LDAPMODIFY_ERROR_OPENING_FILTER_FILE.get(f.getAbsolutePath(), StaticUtils.getExceptionMessage(e)));
                        return ResultCode.LOCAL_ERROR;
                    }
                    try {
                        while (true) {
                            final Filter filter;
                            try {
                                filter = filterReader.readFilter();
                            } catch (final IOException ioe) {
                                Debug.debugException(ioe);
                                commentToErr(ERR_LDAPMODIFY_IO_ERROR_READING_FILTER_FILE.get(f.getAbsolutePath(), StaticUtils.getExceptionMessage(ioe)));
                                return ResultCode.LOCAL_ERROR;
                            } catch (final LDAPException le) {
                                Debug.debugException(le);
                                commentToErr(le.getMessage());
                                if (continueOnError.isPresent()) {
                                    if ((resultCode == null) || (resultCode == ResultCode.SUCCESS) || (resultCode == ResultCode.NO_OPERATION)) {
                                        resultCode = le.getResultCode();
                                    }
                                    continue;
                                } else {
                                    return le.getResultCode();
                                }
                            }
                            if (filter == null) {
                                break;
                            }
                            final ResultCode rc = handleModifyMatchingFilter(connectionPool, changeRecord, modifyEntriesMatchingFiltersFromFile.getIdentifierString(), filter, searchControls, modifyControls, rateLimiter, rejectWriter);
                            if (rc != ResultCode.SUCCESS) {
                                if ((resultCode == null) || (resultCode == ResultCode.SUCCESS) || (resultCode == ResultCode.NO_OPERATION)) {
                                    resultCode = rc;
                                }
                            }
                        }
                    } finally {
                        try {
                            filterReader.close();
                        } catch (final Exception e) {
                            Debug.debugException(e);
                        }
                    }
                }
            }
            if (modifyEntryWithDN.isPresent()) {
                for (final DN dn : modifyEntryWithDN.getValues()) {
                    final ResultCode rc = handleModifyWithDN(connectionPool, changeRecord, modifyEntryWithDN.getIdentifierString(), dn, modifyControls, rateLimiter, rejectWriter);
                    if (rc != ResultCode.SUCCESS) {
                        if ((resultCode == null) || (resultCode == ResultCode.SUCCESS) || (resultCode == ResultCode.NO_OPERATION)) {
                            resultCode = rc;
                        }
                    }
                }
            }
            if (modifyEntriesWithDNsFromFile.isPresent()) {
                for (final File f : modifyEntriesWithDNsFromFile.getValues()) {
                    final DNFileReader dnReader;
                    try {
                        dnReader = new DNFileReader(f);
                    } catch (final Exception e) {
                        Debug.debugException(e);
                        commentToErr(ERR_LDAPMODIFY_ERROR_OPENING_DN_FILE.get(f.getAbsolutePath(), StaticUtils.getExceptionMessage(e)));
                        return ResultCode.LOCAL_ERROR;
                    }
                    try {
                        while (true) {
                            final DN dn;
                            try {
                                dn = dnReader.readDN();
                            } catch (final IOException ioe) {
                                Debug.debugException(ioe);
                                commentToErr(ERR_LDAPMODIFY_IO_ERROR_READING_DN_FILE.get(f.getAbsolutePath(), StaticUtils.getExceptionMessage(ioe)));
                                return ResultCode.LOCAL_ERROR;
                            } catch (final LDAPException le) {
                                Debug.debugException(le);
                                commentToErr(le.getMessage());
                                if (continueOnError.isPresent()) {
                                    if ((resultCode == null) || (resultCode == ResultCode.SUCCESS) || (resultCode == ResultCode.NO_OPERATION)) {
                                        resultCode = le.getResultCode();
                                    }
                                    continue;
                                } else {
                                    return le.getResultCode();
                                }
                            }
                            if (dn == null) {
                                break;
                            }
                            final ResultCode rc = handleModifyWithDN(connectionPool, changeRecord, modifyEntriesWithDNsFromFile.getIdentifierString(), dn, modifyControls, rateLimiter, rejectWriter);
                            if (rc != ResultCode.SUCCESS) {
                                if ((resultCode == null) || (resultCode == ResultCode.SUCCESS) || (resultCode == ResultCode.NO_OPERATION)) {
                                    resultCode = rc;
                                }
                            }
                        }
                    } finally {
                        try {
                            dnReader.close();
                        } catch (final Exception e) {
                            Debug.debugException(e);
                        }
                    }
                }
            }
            if (isBulkModify) {
                continue;
            }
            try {
                final ResultCode rc;
                if (changeRecord instanceof LDIFAddChangeRecord) {
                    rc = doAdd((LDIFAddChangeRecord) changeRecord, addControls, connectionPool, multiUpdateRequests, rejectWriter);
                } else if (changeRecord instanceof LDIFDeleteChangeRecord) {
                    rc = doDelete((LDIFDeleteChangeRecord) changeRecord, deleteControls, connectionPool, multiUpdateRequests, rejectWriter);
                } else if (changeRecord instanceof LDIFModifyChangeRecord) {
                    rc = doModify((LDIFModifyChangeRecord) changeRecord, modifyControls, connectionPool, multiUpdateRequests, rejectWriter);
                } else if (changeRecord instanceof LDIFModifyDNChangeRecord) {
                    rc = doModifyDN((LDIFModifyDNChangeRecord) changeRecord, modifyDNControls, connectionPool, multiUpdateRequests, rejectWriter);
                } else {
                    // This should never happen.
                    commentToErr(ERR_LDAPMODIFY_UNSUPPORTED_CHANGE_RECORD_HEADER.get());
                    for (final String line : changeRecord.toLDIF()) {
                        err("#      " + line);
                    }
                    throw new LDAPException(ResultCode.PARAM_ERROR, ERR_LDAPMODIFY_UNSUPPORTED_CHANGE_RECORD_HEADER.get() + changeRecord.toString());
                }
                if ((resultCode == null) && (rc != ResultCode.SUCCESS)) {
                    resultCode = rc;
                }
            } catch (final LDAPException le) {
                Debug.debugException(le);
                commitTransaction = false;
                if (continueOnError.isPresent()) {
                    if ((resultCode == null) || (resultCode == ResultCode.SUCCESS) || (resultCode == ResultCode.NO_OPERATION)) {
                        resultCode = le.getResultCode();
                    }
                } else {
                    resultCode = le.getResultCode();
                    break;
                }
            }
        }
        // operation, then process that now.
        if (useTransaction.isPresent()) {
            LDAPResult endTxnResult;
            final EndTransactionExtendedRequest endTxnRequest = new EndTransactionExtendedRequest(txnID, commitTransaction);
            try {
                endTxnResult = connectionPool.processExtendedOperation(endTxnRequest);
            } catch (final LDAPException le) {
                endTxnResult = le.toLDAPResult();
            }
            displayResult(endTxnResult, false);
            if (((resultCode == null) || (resultCode == ResultCode.SUCCESS)) && (endTxnResult.getResultCode() != ResultCode.SUCCESS)) {
                resultCode = endTxnResult.getResultCode();
            }
        } else if (multiUpdateErrorBehavior.isPresent()) {
            final MultiUpdateErrorBehavior errorBehavior;
            if (multiUpdateErrorBehavior.getValue().equalsIgnoreCase("atomic")) {
                errorBehavior = MultiUpdateErrorBehavior.ATOMIC;
            } else if (multiUpdateErrorBehavior.getValue().equalsIgnoreCase("abort-on-error")) {
                errorBehavior = MultiUpdateErrorBehavior.ABORT_ON_ERROR;
            } else {
                errorBehavior = MultiUpdateErrorBehavior.CONTINUE_ON_ERROR;
            }
            final Control[] multiUpdateControls;
            if (proxyAs.isPresent()) {
                multiUpdateControls = new Control[] { new ProxiedAuthorizationV2RequestControl(proxyAs.getValue()) };
            } else if (proxyV1As.isPresent()) {
                multiUpdateControls = new Control[] { new ProxiedAuthorizationV1RequestControl(proxyV1As.getValue()) };
            } else {
                multiUpdateControls = StaticUtils.NO_CONTROLS;
            }
            ExtendedResult multiUpdateResult;
            try {
                commentToOut(INFO_LDAPMODIFY_SENDING_MULTI_UPDATE_REQUEST.get());
                final MultiUpdateExtendedRequest multiUpdateRequest = new MultiUpdateExtendedRequest(errorBehavior, multiUpdateRequests, multiUpdateControls);
                multiUpdateResult = connectionPool.processExtendedOperation(multiUpdateRequest);
            } catch (final LDAPException le) {
                multiUpdateResult = new ExtendedResult(le);
            }
            displayResult(multiUpdateResult, false);
            resultCode = multiUpdateResult.getResultCode();
        }
        if (resultCode == null) {
            return ResultCode.SUCCESS;
        } else {
            return resultCode;
        }
    } finally {
        if (rejectWriter != null) {
            try {
                rejectWriter.close();
            } catch (final Exception e) {
                Debug.debugException(e);
            }
        }
        if (ldifReader != null) {
            try {
                ldifReader.close();
            } catch (final Exception e) {
                Debug.debugException(e);
            }
        }
        if (connectionPool != null) {
            try {
                connectionPool.close();
            } catch (final Exception e) {
                Debug.debugException(e);
            }
        }
    }
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) LDAPRequest(com.unboundid.ldap.sdk.LDAPRequest) ArrayList(java.util.ArrayList) ProxiedAuthorizationV2RequestControl(com.unboundid.ldap.sdk.controls.ProxiedAuthorizationV2RequestControl) EndTransactionExtendedRequest(com.unboundid.ldap.sdk.extensions.EndTransactionExtendedRequest) DN(com.unboundid.ldap.sdk.DN) DNFileReader(com.unboundid.util.DNFileReader) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) LDIFModifyDNChangeRecord(com.unboundid.ldif.LDIFModifyDNChangeRecord) RouteToServerRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.RouteToServerRequestControl) SubtreeDeleteRequestControl(com.unboundid.ldap.sdk.controls.SubtreeDeleteRequestControl) SimplePagedResultsControl(com.unboundid.ldap.sdk.controls.SimplePagedResultsControl) TransactionSpecificationRequestControl(com.unboundid.ldap.sdk.controls.TransactionSpecificationRequestControl) AssuredReplicationRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.AssuredReplicationRequestControl) PostReadRequestControl(com.unboundid.ldap.sdk.controls.PostReadRequestControl) SuppressOperationalAttributeUpdateRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.SuppressOperationalAttributeUpdateRequestControl) NameWithEntryUUIDRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.NameWithEntryUUIDRequestControl) ReplicationRepairRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.ReplicationRepairRequestControl) ProxiedAuthorizationV1RequestControl(com.unboundid.ldap.sdk.controls.ProxiedAuthorizationV1RequestControl) OperationPurposeRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.OperationPurposeRequestControl) PasswordUpdateBehaviorRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.PasswordUpdateBehaviorRequestControl) UndeleteRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.UndeleteRequestControl) GetRecentLoginHistoryRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.GetRecentLoginHistoryRequestControl) PermissiveModifyRequestControl(com.unboundid.ldap.sdk.controls.PermissiveModifyRequestControl) AuthorizationIdentityRequestControl(com.unboundid.ldap.sdk.controls.AuthorizationIdentityRequestControl) Control(com.unboundid.ldap.sdk.Control) GetUserResourceLimitsRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.GetUserResourceLimitsRequestControl) HardDeleteRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.HardDeleteRequestControl) IgnoreNoUserModificationRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.IgnoreNoUserModificationRequestControl) GetBackendSetIDRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.GetBackendSetIDRequestControl) GetAuthorizationEntryRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.GetAuthorizationEntryRequestControl) PurgePasswordRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.PurgePasswordRequestControl) ProxiedAuthorizationV2RequestControl(com.unboundid.ldap.sdk.controls.ProxiedAuthorizationV2RequestControl) SoftDeleteRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.SoftDeleteRequestControl) RetirePasswordRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.RetirePasswordRequestControl) GetServerIDRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.GetServerIDRequestControl) NoOpRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.NoOpRequestControl) PasswordPolicyRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.PasswordPolicyRequestControl) SuppressReferentialIntegrityUpdatesRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.SuppressReferentialIntegrityUpdatesRequestControl) AssertionRequestControl(com.unboundid.ldap.sdk.controls.AssertionRequestControl) RouteToBackendSetRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.RouteToBackendSetRequestControl) ManageDsaITRequestControl(com.unboundid.ldap.sdk.controls.ManageDsaITRequestControl) PasswordValidationDetailsRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.PasswordValidationDetailsRequestControl) UniquenessRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.UniquenessRequestControl) GeneratePasswordRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.GeneratePasswordRequestControl) PreReadRequestControl(com.unboundid.ldap.sdk.controls.PreReadRequestControl) LDIFException(com.unboundid.ldif.LDIFException) TransactionSpecificationRequestControl(com.unboundid.ldap.sdk.controls.TransactionSpecificationRequestControl) StartAdministrativeSessionPostConnectProcessor(com.unboundid.ldap.sdk.unboundidds.extensions.StartAdministrativeSessionPostConnectProcessor) LDAPConnectionPool(com.unboundid.ldap.sdk.LDAPConnectionPool) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) LDIFAddChangeRecord(com.unboundid.ldif.LDIFAddChangeRecord) LDAPResult(com.unboundid.ldap.sdk.LDAPResult) MultiUpdateExtendedRequest(com.unboundid.ldap.sdk.unboundidds.extensions.MultiUpdateExtendedRequest) LDAPConnection(com.unboundid.ldap.sdk.LDAPConnection) IOException(java.io.IOException) LDIFModifyChangeRecord(com.unboundid.ldif.LDIFModifyChangeRecord) LDAPSearchException(com.unboundid.ldap.sdk.LDAPSearchException) ArgumentException(com.unboundid.util.args.ArgumentException) LDAPException(com.unboundid.ldap.sdk.LDAPException) IOException(java.io.IOException) LDIFException(com.unboundid.ldif.LDIFException) ProxiedAuthorizationV1RequestControl(com.unboundid.ldap.sdk.controls.ProxiedAuthorizationV1RequestControl) LDIFChangeRecord(com.unboundid.ldif.LDIFChangeRecord) StartAdministrativeSessionExtendedRequest(com.unboundid.ldap.sdk.unboundidds.extensions.StartAdministrativeSessionExtendedRequest) FilterFileReader(com.unboundid.util.FilterFileReader) LDAPException(com.unboundid.ldap.sdk.LDAPException) Filter(com.unboundid.ldap.sdk.Filter) MultiUpdateErrorBehavior(com.unboundid.ldap.sdk.unboundidds.extensions.MultiUpdateErrorBehavior) LDIFReader(com.unboundid.ldif.LDIFReader) StartTransactionExtendedResult(com.unboundid.ldap.sdk.extensions.StartTransactionExtendedResult) StartTransactionExtendedResult(com.unboundid.ldap.sdk.extensions.StartTransactionExtendedResult) ExtendedResult(com.unboundid.ldap.sdk.ExtendedResult) StartTransactionExtendedRequest(com.unboundid.ldap.sdk.extensions.StartTransactionExtendedRequest) LDIFWriter(com.unboundid.ldif.LDIFWriter) FixedRateBarrier(com.unboundid.util.FixedRateBarrier) LDIFDeleteChangeRecord(com.unboundid.ldif.LDIFDeleteChangeRecord) File(java.io.File) ResultCode(com.unboundid.ldap.sdk.ResultCode) NotNull(com.unboundid.util.NotNull)

Example 2 with StartAdministrativeSessionPostConnectProcessor

use of com.unboundid.ldap.sdk.unboundidds.extensions.StartAdministrativeSessionPostConnectProcessor in project ldapsdk by pingidentity.

the class LDAPPasswordModify method doToolProcessing.

/**
 * {@inheritDoc}
 */
@Override()
@NotNull()
public ResultCode doToolProcessing() {
    LDAPConnectionPool pool = null;
    try {
        // before performing the bind.
        try {
            final StartAdministrativeSessionPostConnectProcessor p;
            if (useAdministrativeSession.isPresent()) {
                p = new StartAdministrativeSessionPostConnectProcessor(new StartAdministrativeSessionExtendedRequest(getToolName(), true));
            } else {
                p = null;
            }
            pool = getConnectionPool(1, 2, 0, p, null, true, new ReportBindResultLDAPConnectionPoolHealthCheck(this, true, verbose.isPresent()));
            // Figure out the method to use to update the password.
            final String updateMethod;
            try {
                updateMethod = getPasswordUpdateMethod(pool);
            } catch (final LDAPException e) {
                Debug.debugException(e);
                logCompletionMessage(true, e.getMessage());
                return e.getResultCode();
            }
            switch(updateMethod) {
                case PASSWORD_CHANGE_METHOD_PW_MOD_EXTOP:
                    return doPasswordModifyExtendedOperation(pool);
                case PASSWORD_CHANGE_METHOD_AD:
                    return doLDAPModifyPasswordUpdate(pool, true);
                case PASSWORD_CHANGE_METHOD_LDAP_MOD:
                default:
                    return doLDAPModifyPasswordUpdate(pool, false);
            }
        } catch (final LDAPException le) {
            Debug.debugException(le);
            // If the failure was something else, then display that failure result.
            if (le.getResultCode() != ResultCode.INVALID_CREDENTIALS) {
                for (final String line : ResultUtils.formatResult(le, true, 0, WRAP_COLUMN)) {
                    err(line);
                }
            }
            return le.getResultCode();
        }
    } finally {
        if (pool != null) {
            pool.close();
        }
    }
}
Also used : StartAdministrativeSessionPostConnectProcessor(com.unboundid.ldap.sdk.unboundidds.extensions.StartAdministrativeSessionPostConnectProcessor) LDAPConnectionPool(com.unboundid.ldap.sdk.LDAPConnectionPool) StartAdministrativeSessionExtendedRequest(com.unboundid.ldap.sdk.unboundidds.extensions.StartAdministrativeSessionExtendedRequest) LDAPException(com.unboundid.ldap.sdk.LDAPException) NotNull(com.unboundid.util.NotNull)

Example 3 with StartAdministrativeSessionPostConnectProcessor

use of com.unboundid.ldap.sdk.unboundidds.extensions.StartAdministrativeSessionPostConnectProcessor in project ldapsdk by pingidentity.

the class LDAPSearch method doToolProcessing.

/**
 * {@inheritDoc}
 */
@Override()
@NotNull()
public ResultCode doToolProcessing() {
    // If we should encrypt the output, then get the encryption passphrase.
    if (encryptOutput.isPresent()) {
        if (encryptionPassphraseFile.isPresent()) {
            try {
                encryptionPassphrase = ToolUtils.readEncryptionPassphraseFromFile(encryptionPassphraseFile.getValue());
            } catch (final LDAPException e) {
                Debug.debugException(e);
                wrapErr(0, WRAP_COLUMN, e.getMessage());
                return e.getResultCode();
            }
        } else {
            try {
                encryptionPassphrase = ToolUtils.promptForEncryptionPassphrase(false, true, getOut(), getErr());
            } catch (final LDAPException e) {
                Debug.debugException(e);
                wrapErr(0, WRAP_COLUMN, e.getMessage());
                return e.getResultCode();
            }
        }
    }
    // the header to standard output.
    if (outputFile.isPresent()) {
        if (!separateOutputFilePerSearch.isPresent()) {
            try {
                OutputStream s = new FileOutputStream(outputFile.getValue());
                if (encryptOutput.isPresent()) {
                    s = new PassphraseEncryptedOutputStream(encryptionPassphrase, s);
                }
                if (compressOutput.isPresent()) {
                    s = new GZIPOutputStream(s);
                }
                if (teeResultsToStandardOut.isPresent()) {
                    outStream = new PrintStream(new TeeOutputStream(s, getOut()));
                } else {
                    outStream = new PrintStream(s);
                }
                resultWriter.updateOutputStream(outStream);
                errStream = outStream;
            } catch (final Exception e) {
                Debug.debugException(e);
                wrapErr(0, WRAP_COLUMN, ERR_LDAPSEARCH_CANNOT_OPEN_OUTPUT_FILE.get(outputFile.getValue().getAbsolutePath(), StaticUtils.getExceptionMessage(e)));
                return ResultCode.LOCAL_ERROR;
            }
            resultWriter.writeHeader();
        }
    } else {
        resultWriter.writeHeader();
    }
    // Examine the arguments to determine the sets of controls to use for each
    // type of request.
    final List<Control> searchControls = getSearchControls();
    // If appropriate, ensure that any search result entries that include
    // base64-encoded attribute values will also include comments that attempt
    // to provide a human-readable representation of that value.
    final boolean originalCommentAboutBase64EncodedValues = LDIFWriter.commentAboutBase64EncodedValues();
    LDIFWriter.setCommentAboutBase64EncodedValues(!suppressBase64EncodedValueComments.isPresent());
    LDAPConnectionPool pool = null;
    try {
        // directory server.
        if (!dryRun.isPresent()) {
            try {
                final StartAdministrativeSessionPostConnectProcessor p;
                if (useAdministrativeSession.isPresent()) {
                    p = new StartAdministrativeSessionPostConnectProcessor(new StartAdministrativeSessionExtendedRequest(getToolName(), true));
                } else {
                    p = null;
                }
                pool = getConnectionPool(1, 1, 0, p, null, true, new ReportBindResultLDAPConnectionPoolHealthCheck(this, true, false));
            } catch (final LDAPException le) {
                // This shouldn't happen since the pool won't throw an exception if an
                // attempt to create an initial connection fails.
                Debug.debugException(le);
                commentToErr(ERR_LDAPSEARCH_CANNOT_CREATE_CONNECTION_POOL.get(StaticUtils.getExceptionMessage(le)));
                return le.getResultCode();
            }
            if (retryFailedOperations.isPresent()) {
                pool.setRetryFailedOperationsDueToInvalidConnections(true);
            }
        }
        // If appropriate, create a rate limiter.
        final FixedRateBarrier rateLimiter;
        if (ratePerSecond.isPresent()) {
            rateLimiter = new FixedRateBarrier(1000L, ratePerSecond.getValue());
        } else {
            rateLimiter = null;
        }
        // requests from those URLs.
        if (ldapURLFile.isPresent()) {
            return searchWithLDAPURLs(pool, rateLimiter, searchControls);
        }
        // Get the set of requested attributes, as a combination of the
        // requestedAttribute argument values and any trailing arguments.
        final ArrayList<String> attrList = new ArrayList<>(10);
        if (requestedAttribute.isPresent()) {
            attrList.addAll(requestedAttribute.getValues());
        }
        final List<String> trailingArgs = parser.getTrailingArguments();
        if (!trailingArgs.isEmpty()) {
            final Iterator<String> trailingArgIterator = trailingArgs.iterator();
            if (!(filter.isPresent() || filterFile.isPresent())) {
                trailingArgIterator.next();
            }
            while (trailingArgIterator.hasNext()) {
                attrList.add(trailingArgIterator.next());
            }
        }
        final String[] attributes = new String[attrList.size()];
        attrList.toArray(attributes);
        // If either or both the filter or filterFile arguments are provided, then
        // use them to get the filters to process.  Otherwise, the first trailing
        // argument should be a filter.
        ResultCode resultCode = ResultCode.SUCCESS;
        if (filter.isPresent() || filterFile.isPresent()) {
            if (filter.isPresent()) {
                for (final Filter f : filter.getValues()) {
                    final ResultCode rc = searchWithFilter(pool, f, attributes, rateLimiter, searchControls);
                    if (rc != ResultCode.SUCCESS) {
                        if (resultCode == ResultCode.SUCCESS) {
                            resultCode = rc;
                        }
                        if (!continueOnError.isPresent()) {
                            return resultCode;
                        }
                    }
                }
            }
            if (filterFile.isPresent()) {
                final ResultCode rc = searchWithFilterFile(pool, attributes, rateLimiter, searchControls);
                if (rc != ResultCode.SUCCESS) {
                    if (resultCode == ResultCode.SUCCESS) {
                        resultCode = rc;
                    }
                    if (!continueOnError.isPresent()) {
                        return resultCode;
                    }
                }
            }
        } else {
            final Filter f;
            try {
                final String filterStr = parser.getTrailingArguments().iterator().next();
                f = Filter.create(filterStr);
            } catch (final LDAPException le) {
                // This should never happen.
                Debug.debugException(le);
                displayResult(le.toLDAPResult());
                return le.getResultCode();
            }
            resultCode = searchWithFilter(pool, f, attributes, rateLimiter, searchControls);
        }
        return resultCode;
    } finally {
        if (pool != null) {
            try {
                pool.close();
            } catch (final Exception e) {
                Debug.debugException(e);
            }
        }
        if (outStream != null) {
            try {
                outStream.close();
                outStream = null;
            } catch (final Exception e) {
                Debug.debugException(e);
            }
        }
        if (errStream != null) {
            try {
                errStream.close();
                errStream = null;
            } catch (final Exception e) {
                Debug.debugException(e);
            }
        }
        LDIFWriter.setCommentAboutBase64EncodedValues(originalCommentAboutBase64EncodedValues);
    }
}
Also used : StartAdministrativeSessionPostConnectProcessor(com.unboundid.ldap.sdk.unboundidds.extensions.StartAdministrativeSessionPostConnectProcessor) PrintStream(java.io.PrintStream) TeeOutputStream(com.unboundid.util.TeeOutputStream) LDAPConnectionPool(com.unboundid.ldap.sdk.LDAPConnectionPool) GZIPOutputStream(java.util.zip.GZIPOutputStream) FileOutputStream(java.io.FileOutputStream) TeeOutputStream(com.unboundid.util.TeeOutputStream) PassphraseEncryptedOutputStream(com.unboundid.util.PassphraseEncryptedOutputStream) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) PassphraseEncryptedOutputStream(com.unboundid.util.PassphraseEncryptedOutputStream) LDAPSearchException(com.unboundid.ldap.sdk.LDAPSearchException) ArgumentException(com.unboundid.util.args.ArgumentException) LDAPException(com.unboundid.ldap.sdk.LDAPException) IOException(java.io.IOException) VirtualListViewRequestControl(com.unboundid.ldap.sdk.controls.VirtualListViewRequestControl) RouteToServerRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.RouteToServerRequestControl) RFC3672SubentriesRequestControl(com.unboundid.ldap.sdk.controls.RFC3672SubentriesRequestControl) SimplePagedResultsControl(com.unboundid.ldap.sdk.controls.SimplePagedResultsControl) MatchingEntryCountRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.MatchingEntryCountRequestControl) MatchedValuesRequestControl(com.unboundid.ldap.sdk.controls.MatchedValuesRequestControl) VirtualAttributesOnlyRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.VirtualAttributesOnlyRequestControl) AccountUsableRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.AccountUsableRequestControl) OverrideSearchLimitsRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.OverrideSearchLimitsRequestControl) SuppressOperationalAttributeUpdateRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.SuppressOperationalAttributeUpdateRequestControl) ProxiedAuthorizationV1RequestControl(com.unboundid.ldap.sdk.controls.ProxiedAuthorizationV1RequestControl) OperationPurposeRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.OperationPurposeRequestControl) SoftDeletedEntryAccessRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.SoftDeletedEntryAccessRequestControl) JoinRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.JoinRequestControl) ReturnConflictEntriesRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.ReturnConflictEntriesRequestControl) GetRecentLoginHistoryRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.GetRecentLoginHistoryRequestControl) PermitUnindexedSearchRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.PermitUnindexedSearchRequestControl) RejectUnindexedSearchRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.RejectUnindexedSearchRequestControl) AuthorizationIdentityRequestControl(com.unboundid.ldap.sdk.controls.AuthorizationIdentityRequestControl) Control(com.unboundid.ldap.sdk.Control) GetUserResourceLimitsRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.GetUserResourceLimitsRequestControl) GetBackendSetIDRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.GetBackendSetIDRequestControl) GetAuthorizationEntryRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.GetAuthorizationEntryRequestControl) RealAttributesOnlyRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.RealAttributesOnlyRequestControl) ExcludeBranchRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.ExcludeBranchRequestControl) ProxiedAuthorizationV2RequestControl(com.unboundid.ldap.sdk.controls.ProxiedAuthorizationV2RequestControl) ServerSideSortRequestControl(com.unboundid.ldap.sdk.controls.ServerSideSortRequestControl) GetServerIDRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.GetServerIDRequestControl) PasswordPolicyRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.PasswordPolicyRequestControl) AssertionRequestControl(com.unboundid.ldap.sdk.controls.AssertionRequestControl) RouteToBackendSetRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.RouteToBackendSetRequestControl) ManageDsaITRequestControl(com.unboundid.ldap.sdk.controls.ManageDsaITRequestControl) PersistentSearchRequestControl(com.unboundid.ldap.sdk.controls.PersistentSearchRequestControl) GetEffectiveRightsRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.GetEffectiveRightsRequestControl) DraftLDUPSubentriesRequestControl(com.unboundid.ldap.sdk.controls.DraftLDUPSubentriesRequestControl) StartAdministrativeSessionExtendedRequest(com.unboundid.ldap.sdk.unboundidds.extensions.StartAdministrativeSessionExtendedRequest) LDAPException(com.unboundid.ldap.sdk.LDAPException) GZIPOutputStream(java.util.zip.GZIPOutputStream) Filter(com.unboundid.ldap.sdk.Filter) MatchedValuesFilter(com.unboundid.ldap.sdk.controls.MatchedValuesFilter) FileOutputStream(java.io.FileOutputStream) FixedRateBarrier(com.unboundid.util.FixedRateBarrier) ResultCode(com.unboundid.ldap.sdk.ResultCode) NotNull(com.unboundid.util.NotNull)

Example 4 with StartAdministrativeSessionPostConnectProcessor

use of com.unboundid.ldap.sdk.unboundidds.extensions.StartAdministrativeSessionPostConnectProcessor in project ldapsdk by pingidentity.

the class LDAPDelete method doToolProcessing.

/**
 * {@inheritDoc}
 */
@Override()
@NotNull()
public ResultCode doToolProcessing() {
    // Get the controls that should be included in search and delete requests.
    searchControls = getSearchControls();
    deleteControls = getDeleteControls();
    // barrier.
    if (ratePerSecond.isPresent()) {
        deleteRateLimiter = new FixedRateBarrier(1000L, ratePerSecond.getValue());
    }
    // Create a subtree deleter instance if appropriate.
    if (clientSideSubtreeDelete.isPresent()) {
        subtreeDeleter = new SubtreeDeleter();
        subtreeDeleter.setAdditionalSearchControls(searchControls);
        subtreeDeleter.setAdditionalSearchControls(deleteControls);
        subtreeDeleter.setDeleteRateLimiter(deleteRateLimiter);
        if (searchPageSize.isPresent()) {
            subtreeDeleter.setSimplePagedResultsPageSize(searchPageSize.getValue());
        }
    }
    // If the encryptionPassphraseFile argument was provided, then read that
    // passphrase.
    final char[] encryptionPassphrase;
    if (encryptionPassphraseFile.isPresent()) {
        try {
            encryptionPassphrase = getPasswordFileReader().readPassword(encryptionPassphraseFile.getValue());
        } catch (final LDAPException e) {
            Debug.debugException(e);
            commentToErr(e.getMessage());
            return e.getResultCode();
        } catch (final Exception e) {
            Debug.debugException(e);
            commentToErr(ERR_LDAPDELETE_CANNOT_READ_ENCRYPTION_PW_FILE.get(encryptionPassphraseFile.getValue().getAbsolutePath(), StaticUtils.getExceptionMessage(e)));
            return ResultCode.LOCAL_ERROR;
        }
    } else {
        encryptionPassphrase = null;
    }
    // If the character set argument was specified, then make sure it's valid.
    final Charset charset;
    try {
        charset = Charset.forName(characterSet.getValue());
    } catch (final Exception e) {
        Debug.debugException(e);
        commentToErr(ERR_LDAPDELETE_UNSUPPORTED_CHARSET.get(characterSet.getValue()));
        return ResultCode.PARAM_ERROR;
    }
    // Get the connection pool.
    final StartAdministrativeSessionPostConnectProcessor p;
    if (useAdministrativeSession.isPresent()) {
        p = new StartAdministrativeSessionPostConnectProcessor(new StartAdministrativeSessionExtendedRequest(getToolName(), true));
    } else {
        p = null;
    }
    try {
        connectionPool = getConnectionPool(1, 2, 0, p, null, true, new ReportBindResultLDAPConnectionPoolHealthCheck(this, true, verbose.isPresent()));
        connectionPool.setRetryFailedOperationsDueToInvalidConnections((!neverRetry.isPresent()));
    } catch (final LDAPException e) {
        Debug.debugException(e);
        // If the failure was something else, then display that failure result.
        if (e.getResultCode() != ResultCode.INVALID_CREDENTIALS) {
            for (final String line : ResultUtils.formatResult(e, true, 0, WRAP_COLUMN)) {
                err(line);
            }
        }
        return e.getResultCode();
    }
    // Figure out the method that we'll identify the entries to delete and
    // take the appropriate action.
    final AtomicReference<ResultCode> returnCode = new AtomicReference<>();
    if (entryDN.isPresent()) {
        deleteFromEntryDNArgument(returnCode);
    } else if (dnFile.isPresent()) {
        deleteFromDNFile(returnCode, charset, encryptionPassphrase);
    } else if (deleteEntriesMatchingFilter.isPresent()) {
        deleteFromFilters(returnCode);
    } else if (deleteEntriesMatchingFiltersFromFile.isPresent()) {
        deleteFromFilterFile(returnCode, charset, encryptionPassphrase);
    } else if (!parser.getTrailingArguments().isEmpty()) {
        deleteFromTrailingArguments(returnCode);
    } else {
        deleteFromStandardInput(returnCode, charset, encryptionPassphrase);
    }
    // Close the reject writer.
    final LDIFWriter rw = rejectWriter.get();
    if (rw != null) {
        try {
            rw.close();
        } catch (final Exception e) {
            Debug.debugException(e);
            commentToErr(ERR_LDAPDELETE_ERROR_CLOSING_REJECT_WRITER.get(rejectFile.getValue().getAbsolutePath(), StaticUtils.getExceptionMessage(e)));
            returnCode.compareAndSet(null, ResultCode.LOCAL_ERROR);
        }
    }
    // Close the connection pool.
    connectionPool.close();
    returnCode.compareAndSet(null, ResultCode.SUCCESS);
    return returnCode.get();
}
Also used : StartAdministrativeSessionPostConnectProcessor(com.unboundid.ldap.sdk.unboundidds.extensions.StartAdministrativeSessionPostConnectProcessor) Charset(java.nio.charset.Charset) AtomicReference(java.util.concurrent.atomic.AtomicReference) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) GeneralSecurityException(java.security.GeneralSecurityException) ArgumentException(com.unboundid.util.args.ArgumentException) LDAPException(com.unboundid.ldap.sdk.LDAPException) IOException(java.io.IOException) SubtreeDeleter(com.unboundid.util.SubtreeDeleter) StartAdministrativeSessionExtendedRequest(com.unboundid.ldap.sdk.unboundidds.extensions.StartAdministrativeSessionExtendedRequest) LDAPException(com.unboundid.ldap.sdk.LDAPException) FixedRateBarrier(com.unboundid.util.FixedRateBarrier) LDIFWriter(com.unboundid.ldif.LDIFWriter) ResultCode(com.unboundid.ldap.sdk.ResultCode) NotNull(com.unboundid.util.NotNull)

Example 5 with StartAdministrativeSessionPostConnectProcessor

use of com.unboundid.ldap.sdk.unboundidds.extensions.StartAdministrativeSessionPostConnectProcessor in project ldapsdk by pingidentity.

the class LDAPCompare method doToolProcessing.

/**
 * {@inheritDoc}
 */
@Override()
@NotNull()
public ResultCode doToolProcessing() {
    final List<CompareRequest> compareRequests;
    try {
        compareRequests = getCompareRequests();
    } catch (final LDAPException e) {
        Debug.debugException(e);
        logCompletionMessage(true, e.getMessage());
        return e.getResultCode();
    }
    LDAPConnectionPool pool = null;
    try {
        // before performing the bind.
        try {
            final StartAdministrativeSessionPostConnectProcessor p;
            if (useAdministrativeSession.isPresent()) {
                p = new StartAdministrativeSessionPostConnectProcessor(new StartAdministrativeSessionExtendedRequest(getToolName(), true));
            } else {
                p = null;
            }
            pool = getConnectionPool(1, 2, 0, p, null, true, new ReportBindResultLDAPConnectionPoolHealthCheck(this, true, verbose.isPresent()));
            pool.setRetryFailedOperationsDueToInvalidConnections(true);
            final PrintStream writer;
            if (outputFile.isPresent()) {
                try {
                    writer = new PrintStream(outputFile.getValue());
                } catch (final Exception e) {
                    Debug.debugException(e);
                    logCompletionMessage(true, ERR_LDAPCOMPARE_CANNOT_OPEN_OUTPUT_FILE.get(outputFile.getValue().getAbsolutePath(), StaticUtils.getExceptionMessage(e)));
                    return ResultCode.LOCAL_ERROR;
                }
            } else {
                writer = null;
            }
            final LDAPCompareOutputHandler outputHandler;
            switch(StaticUtils.toLowerCase(outputFormat.getValue())) {
                case OUTPUT_FORMAT_CSV:
                    outputHandler = new LDAPCompareCSVOutputHandler();
                    break;
                case OUTPUT_FORMAT_JSON:
                    outputHandler = new LDAPCompareJSONOutputHandler();
                    break;
                case OUTPUT_FORMAT_TAB_DELIMITED:
                default:
                    outputHandler = new LDAPCompareTabDelimitedOutputHandler();
                    break;
            }
            if (!terse.isPresent()) {
                for (final String line : outputHandler.getHeaderLines()) {
                    if (writer != null) {
                        writer.println(line);
                    }
                    if ((writer == null) || teeOutput.isPresent()) {
                        out(line);
                    }
                }
            }
            ResultCode resultCode = null;
            int numTrue = 0;
            int numFalse = 0;
            int numErrors = 0;
            for (final CompareRequest compareRequest : compareRequests) {
                LDAPResult compareResult;
                try {
                    compareResult = pool.compare(compareRequest);
                } catch (final LDAPException e) {
                    Debug.debugException(e);
                    compareResult = e.toLDAPResult();
                }
                try {
                    writeResult(writer, outputHandler, compareRequest, compareResult);
                } catch (final LDAPException e) {
                    Debug.debugException(e);
                    logCompletionMessage(true, e.getMessage());
                    return e.getResultCode();
                }
                final ResultCode compareResultCode = compareResult.getResultCode();
                if (compareResultCode == ResultCode.COMPARE_TRUE) {
                    numTrue++;
                    if (resultCode == null) {
                        resultCode = ResultCode.COMPARE_TRUE;
                    }
                } else if (compareResultCode == ResultCode.COMPARE_FALSE) {
                    numFalse++;
                    if (resultCode == null) {
                        resultCode = ResultCode.COMPARE_FALSE;
                    }
                } else {
                    numErrors++;
                    if ((resultCode == null) || (resultCode == ResultCode.COMPARE_TRUE) || (resultCode == ResultCode.COMPARE_FALSE)) {
                        resultCode = compareResultCode;
                    }
                    if (!continueOnError.isPresent()) {
                        return resultCode;
                    }
                }
            }
            if (resultCode == ResultCode.COMPARE_TRUE) {
                if (compareRequests.size() > 1) {
                    resultCode = ResultCode.SUCCESS;
                    logCompletionMessage(false, INFO_LDAPCOMPARE_RESULT_ALL_SUCCEEDED.get(numTrue, numFalse));
                } else {
                    if (!useCompareResultCodeAsExitCode.isPresent()) {
                        resultCode = ResultCode.SUCCESS;
                    }
                    logCompletionMessage(false, INFO_LDAPCOMPARE_RESULT_COMPARE_MATCHED.get());
                }
            } else if (resultCode == ResultCode.COMPARE_FALSE) {
                if (compareRequests.size() > 1) {
                    resultCode = ResultCode.SUCCESS;
                    logCompletionMessage(false, INFO_LDAPCOMPARE_RESULT_ALL_SUCCEEDED.get(numTrue, numFalse));
                } else {
                    if (!useCompareResultCodeAsExitCode.isPresent()) {
                        resultCode = ResultCode.SUCCESS;
                    }
                    logCompletionMessage(false, INFO_LDAPCOMPARE_RESULT_COMPARE_DID_NOT_MATCH.get());
                }
            } else {
                if (compareRequests.size() > 1) {
                    logCompletionMessage(true, ERR_LDAPCOMPARE_RESULT_WITH_ERRORS.get(numErrors, numTrue, numFalse));
                } else {
                    logCompletionMessage(true, ERR_LDAPCOMPARE_RESULT_FAILED.get());
                }
            }
            return resultCode;
        } catch (final LDAPException le) {
            Debug.debugException(le);
            // If the failure was something else, then display that failure result.
            if (le.getResultCode() != ResultCode.INVALID_CREDENTIALS) {
                for (final String line : ResultUtils.formatResult(le, true, 0, WRAP_COLUMN)) {
                    err(line);
                }
            }
            return le.getResultCode();
        }
    } finally {
        if (pool != null) {
            pool.close();
        }
    }
}
Also used : StartAdministrativeSessionPostConnectProcessor(com.unboundid.ldap.sdk.unboundidds.extensions.StartAdministrativeSessionPostConnectProcessor) PrintStream(java.io.PrintStream) LDAPConnectionPool(com.unboundid.ldap.sdk.LDAPConnectionPool) LDAPResult(com.unboundid.ldap.sdk.LDAPResult) ArgumentException(com.unboundid.util.args.ArgumentException) LDAPException(com.unboundid.ldap.sdk.LDAPException) IOException(java.io.IOException) CompareRequest(com.unboundid.ldap.sdk.CompareRequest) StartAdministrativeSessionExtendedRequest(com.unboundid.ldap.sdk.unboundidds.extensions.StartAdministrativeSessionExtendedRequest) LDAPException(com.unboundid.ldap.sdk.LDAPException) ResultCode(com.unboundid.ldap.sdk.ResultCode) NotNull(com.unboundid.util.NotNull)

Aggregations

LDAPException (com.unboundid.ldap.sdk.LDAPException)6 StartAdministrativeSessionExtendedRequest (com.unboundid.ldap.sdk.unboundidds.extensions.StartAdministrativeSessionExtendedRequest)6 StartAdministrativeSessionPostConnectProcessor (com.unboundid.ldap.sdk.unboundidds.extensions.StartAdministrativeSessionPostConnectProcessor)6 NotNull (com.unboundid.util.NotNull)6 LDAPConnectionPool (com.unboundid.ldap.sdk.LDAPConnectionPool)5 ResultCode (com.unboundid.ldap.sdk.ResultCode)5 IOException (java.io.IOException)5 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)4 ArgumentException (com.unboundid.util.args.ArgumentException)4 Control (com.unboundid.ldap.sdk.Control)3 FixedRateBarrier (com.unboundid.util.FixedRateBarrier)3 Filter (com.unboundid.ldap.sdk.Filter)2 LDAPResult (com.unboundid.ldap.sdk.LDAPResult)2 LDAPSearchException (com.unboundid.ldap.sdk.LDAPSearchException)2 AssertionRequestControl (com.unboundid.ldap.sdk.controls.AssertionRequestControl)2 AuthorizationIdentityRequestControl (com.unboundid.ldap.sdk.controls.AuthorizationIdentityRequestControl)2 ManageDsaITRequestControl (com.unboundid.ldap.sdk.controls.ManageDsaITRequestControl)2 ProxiedAuthorizationV1RequestControl (com.unboundid.ldap.sdk.controls.ProxiedAuthorizationV1RequestControl)2 ProxiedAuthorizationV2RequestControl (com.unboundid.ldap.sdk.controls.ProxiedAuthorizationV2RequestControl)2 SimplePagedResultsControl (com.unboundid.ldap.sdk.controls.SimplePagedResultsControl)2