use of org.apache.directory.api.ldap.codec.api.MessageDecorator in project directory-ldap-api by apache.
the class LdapNetworkConnection method loadSchema.
/**
* loads schema using the specified schema loader
*
* @param loader the {@link SchemaLoader} to be used to load schema
* @throws LdapException If the schema loading failed
*/
public void loadSchema(SchemaLoader loader) throws LdapException {
try {
SchemaManager tmp = new DefaultSchemaManager(loader);
tmp.loadAllEnabled();
if (!tmp.getErrors().isEmpty() && loader.isStrict()) {
String msg = I18n.err(I18n.ERR_03204_ERROR_LOADING_SCHEMA);
if (LOG.isErrorEnabled()) {
LOG.error("{} {}", msg, Strings.listToString(tmp.getErrors()));
}
throw new LdapException(msg);
}
schemaManager = tmp;
// Change the container's BinaryDetector
ldapSession.setAttribute(LdapDecoder.MESSAGE_CONTAINER_ATTR, new LdapMessageContainer<MessageDecorator<? extends Message>>(codec, new SchemaBinaryAttributeDetector(schemaManager)));
} catch (LdapException le) {
throw le;
} catch (Exception e) {
LOG.error(I18n.err(I18n.ERR_03205_FAIL_LOAD_SCHEMA), e);
throw new LdapException(e);
}
}
use of org.apache.directory.api.ldap.codec.api.MessageDecorator in project directory-ldap-api by apache.
the class LdapNetworkConnection method connect.
// -------------------------- The methods ---------------------------//
/**
* {@inheritDoc}
*/
@Override
public boolean connect() throws LdapException {
if ((ldapSession != null) && connected.get()) {
// No need to connect if we already have a connected session
return true;
}
// Create the connector if needed
if (connector == null) {
createConnector();
}
// Build the connection address
SocketAddress address = new InetSocketAddress(config.getLdapHost(), config.getLdapPort());
// And create the connection future
timeout = config.getTimeout();
long maxRetry = System.currentTimeMillis() + timeout;
ConnectFuture connectionFuture = null;
boolean interrupted = false;
while (maxRetry > System.currentTimeMillis() && !interrupted) {
connectionFuture = connector.connect(address);
boolean result = false;
// Wait until it's established
try {
result = connectionFuture.await(timeout);
} catch (InterruptedException e) {
connector.dispose();
connector = null;
LOG.debug(I18n.msg(I18n.MSG_03221_INTERRUPTED_WAITING_FOR_CONNECTION, config.getLdapHost(), config.getLdapPort()), e);
interrupted = true;
throw new LdapOtherException(e.getMessage(), e);
} finally {
if (result) {
boolean isConnected = connectionFuture.isConnected();
if (!isConnected) {
Throwable connectionException = connectionFuture.getException();
if ((connectionException instanceof ConnectException) || (connectionException instanceof UnresolvedAddressException)) {
// We know that there was a permanent error such as "connection refused".
if (LOG.isDebugEnabled()) {
LOG.debug(I18n.msg(I18n.MSG_03245_CONNECTION_ERROR, connectionFuture.getException().getMessage()));
}
}
if (LOG.isDebugEnabled()) {
LOG.debug(I18n.msg(I18n.MSG_03244_CONNECTION_RETRYING));
}
// Wait 500 ms and retry
try {
Thread.sleep(500);
} catch (InterruptedException e) {
connector = null;
LOG.debug(I18n.msg(I18n.MSG_03221_INTERRUPTED_WAITING_FOR_CONNECTION, config.getLdapHost(), config.getLdapPort()), e);
interrupted = true;
throw new LdapOtherException(e.getMessage(), e);
}
} else {
break;
}
}
}
}
if (connectionFuture == null) {
connector.dispose();
throw new InvalidConnectionException("Cannot connect");
}
boolean isConnected = connectionFuture.isConnected();
if (!isConnected) {
// disposing connector if not connected
try {
close();
} catch (IOException ioe) {
// Nothing to do
}
Throwable e = connectionFuture.getException();
if (e != null) {
StringBuilder message = new StringBuilder("Cannot connect to the server: ");
// (most of the time no message is associated with this exception)
if ((e instanceof UnresolvedAddressException) && (e.getMessage() == null)) {
message.append("Hostname '");
message.append(config.getLdapHost());
message.append("' could not be resolved.");
throw new InvalidConnectionException(message.toString(), e);
}
// Default case
message.append(e.getMessage());
throw new InvalidConnectionException(message.toString(), e);
}
return false;
}
// Get the close future for this session
CloseFuture closeFuture = connectionFuture.getSession().getCloseFuture();
// Add a listener to close the session in the session.
closeFuture.addListener(new IoFutureListener<IoFuture>() {
@Override
public void operationComplete(IoFuture future) {
// Process all the waiting operations and cancel them
LOG.debug(I18n.msg(I18n.MSG_03238_NOD_RECEIVED));
for (ResponseFuture<?> responseFuture : futureMap.values()) {
LOG.debug(I18n.msg(I18n.MSG_03235_CLOSING, responseFuture));
responseFuture.cancel();
try {
if (responseFuture instanceof AddFuture) {
((AddFuture) responseFuture).set(AddNoDResponse.PROTOCOLERROR);
} else if (responseFuture instanceof BindFuture) {
((BindFuture) responseFuture).set(BindNoDResponse.PROTOCOLERROR);
} else if (responseFuture instanceof CompareFuture) {
((CompareFuture) responseFuture).set(CompareNoDResponse.PROTOCOLERROR);
} else if (responseFuture instanceof DeleteFuture) {
((DeleteFuture) responseFuture).set(DeleteNoDResponse.PROTOCOLERROR);
} else if (responseFuture instanceof ExtendedFuture) {
((ExtendedFuture) responseFuture).set(ExtendedNoDResponse.PROTOCOLERROR);
} else if (responseFuture instanceof ModifyFuture) {
((ModifyFuture) responseFuture).set(ModifyNoDResponse.PROTOCOLERROR);
} else if (responseFuture instanceof ModifyDnFuture) {
((ModifyDnFuture) responseFuture).set(ModifyDnNoDResponse.PROTOCOLERROR);
} else if (responseFuture instanceof SearchFuture) {
((SearchFuture) responseFuture).set(SearchNoDResponse.PROTOCOLERROR);
}
} catch (InterruptedException e) {
LOG.error(I18n.err(I18n.ERR_03202_ERROR_PROCESSING_NOD, responseFuture), e);
}
futureMap.remove(messageId.get());
}
futureMap.clear();
}
});
// Get back the session
ldapSession = connectionFuture.getSession();
connected.set(true);
// Store the container into the session if we don't have one
@SuppressWarnings("unchecked") LdapMessageContainer<MessageDecorator<? extends Message>> container = (LdapMessageContainer<MessageDecorator<? extends Message>>) ldapSession.getAttribute(LdapDecoder.MESSAGE_CONTAINER_ATTR);
if (container != null) {
if ((schemaManager != null) && !(container.getBinaryAttributeDetector() instanceof SchemaBinaryAttributeDetector)) {
container.setBinaryAttributeDetector(new SchemaBinaryAttributeDetector(schemaManager));
}
} else {
BinaryAttributeDetector atDetector = new DefaultConfigurableBinaryAttributeDetector();
if (schemaManager != null) {
atDetector = new SchemaBinaryAttributeDetector(schemaManager);
}
ldapSession.setAttribute(LdapDecoder.MESSAGE_CONTAINER_ATTR, new LdapMessageContainer<MessageDecorator<? extends Message>>(codec, atDetector));
}
// Initialize the MessageId
messageId.set(0);
// And return
return true;
}
use of org.apache.directory.api.ldap.codec.api.MessageDecorator in project directory-ldap-api by apache.
the class SearchRequestDecorator method unstackFilters.
/**
* This method is used to clear the filter's stack for terminated elements. An element
* is considered as terminated either if :
* - it's a final element (ie an element which cannot contains a Filter)
* - its current length equals its expected length.
*
* @param container The container being decoded
*/
@SuppressWarnings("unchecked")
public void unstackFilters(Asn1Container container) {
LdapMessageContainer<MessageDecorator<Message>> ldapMessageContainer = (LdapMessageContainer<MessageDecorator<Message>>) container;
TLV tlv = ldapMessageContainer.getCurrentTLV();
TLV localParent = tlv.getParent();
Filter localFilter = terminalFilter;
// The parent has been completed, so fold it
while ((localParent != null) && (localParent.getExpectedLength() == 0)) {
int parentTlvId = localFilter.getParent() != null ? localFilter.getParent().getTlvId() : localFilter.getParentTlvId();
if (localParent.getId() != parentTlvId) {
localParent = localParent.getParent();
} else {
Filter filterParent = localFilter.getParent();
// pushed on the stack, so we need to get its parent's parent
if (localFilter instanceof PresentFilter) {
if (filterParent == null) {
// We don't have parent, get out
break;
}
filterParent = filterParent.getParent();
} else {
filterParent = filterParent.getParent();
}
if (filterParent != null) {
// The parent is a filter ; it will become the new currentFilter
// and we will loop again.
localFilter = currentFilter;
currentFilter = filterParent;
localParent = localParent.getParent();
} else {
// We can stop the recursion, we have reached the searchResult Object
break;
}
}
}
}
use of org.apache.directory.api.ldap.codec.api.MessageDecorator in project directory-ldap-api by apache.
the class BindRequestTest method testDecodeBindRequestBadDN.
/**
* Test the decoding of a BindRequest with Simple authentication and
* controls
*/
@Test
public void testDecodeBindRequestBadDN() {
Asn1Decoder ldapDecoder = new Asn1Decoder();
ByteBuffer stream = ByteBuffer.allocate(0x35);
stream.put(new byte[] { 0x30, // LDAPMessage ::=SEQUENCE {
0x33, 0x02, 0x01, // messageID MessageID
0x01, 0x60, // CHOICE { ..., bindRequest BindRequest, ...
0x2E, // BindRequest ::= APPLICATION[0] SEQUENCE {
0x02, 0x01, // version INTEGER (1..127),
0x03, 0x04, // name LDAPDN,
0x1F, 'u', 'i', 'd', ':', 'a', 'k', 'a', 'r', 'a', 's', 'u', 'l', 'u', ',', 'd', 'c', '=', 'e', 'x', 'a', 'm', 'p', 'l', 'e', ',', 'd', 'c', '=', 'c', 'o', 'm', (byte) 0x80, // authentication AuthenticationChoice
0x08, // ...
'p', 'a', 's', 's', 'w', 'o', 'r', 'd' });
stream.flip();
// Allocate a LdapMessage Container
LdapMessageContainer<MessageDecorator<? extends Message>> container = new LdapMessageContainer<MessageDecorator<? extends Message>>(codec);
// Decode the BindRequest PDU
try {
ldapDecoder.decode(stream, container);
BindRequest bindRequest = ((BindRequestDecorator) container.getMessage());
assertNull(bindRequest.getDn());
assertEquals("uid:akarasulu,dc=example,dc=com", bindRequest.getName());
} catch (DecoderException de) {
assertTrue(de instanceof ResponseCarryingException);
Message response = ((ResponseCarryingException) de).getResponse();
assertTrue(response instanceof BindResponseImpl);
assertEquals(ResultCodeEnum.INVALID_DN_SYNTAX, ((BindResponseImpl) response).getLdapResult().getResultCode());
return;
}
}
use of org.apache.directory.api.ldap.codec.api.MessageDecorator in project directory-ldap-api by apache.
the class LdapDecoderTest method testDecodeBadLengthTooSmall.
/**
* Test the decoding of a PDU with a bad Length. The first TLV has a length
* of 0x32 when the PDU is 0x33 bytes long.
*/
@Test
public void testDecodeBadLengthTooSmall() {
Asn1Decoder ldapDecoder = new Asn1Decoder();
ByteBuffer stream = ByteBuffer.allocate(0x35);
stream.put(new byte[] { // Length should be 0x33...
0x30, // LDAPMessage ::=SEQUENCE {
0x32, 0x02, 0x01, // messageID MessageID
0x01, 0x60, // CHOICE { ..., bindRequest BindRequest, ...
0x2E, // BindRequest ::= APPLICATION[0] SEQUENCE {
0x02, 0x01, // version INTEGER (1..127),
0x03, 0x04, // name LDAPDN,
0x1F, 'u', 'i', 'd', '=', 'a', 'k', 'a', 'r', 'a', 's', 'u', 'l', 'u', ',', 'd', 'c', '=', 'e', 'x', 'a', 'm', 'p', 'l', 'e', ',', 'd', 'c', '=', 'c', 'o', 'm', (byte) 0x80, // authentication
0x08, // ...
'p', 'a', 's', 's', 'w', 'o', 'r', 'd' });
stream.flip();
// Allocate a LdapMessage Container
LdapMessageContainer<MessageDecorator<? extends Message>> ldapMessageContainer = new LdapMessageContainer<MessageDecorator<? extends Message>>(codec);
// Decode a BindRequest PDU
try {
ldapDecoder.decode(stream, ldapMessageContainer);
} catch (DecoderException de) {
assertEquals("ERR_01003_VALUE_LENGTH_ABOVE_EXPECTED_LENGTH The current Value length 48 is above the expected length 47", de.getMessage());
return;
}
fail("Should never reach this point..");
}
Aggregations