Search in sources :

Example 41 with Nullable

use of com.unboundid.util.Nullable in project ldapsdk by pingidentity.

the class LDAPMessage method readLDAPResponseFrom.

/**
 * Reads {@link LDAPResponse} object from the provided ASN.1 stream reader.
 *
 * @param  reader               The ASN.1 stream reader from which the LDAP
 *                              message should be read.
 * @param  ignoreSocketTimeout  Indicates whether to ignore socket timeout
 *                              exceptions caught during processing.  This
 *                              should be {@code true} when the associated
 *                              connection is operating in asynchronous mode,
 *                              and {@code false} when operating in
 *                              synchronous mode.  In either case, exceptions
 *                              will not be ignored for the first read, since
 *                              that will be handled by the connection reader.
 * @param  schema               The schema to use to select the appropriate
 *                              matching rule for attributes included in the
 *                              response.
 *
 * @return  The decoded LDAP message, or {@code null} if the end of the input
 *          stream has been reached.
 *
 * @throws  LDAPException  If an error occurs while attempting to read or
 *                         decode the LDAP message.
 */
@Nullable()
public static LDAPResponse readLDAPResponseFrom(@NotNull final ASN1StreamReader reader, final boolean ignoreSocketTimeout, @Nullable final Schema schema) throws LDAPException {
    final ASN1StreamReaderSequence messageSequence;
    try {
        reader.setIgnoreSocketTimeout(false, ignoreSocketTimeout);
        messageSequence = reader.beginSequence();
        if (messageSequence == null) {
            return null;
        }
    } catch (final IOException ioe) {
        final ResultCode resultCode;
        if (ioe instanceof SocketTimeoutException) {
            resultCode = ResultCode.TIMEOUT;
        } else {
            Debug.debugException(ioe);
            resultCode = ResultCode.SERVER_DOWN;
        }
        throw new LDAPException(resultCode, ERR_MESSAGE_IO_ERROR.get(StaticUtils.getExceptionMessage(ioe)), ioe);
    } catch (final Exception e) {
        Debug.debugException(e);
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_MESSAGE_CANNOT_DECODE.get(StaticUtils.getExceptionMessage(e)), e);
    }
    try {
        reader.setIgnoreSocketTimeout(ignoreSocketTimeout, ignoreSocketTimeout);
        final int messageID = reader.readInteger();
        final byte protocolOpType = (byte) reader.peek();
        switch(protocolOpType) {
            case PROTOCOL_OP_TYPE_ADD_RESPONSE:
            case PROTOCOL_OP_TYPE_DELETE_RESPONSE:
            case PROTOCOL_OP_TYPE_MODIFY_RESPONSE:
            case PROTOCOL_OP_TYPE_MODIFY_DN_RESPONSE:
                return InternalSDKHelper.readLDAPResultFrom(messageID, messageSequence, reader);
            case PROTOCOL_OP_TYPE_BIND_RESPONSE:
                return InternalSDKHelper.readBindResultFrom(messageID, messageSequence, reader);
            case PROTOCOL_OP_TYPE_COMPARE_RESPONSE:
                return InternalSDKHelper.readCompareResultFrom(messageID, messageSequence, reader);
            case PROTOCOL_OP_TYPE_EXTENDED_RESPONSE:
                return InternalSDKHelper.readExtendedResultFrom(messageID, messageSequence, reader);
            case PROTOCOL_OP_TYPE_SEARCH_RESULT_ENTRY:
                return InternalSDKHelper.readSearchResultEntryFrom(messageID, messageSequence, reader, schema);
            case PROTOCOL_OP_TYPE_SEARCH_RESULT_REFERENCE:
                return InternalSDKHelper.readSearchResultReferenceFrom(messageID, messageSequence, reader);
            case PROTOCOL_OP_TYPE_SEARCH_RESULT_DONE:
                return InternalSDKHelper.readSearchResultFrom(messageID, messageSequence, reader);
            case PROTOCOL_OP_TYPE_INTERMEDIATE_RESPONSE:
                return InternalSDKHelper.readIntermediateResponseFrom(messageID, messageSequence, reader);
            case PROTOCOL_OP_TYPE_ABANDON_REQUEST:
            case PROTOCOL_OP_TYPE_ADD_REQUEST:
            case PROTOCOL_OP_TYPE_BIND_REQUEST:
            case PROTOCOL_OP_TYPE_COMPARE_REQUEST:
            case PROTOCOL_OP_TYPE_DELETE_REQUEST:
            case PROTOCOL_OP_TYPE_EXTENDED_REQUEST:
            case PROTOCOL_OP_TYPE_MODIFY_REQUEST:
            case PROTOCOL_OP_TYPE_MODIFY_DN_REQUEST:
            case PROTOCOL_OP_TYPE_SEARCH_REQUEST:
            case PROTOCOL_OP_TYPE_UNBIND_REQUEST:
                throw new LDAPException(ResultCode.DECODING_ERROR, ERR_MESSAGE_PROTOCOL_OP_TYPE_NOT_RESPONSE.get(StaticUtils.toHex(protocolOpType)));
            default:
                throw new LDAPException(ResultCode.DECODING_ERROR, ERR_MESSAGE_INVALID_PROTOCOL_OP_TYPE.get(StaticUtils.toHex(protocolOpType)));
        }
    } catch (final LDAPException le) {
        Debug.debugException(le);
        throw le;
    } catch (final IOException ioe) {
        Debug.debugException(ioe);
        if ((ioe instanceof SocketTimeoutException) || (ioe instanceof InterruptedIOException)) {
            // connection to be terminated.
            throw new LDAPException(ResultCode.DECODING_ERROR, ERR_MESSAGE_CANNOT_DECODE.get(StaticUtils.getExceptionMessage(ioe)));
        } else {
            throw new LDAPException(ResultCode.SERVER_DOWN, ERR_MESSAGE_IO_ERROR.get(StaticUtils.getExceptionMessage(ioe)), ioe);
        }
    } catch (final Exception e) {
        Debug.debugException(e);
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_MESSAGE_CANNOT_DECODE.get(StaticUtils.getExceptionMessage(e)), e);
    }
}
Also used : ASN1StreamReaderSequence(com.unboundid.asn1.ASN1StreamReaderSequence) InterruptedIOException(java.io.InterruptedIOException) SocketTimeoutException(java.net.SocketTimeoutException) LDAPException(com.unboundid.ldap.sdk.LDAPException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ResultCode(com.unboundid.ldap.sdk.ResultCode) InterruptedIOException(java.io.InterruptedIOException) SocketTimeoutException(java.net.SocketTimeoutException) LDAPException(com.unboundid.ldap.sdk.LDAPException) IOException(java.io.IOException) Nullable(com.unboundid.util.Nullable)

Example 42 with Nullable

use of com.unboundid.util.Nullable in project ldapsdk by pingidentity.

the class ChangeLogEntry method parseModificationList.

/**
 * Parses the modification list from a changelog entry representing a modify
 * operation.
 *
 * @param  entry     The entry containing the data to parse.
 * @param  targetDN  The DN of the target entry.
 *
 * @return  The parsed modification list, or {@code null} if the changelog
 *          entry does not include any modifications.
 *
 * @throws  LDAPException  If an error occurs while parsing the modification
 *                         list.
 */
@Nullable()
private static List<Modification> parseModificationList(@NotNull final Entry entry, @NotNull final String targetDN) throws LDAPException {
    final Attribute changesAttr = entry.getAttribute(ATTR_CHANGES);
    if ((changesAttr == null) || (!changesAttr.hasValue())) {
        return null;
    }
    final byte[] valueBytes = changesAttr.getValueByteArray();
    if (valueBytes.length == 0) {
        return null;
    }
    final ArrayList<String> ldifLines = new ArrayList<>(20);
    ldifLines.add("dn: " + targetDN);
    ldifLines.add("changetype: modify");
    // Even though it's a violation of the specification in
    // draft-good-ldap-changelog, it appears that some servers (e.g., Sun DSEE)
    // may terminate the changes value with a null character (\u0000).  If that
    // is the case, then we'll need to strip it off before trying to parse it.
    final StringTokenizer tokenizer;
    if ((valueBytes.length > 0) && (valueBytes[valueBytes.length - 1] == 0x00)) {
        final String fullValue = changesAttr.getValue();
        final String realValue = fullValue.substring(0, fullValue.length() - 2);
        tokenizer = new StringTokenizer(realValue, "\r\n");
    } else {
        tokenizer = new StringTokenizer(changesAttr.getValue(), "\r\n");
    }
    while (tokenizer.hasMoreTokens()) {
        ldifLines.add(tokenizer.nextToken());
    }
    final String[] lineArray = new String[ldifLines.size()];
    ldifLines.toArray(lineArray);
    try {
        final LDIFModifyChangeRecord changeRecord = (LDIFModifyChangeRecord) LDIFReader.decodeChangeRecord(lineArray);
        return Collections.unmodifiableList(Arrays.asList(changeRecord.getModifications()));
    } catch (final LDIFException le) {
        Debug.debugException(le);
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_CHANGELOG_CANNOT_PARSE_MOD_LIST.get(ATTR_CHANGES, StaticUtils.getExceptionMessage(le)), le);
    }
}
Also used : StringTokenizer(java.util.StringTokenizer) ArrayList(java.util.ArrayList) LDIFException(com.unboundid.ldif.LDIFException) LDIFModifyChangeRecord(com.unboundid.ldif.LDIFModifyChangeRecord) Nullable(com.unboundid.util.Nullable)

Example 43 with Nullable

use of com.unboundid.util.Nullable in project ldapsdk by pingidentity.

the class CompareRequest method processAsync.

/**
 * Sends this compare request to the directory server over the provided
 * connection and returns the message ID for the request.
 *
 * @param  connection      The connection to use to communicate with the
 *                         directory server.
 * @param  resultListener  The async result listener that is to be notified
 *                         when the response is received.  It may be
 *                         {@code null} only if the result is to be processed
 *                         by this class.
 *
 * @return  The async request ID created for the operation, or {@code null} if
 *          the provided {@code resultListener} is {@code null} and the
 *          operation will not actually be processed asynchronously.
 *
 * @throws  LDAPException  If a problem occurs while sending the request.
 */
@Nullable()
AsyncRequestID processAsync(@NotNull final LDAPConnection connection, @Nullable final AsyncCompareResultListener resultListener) throws LDAPException {
    // Create the LDAP message.
    messageID = connection.nextMessageID();
    final LDAPMessage message = new LDAPMessage(messageID, this, getControls());
    // If the provided async result listener is {@code null}, then we'll use
    // this class as the message acceptor.  Otherwise, create an async helper
    // and use it as the message acceptor.
    final AsyncRequestID asyncRequestID;
    final long timeout = getResponseTimeoutMillis(connection);
    if (resultListener == null) {
        asyncRequestID = null;
        connection.registerResponseAcceptor(messageID, this);
    } else {
        final AsyncCompareHelper compareHelper = new AsyncCompareHelper(connection, messageID, resultListener, getIntermediateResponseListener());
        connection.registerResponseAcceptor(messageID, compareHelper);
        asyncRequestID = compareHelper.getAsyncRequestID();
        if (timeout > 0L) {
            final Timer timer = connection.getTimer();
            final AsyncTimeoutTimerTask timerTask = new AsyncTimeoutTimerTask(compareHelper);
            timer.schedule(timerTask, timeout);
            asyncRequestID.setTimerTask(timerTask);
        }
    }
    // Send the request to the server.
    try {
        Debug.debugLDAPRequest(Level.INFO, this, messageID, connection);
        final LDAPConnectionLogger logger = connection.getConnectionOptions().getConnectionLogger();
        if (logger != null) {
            logger.logCompareRequest(connection, messageID, this);
        }
        connection.getConnectionStatistics().incrementNumCompareRequests();
        connection.sendMessage(message, timeout);
        return asyncRequestID;
    } catch (final LDAPException le) {
        Debug.debugException(le);
        connection.deregisterResponseAcceptor(messageID);
        throw le;
    }
}
Also used : Timer(java.util.Timer) LDAPMessage(com.unboundid.ldap.protocol.LDAPMessage) Nullable(com.unboundid.util.Nullable)

Example 44 with Nullable

use of com.unboundid.util.Nullable in project ldapsdk by pingidentity.

the class LDAPObjectHandler method getEntryDN.

/**
 * Retrieves the DN of the entry in which the provided object is stored, if
 * available.  The entry DN will not be available if the provided object was
 * not retrieved using the persistence framework, or if the associated class
 * (or one of its superclasses) does not have a field marked with either the
 * {@link LDAPDNField} or {@link LDAPEntryField} annotation.
 *
 * @param  o  The object for which to retrieve the associated entry DN.
 *
 * @return  The DN of the entry in which the provided object is stored, or
 *          {@code null} if that is not available.
 *
 * @throws  LDAPPersistException  If a problem occurred while attempting to
 *                                obtain the entry DN.
 */
@Nullable()
public String getEntryDN(@NotNull final T o) throws LDAPPersistException {
    final String dnFieldValue = getDNFieldValue(o);
    if (dnFieldValue != null) {
        return dnFieldValue;
    }
    final ReadOnlyEntry entry = getEntry(o);
    if (entry != null) {
        return entry.getDN();
    }
    return null;
}
Also used : ReadOnlyEntry(com.unboundid.ldap.sdk.ReadOnlyEntry) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) Nullable(com.unboundid.util.Nullable)

Example 45 with Nullable

use of com.unboundid.util.Nullable in project ldapsdk by pingidentity.

the class LDAPPersister method searchForObject.

/**
 * Performs a search in the directory to retrieve the object whose contents
 * match the contents of the provided object.  It is expected that at most one
 * entry matches the provided criteria, and that it can be decoded as an
 * object of the associated type.  If multiple entries match the resulting
 * criteria, or if the matching entry cannot be decoded as the associated type
 * of object, then an exception will be thrown.
 * <BR><BR>
 * A search filter will be generated from the provided object containing all
 * non-{@code null} values from fields and getter methods whose
 * {@link LDAPField} or {@link LDAPGetter} annotation has the {@code inFilter}
 * element set to {@code true}.
 *
 * @param  o            The object to use to construct the search filter.  It
 *                      must not be {@code null}.
 * @param  i            The connection to use to communicate with the
 *                      directory server.  It must not be {@code null}.
 * @param  baseDN       The base DN to use for the search.  It may be
 *                      {@code null} if the {@link LDAPObject#defaultParentDN}
 *                      element in the {@code LDAPObject} should be used as
 *                      the base DN.
 * @param  scope        The scope to use for the search operation.  It must
 *                      not be {@code null}.
 * @param  derefPolicy  The dereference policy to use for the search
 *                      operation.  It must not be {@code null}.
 * @param  sizeLimit    The maximum number of entries to retrieve from the
 *                      directory.  A value of zero indicates that no
 *                      client-requested size limit should be enforced.
 * @param  timeLimit    The maximum length of time in seconds that the server
 *                      should spend processing the search.  A value of zero
 *                      indicates that no client-requested time limit should
 *                      be enforced.
 * @param  extraFilter  An optional additional filter to be ANDed with the
 *                      filter generated from the provided object.  If this is
 *                      {@code null}, then only the filter generated from the
 *                      object will be used.
 * @param  controls     An optional set of controls to include in the search
 *                      request.  It may be empty or {@code null} if no
 *                      controls are needed.
 *
 * @return  The object constructed from the entry returned by the search, or
 *          {@code null} if no entry was returned.
 *
 * @throws  LDAPPersistException  If an error occurs while preparing or
 *                                sending the search request or decoding the
 *                                entry that was returned.
 */
@Nullable()
public T searchForObject(@NotNull final T o, @NotNull final LDAPInterface i, @Nullable final String baseDN, @NotNull final SearchScope scope, @NotNull final DereferencePolicy derefPolicy, final int sizeLimit, final int timeLimit, @Nullable final Filter extraFilter, @Nullable final Control... controls) throws LDAPPersistException {
    Validator.ensureNotNull(o, i, scope, derefPolicy);
    final String base;
    if (baseDN == null) {
        base = handler.getDefaultParentDN().toString();
    } else {
        base = baseDN;
    }
    final Filter filter;
    if (extraFilter == null) {
        filter = handler.createFilter(o);
    } else {
        filter = Filter.simplifyFilter(Filter.createANDFilter(handler.createFilter(o), extraFilter), true);
    }
    final SearchRequest searchRequest = new SearchRequest(base, scope, derefPolicy, sizeLimit, timeLimit, false, filter, handler.getAttributesToRequest());
    if (controls != null) {
        searchRequest.setControls(controls);
    }
    try {
        final Entry e = i.searchForEntry(searchRequest);
        if (e == null) {
            return null;
        } else {
            return decode(e);
        }
    } catch (final LDAPPersistException lpe) {
        Debug.debugException(lpe);
        throw lpe;
    } catch (final LDAPException le) {
        Debug.debugException(le);
        throw new LDAPPersistException(le);
    }
}
Also used : SearchRequest(com.unboundid.ldap.sdk.SearchRequest) Entry(com.unboundid.ldap.sdk.Entry) LDAPException(com.unboundid.ldap.sdk.LDAPException) Filter(com.unboundid.ldap.sdk.Filter) Nullable(com.unboundid.util.Nullable)

Aggregations

Nullable (com.unboundid.util.Nullable)149 ArrayList (java.util.ArrayList)47 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)42 Entry (com.unboundid.ldap.sdk.Entry)30 LDAPException (com.unboundid.ldap.sdk.LDAPException)30 ASN1Sequence (com.unboundid.asn1.ASN1Sequence)21 Attribute (com.unboundid.ldap.sdk.Attribute)21 ASN1Element (com.unboundid.asn1.ASN1Element)20 Filter (com.unboundid.ldap.sdk.Filter)20 SearchResult (com.unboundid.ldap.sdk.SearchResult)18 IOException (java.io.IOException)16 ReadOnlyEntry (com.unboundid.ldap.sdk.ReadOnlyEntry)14 File (java.io.File)14 DN (com.unboundid.ldap.sdk.DN)12 ArgumentException (com.unboundid.util.args.ArgumentException)10 RDN (com.unboundid.ldap.sdk.RDN)9 LDIFException (com.unboundid.ldif.LDIFException)8 ChangeLogEntry (com.unboundid.ldap.sdk.ChangeLogEntry)7 Modification (com.unboundid.ldap.sdk.Modification)7 LDIFModifyChangeRecord (com.unboundid.ldif.LDIFModifyChangeRecord)7