Java Code Examples for org.apache.directory.api.util.Strings#isEmpty()

The following examples show how to use org.apache.directory.api.util.Strings#isEmpty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GrokServiceImpl.java    From metron with Apache License 2.0 6 votes vote down vote up
@Override
public GrokValidation validateGrokStatement(GrokValidation grokValidation) throws RestException {
    Map<String, Object> results;
    try {
        if (grokValidation.getPatternLabel() == null) {
          throw new RestException("Pattern label is required");
        }
        if (Strings.isEmpty(grokValidation.getStatement())) {
          throw new RestException("Grok statement is required");
        }
        Grok grok = new Grok();
        grok.addPatternFromReader(new InputStreamReader(getClass().getResourceAsStream(
            "/patterns/common"), StandardCharsets.UTF_8));
        grok.addPatternFromReader(new StringReader(grokValidation.getStatement()));
        String grokPattern = "%{" + grokValidation.getPatternLabel() + "}";
        grok.compile(grokPattern);
        Match gm = grok.match(grokValidation.getSampleData());
        gm.captures();
        results = gm.toMap();
        results.remove(grokValidation.getPatternLabel());
    } catch (Exception e) {
        throw new RestException(e);
    }
    grokValidation.setResults(results);
    return grokValidation;
}
 
Example 2
Source File: DefaultEntry.java    From MyVirtualDirectory with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Creates a new instance of DefaultEntry, schema aware.
 * </p>
 * <p>
 * No attributes will be created.
 * </p>
 *
 * @param schemaManager The reference to the schemaManager
 * @param dn The String Dn for this serverEntry. Can be null.
 * @throws LdapInvalidDnException If the Dn is invalid
 */
public DefaultEntry( SchemaManager schemaManager, String dn ) throws LdapInvalidDnException
{
    this.schemaManager = schemaManager;

    if ( Strings.isEmpty( dn ) )
    {
        this.dn = Dn.EMPTY_DN;
    }
    else
    {
        this.dn = new Dn( dn );
        normalizeDN( this.dn );
    }

    // Initialize the ObjectClass object
    initObjectClassAT();
}
 
Example 3
Source File: StoreSearchRequestAttributeDesc.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void action( LdapMessageContainer<SearchRequest> container )
{
    SearchRequest searchRequest = container.getMessage();
    TLV tlv = container.getCurrentTLV();
    String attributeDescription = null;

    if ( tlv.getLength() != 0 )
    {
        attributeDescription = Strings.utf8ToString( tlv.getValue().getData() );

        // If the attributeDescription is empty, we won't add it
        if ( !Strings.isEmpty( attributeDescription.trim() ) )
        {
            searchRequest.addAttributes( attributeDescription );
        }
    }

    // We can have an END transition
    container.setGrammarEndAllowed( true );

    if ( LOG.isDebugEnabled() )
    {
        LOG.debug( I18n.msg( I18n.MSG_05159_DECODED_ATT_DESC, attributeDescription ) );
    }
}
 
Example 4
Source File: BerValue.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Encode an OctetString
 *
 * @param buffer The PDU in which the value will be put
 * @param data The byte[] to be encoded
 */
public static void encodeOctetString( Asn1Buffer buffer, byte[] data )
{
    if ( Strings.isEmpty( data ) )
    {
        buffer.put( ( byte ) 0 );
    }
    else
    {
        buffer.put( data );
        buffer.put( TLV.getBytes( data.length ) );
    }

    buffer.put( UniversalTag.OCTET_STRING.getValue() );
}
 
Example 5
Source File: Dsmlv2ResponseGrammar.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void action( Dsmlv2Container container ) throws XmlPullParserException
{
    ExtendedResponse extendedResponse = ( ExtendedResponse ) container.getBatchResponse().getCurrentResponse();

    XmlPullParser xpp = container.getParser();

    try
    {
        String nextText = xpp.nextText();

        if ( !Strings.isEmpty( nextText ) )
        {
            extendedResponse.setResponseName( Oid.fromString( nextText.trim() ).toString() );
        }

    }
    catch ( IOException ioe )
    {
        throw new XmlPullParserException( I18n.err( I18n.ERR_03008_UNEXPECTED_ERROR, ioe.getMessage() ), xpp, ioe );
    }
    catch ( DecoderException de )
    {
        throw new XmlPullParserException( de.getMessage(), xpp, de );
    }
}
 
Example 6
Source File: SearchRequestHandler.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
/**
 * Manage the abandoned Paged Search (when paged size = 0). We have to
 * remove the cookie and its associated cursor from the session.
 */
private SearchResultDone abandonPagedSearch( LdapSession session, SearchRequest req ) throws Exception
{
    PagedResults pagedSearchControl = ( PagedResults ) req.getControls().get( PagedResults.OID );
    byte[] cookie = pagedSearchControl.getCookie();

    if ( !Strings.isEmpty( cookie ) )
    {
        // If the cookie is not null, we have to destroy the associated
        // cursor stored into the session (if any)
        int cookieValue = pagedSearchControl.getCookieValue();
        PagedSearchContext psCookie = session.removePagedSearchContext( cookieValue );
        pagedSearchControl.setCookie( psCookie.getCookie() );
        pagedSearchControl.setSize( 0 );
        pagedSearchControl.setCritical( true );

        // Close the cursor
        EntryFilteringCursor cursor = psCookie.getCursor();

        if ( cursor != null )
        {
            cursor.close();
        }
    }
    else
    {
        pagedSearchControl.setSize( 0 );
        pagedSearchControl.setCritical( true );
    }

    // and return
    // DO NOT WRITE THE RESPONSE - JUST RETURN IT
    LdapResult ldapResult = req.getResultResponse().getLdapResult();
    ldapResult.setResultCode( ResultCodeEnum.SUCCESS );
    req.getResultResponse().addControl( pagedSearchControl );
    return req.getResultResponse();
}
 
Example 7
Source File: DefaultEntry.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void add( String upId, Value<?>... values ) throws LdapException
{
    if ( Strings.isEmpty( upId ) )
    {
        String message = I18n.err( I18n.ERR_04457_NULL_ATTRIBUTE_ID );
        LOG.error( message );
        throw new IllegalArgumentException( message );
    }

    // First, transform the upID to a valid ID
    String id = getId( upId );

    if ( schemaManager != null )
    {
        add( upId, schemaManager.lookupAttributeTypeRegistry( upId ), values );
    }
    else
    {
        // Now, check to see if we already have such an attribute
        Attribute attribute = attributes.get( id );

        if ( attribute != null )
        {
            // This Attribute already exist, we add the values
            // into it. (If the values already exists, they will
            // not be added, but this is done in the add() method)
            attribute.add( values );
            attribute.setUpId( upId );
        }
        else
        {
            // We have to create a new Attribute and set the values
            // and the upId
            attributes.put( id, new DefaultAttribute( upId, values ) );
        }
    }
}
 
Example 8
Source File: Dsmlv2Grammar.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void action( Dsmlv2Container container ) throws XmlPullParserException
{
    AbstractRequestDsml<? extends Request> request =
        ( AbstractRequestDsml<? extends Request> ) container.getBatchRequest().getCurrentRequest();
    DsmlControl<? extends Control> control = request.getCurrentControl();

    XmlPullParser xpp = container.getParser();

    try
    {
        // We have to catch the type Attribute Value before going to the next Text node
        String typeValue = ParserUtils.getXsiTypeAttributeValue( xpp );

        // Getting the value
        String nextText = xpp.nextText();

        if ( !Strings.isEmpty( nextText ) )
        {
            if ( ParserUtils.isBase64BinaryValue( xpp, typeValue ) )
            {
                control.setValue( Base64.decode( nextText.trim().toCharArray() ) );
            }
            else
            {
                control.setValue( Strings.getBytesUtf8( nextText.trim() ) );
            }
        }
    }
    catch ( IOException ioe )
    {
        throw new XmlPullParserException( I18n.err( I18n.ERR_03008_UNEXPECTED_ERROR, ioe.getMessage() ), xpp, ioe );
    }
}
 
Example 9
Source File: DefaultEntry.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the attributeType from an Attribute ID.
 *
 * @param upId The ID we are looking for
 * @return The found attributeType
 * @throws LdapException If the lookup failed
 */
protected AttributeType getAttributeType( String upId ) throws LdapException
{
    if ( Strings.isEmpty( Strings.trim( upId ) ) )
    {
        String message = I18n.err( I18n.ERR_13204_NULL_ATTRIBUTE_ID );
        LOG.error( message );
        throw new IllegalArgumentException( message );
    }

    return schemaManager.lookupAttributeTypeRegistry( upId );
}
 
Example 10
Source File: LoadableSchemaObject.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Test that the FQCN is equal to the instance's name. If the FQCN is
 * empty, fill it with the instance's name
 *
 * @return true if the FQCN is correctly set
 */
public boolean isValid()
{
    String className = this.getClass().getName();

    if ( Strings.isEmpty( fqcn ) )
    {
        fqcn = className;
        return true;
    }
    else
    {
        return className.equals( fqcn );
    }
}
 
Example 11
Source File: SubstringFilter.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public StringBuilder build( StringBuilder builder )
{
    builder.append( "(" ).append( attribute ).append( '=' );

    if ( !Strings.isEmpty( initial ) )
    {
        builder.append( FilterEncoder.encodeFilterValue( initial ) );
    }

    if ( any != null )
    {
        for ( String string : any )
        {
            builder.append( '*' ).append( FilterEncoder.encodeFilterValue( string ) );
        }
    }

    builder.append( '*' );

    if ( !Strings.isEmpty( end ) )
    {
        builder.append( FilterEncoder.encodeFilterValue( end ) );
    }

    builder.append( ")" );

    return builder;
}
 
Example 12
Source File: DefaultEntry.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the attributeType from an Attribute ID.
 */
protected AttributeType getAttributeType( String upId ) throws LdapException
{
    if ( Strings.isEmpty( Strings.trim( upId ) ) )
    {
        String message = I18n.err( I18n.ERR_04457_NULL_ATTRIBUTE_ID );
        LOG.error( message );
        throw new IllegalArgumentException( message );
    }

    return schemaManager.lookupAttributeTypeRegistry( upId );
}
 
Example 13
Source File: BerValue.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Encode an OctetString
 *
 * @param buffer The PDU in which the value will be put
 * @param tag The tag to use
 * @param data The OctetString to be encoded
 */
public static void encodeOctetString( Asn1Buffer buffer, byte tag, byte[] data )
{
    if ( Strings.isEmpty( data ) )
    {
        buffer.put( ( byte ) 0 );
    }
    else
    {
        buffer.put( data );
        buffer.put( TLV.getBytes( data.length ) );
    }

    buffer.put( tag );
}
 
Example 14
Source File: AbstractLdapConnection.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Create a complete BindRequest ready to be sent.
 *
 * @param name The DN to bind with
 * @param credentials The user's password
 * @param saslMechanism The SASL mechanism to use
 * @param controls The controls to send
 * @return The created BindRequest
 */
protected BindRequest createBindRequest( String name, byte[] credentials, String saslMechanism, Control... controls )
{
    // Set the new messageId
    BindRequest bindRequest = new BindRequestImpl();

    // Set the version
    bindRequest.setVersion3( true );

    // Set the name
    bindRequest.setName( name );

    // Set the credentials
    if ( Strings.isEmpty( saslMechanism ) )
    {
        // Simple bind
        bindRequest.setSimple( true );
        bindRequest.setCredentials( credentials );
    }
    else
    {
        // SASL bind
        bindRequest.setSimple( false );
        bindRequest.setCredentials( credentials );
        bindRequest.setSaslMechanism( saslMechanism );
    }

    // Add the controls
    if ( ( controls != null ) && ( controls.length != 0 ) )
    {
        bindRequest.addAllControls( controls );
    }

    return bindRequest;
}
 
Example 15
Source File: DefaultEntry.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * <p>
 * Removes the specified binary values from an attribute.
 * </p>
 * <p>
 * If at least one value is removed, this method returns <code>true</code>.
 * </p>
 * <p>
 * If there is no more value after having removed the values, the attribute
 * will be removed too.
 * </p>
 * <p>
 * If the attribute does not exist, nothing is done and the method returns
 * <code>false</code>
 * </p>
 *
 * @param upId The attribute ID
 * @param values the values to be removed
 * @return <code>true</code> if at least a value is removed, <code>false</code>
 * if not all the values have been removed or if the attribute does not exist.
 */
@Override
public boolean remove( String upId, byte[]... values ) throws LdapException
{
    if ( Strings.isEmpty( upId ) )
    {
        if ( LOG.isInfoEnabled() )
        {
            LOG.info( I18n.err( I18n.ERR_13204_NULL_ATTRIBUTE_ID ) );
        }

        return false;
    }

    if ( schemaManager == null )
    {
        String id = getId( upId );

        Attribute attribute = get( id );

        if ( attribute == null )
        {
            // Can't remove values from a not existing attribute !
            return false;
        }

        int nbOldValues = attribute.size();

        // Remove the values
        attribute.remove( values );

        if ( attribute.size() == 0 )
        {
            // No mare values, remove the attribute
            attributes.remove( id );

            return true;
        }

        return nbOldValues != attribute.size();
    }
    else
    {
        try
        {
            AttributeType attributeType = getAttributeType( upId );

            return remove( attributeType, values );
        }
        catch ( LdapException ne )
        {
            LOG.error( I18n.err( I18n.ERR_13205_CANNOT_REMOVE_VAL_MISSING_ATTR, upId ) );
            return false;
        }
        catch ( IllegalArgumentException iae )
        {
            LOG.error( I18n.err( I18n.ERR_13206_CANNOT_REMOVE_VAL_BAD_ATTR, upId ) );
            return false;
        }
    }

}
 
Example 16
Source File: BindRequestImpl.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean equals( Object obj )
{
    if ( obj == this )
    {
        return true;
    }

    if ( !( obj instanceof BindRequest ) )
    {
        return false;
    }

    if ( !super.equals( obj ) )
    {
        return false;
    }

    BindRequest req = ( BindRequest ) obj;

    if ( req.isSimple() != isSimple() )
    {
        return false;
    }

    if ( req.isVersion3() != isVersion3() )
    {
        return false;
    }

    String name1 = req.getName();
    String name2 = getName();

    if ( Strings.isEmpty( name1 ) )
    {
        if ( !Strings.isEmpty( name2 ) )
        {
            return false;
        }
    }
    else
    {
        if ( Strings.isEmpty( name2 ) )
        {
            return false;
        }
        else if ( !name2.equals( name1 ) )
        {
            return false;
        }
    }

    Dn dn1 = req.getDn();
    Dn dn2 = getDn();

    if ( Dn.isNullOrEmpty( dn1 ) )
    {
        if ( !Dn.isNullOrEmpty( dn2 ) )
        {
            return false;
        }
    }
    else
    {
        if ( Dn.isNullOrEmpty( dn2 ) )
        {
            return false;
        }
        else if ( !dn1.equals( dn2 ) )
        {
            return false;
        }
    }

    return Arrays.equals( req.getCredentials(), getCredentials() );
}
 
Example 17
Source File: DefaultEntry.java    From MyVirtualDirectory with Apache License 2.0 4 votes vote down vote up
/**
 * <p>
 * Removes the specified values from an attribute.
 * </p>
 * <p>
 * If at least one value is removed, this method returns <code>true</code>.
 * </p>
 * <p>
 * If there is no more value after having removed the values, the attribute
 * will be removed too.
 * </p>
 * <p>
 * If the attribute does not exist, nothing is done and the method returns
 * <code>false</code>
 * </p>
 *
 * @param upId The attribute ID
 * @param values the attributes to be removed
 * @return <code>true</code> if at least a value is removed, <code>false</code>
 * if not all the values have been removed or if the attribute does not exist.
 */
public boolean remove( String upId, Value<?>... values ) throws LdapException
{
    if ( Strings.isEmpty( upId ) )
    {
        String message = I18n.err( I18n.ERR_04457_NULL_ATTRIBUTE_ID );
        LOG.info( message );
        return false;
    }

    if ( schemaManager == null )
    {
        String id = getId( upId );

        Attribute attribute = get( id );

        if ( attribute == null )
        {
            // Can't remove values from a not existing attribute !
            return false;
        }

        int nbOldValues = attribute.size();

        // Remove the values
        attribute.remove( values );

        if ( attribute.size() == 0 )
        {
            // No mare values, remove the attribute
            attributes.remove( id );

            return true;
        }

        return nbOldValues != attribute.size();
    }
    else
    {
        try
        {
            AttributeType attributeType = getAttributeType( upId );

            return remove( attributeType, values );
        }
        catch ( LdapException ne )
        {
            LOG.error( I18n.err( I18n.ERR_04465, upId ) );
            return false;
        }
        catch ( IllegalArgumentException iae )
        {
            LOG.error( I18n.err( I18n.ERR_04466, upId ) );
            return false;
        }
    }
}
 
Example 18
Source File: DefaultAttribute.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void apply( AttributeType attributeType ) throws LdapInvalidAttributeValueException
{
    if ( attributeType == null )
    {
        throw new IllegalArgumentException( I18n.err( I18n.ERR_13245_AT_PARAMETER_NULL ) );
    }

    this.attributeType = attributeType;
    this.id = attributeType.getOid();

    if ( Strings.isEmpty( this.upId ) )
    {
        this.upId = attributeType.getName();
    }
    else
    {
        if ( !areCompatible( this.upId, attributeType ) )
        {
            this.upId = attributeType.getName();
        }
    }

    if ( values != null )
    {
        Set<Value> newValues = new LinkedHashSet<>( values.size() );

        for ( Value value : values )
        {
            if ( value.isSchemaAware() )
            {
                newValues.add( value );
            }
            else
            {
                if ( value.isHumanReadable() )
                {
                    newValues.add( new Value( attributeType, value.getString() ) );
                }
                else
                {
                    newValues.add( new Value( attributeType, value.getBytes() ) );
                }
            }
        }

        values = newValues;
    }

    isHR = attributeType.getSyntax().isHumanReadable();

    // Compute the hashCode
    rehash();
}
 
Example 19
Source File: Dn.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new instance of schema aware Dn, using varargs to declare the RDNs. Each
 * String is either a full Rdn, or a couple of AttributeType DI and a value.
 * If the String contains a '=' symbol, the the constructor will assume that
 * the String arg contains afull Rdn, otherwise, it will consider that the
 * following arg is the value.<br>
 * The created Dn is Schema aware.
 * <br><br>
 * An example of usage would be :
 * <pre>
 * String exampleName = "example";
 * String baseDn = "dc=apache,dc=org";
 *
 * Dn dn = new Dn( DefaultSchemaManager.INSTANCE,
 *     "cn=Test",
 *     "ou", exampleName,
 *     baseDn);
 * </pre>
 *
 * @param schemaManager the schema manager
 * @param upRdns The list of String composing the Dn
 * @throws LdapInvalidDnException If the resulting Dn is invalid
 */
public Dn( SchemaManager schemaManager, String... upRdns ) throws LdapInvalidDnException
{
    StringBuilder sbUpName = new StringBuilder();
    boolean valueExpected = false;
    boolean isFirst = true;
    this.schemaManager = schemaManager;

    for ( String upRdn : upRdns )
    {
        if ( Strings.isEmpty( upRdn ) )
        {
            continue;
        }

        if ( isFirst )
        {
            isFirst = false;
        }
        else if ( !valueExpected )
        {
            sbUpName.append( ',' );
        }

        if ( !valueExpected )
        {
            sbUpName.append( upRdn );

            if ( upRdn.indexOf( '=' ) == -1 )
            {
                valueExpected = true;
            }
        }
        else
        {
            sbUpName.append( "=" ).append( upRdn );

            valueExpected = false;
        }
    }

    if ( !isFirst && valueExpected )
    {
        throw new LdapInvalidDnException( ResultCodeEnum.INVALID_DN_SYNTAX, I18n.err( I18n.ERR_13611_VALUE_MISSING_ON_RDN ) );
    }

    // Stores the representations of a Dn : internal (as a string and as a
    // byte[]) and external.
    upName = sbUpName.toString();

    try
    {
        normName = parseInternal( schemaManager, upName, rdns );
    }
    catch ( LdapInvalidDnException e )
    {
        if ( schemaManager == null || !schemaManager.isRelaxed() )
        {
            throw e;
        }
        // Ignore invalid DN formats in relaxed mode.
        // This is needed to support unbelievably insane
        // DN formats such as <GUI=abcd...> format used by
        // Active Directory
    }
}
 
Example 20
Source File: Ava.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * Deserialize an AVA from a byte[], starting at a given position
 * 
 * @param buffer The buffer containing the AVA
 * @param pos The position in the buffer
 * @return The new position
 * @throws IOException If the serialized value is not an AVA
 * @throws LdapInvalidAttributeValueException If the serialized AVA is invalid
 */
public int deserialize( byte[] buffer, int pos ) throws IOException, LdapInvalidAttributeValueException
{
    if ( ( pos < 0 ) || ( pos >= buffer.length ) )
    {
        throw new ArrayIndexOutOfBoundsException();
    }

    // Read the upName value, if it's not null
    boolean hasUpName = Serialize.deserializeBoolean( buffer, pos );
    pos++;

    if ( hasUpName )
    {
        byte[] wrappedValueBytes = Serialize.deserializeBytes( buffer, pos );
        pos += 4 + wrappedValueBytes.length;
        upName = Strings.utf8ToString( wrappedValueBytes );
    }

    // Read the upType value, if it's not null
    boolean hasUpType = Serialize.deserializeBoolean( buffer, pos );
    pos++;

    if ( hasUpType )
    {
        byte[] upTypeBytes = Serialize.deserializeBytes( buffer, pos );
        pos += 4 + upTypeBytes.length;
        upType = Strings.utf8ToString( upTypeBytes );
    }

    // Update the AtributeType
    if ( schemaManager != null )
    {
        if ( !Strings.isEmpty( upType ) )
        {
            attributeType = schemaManager.getAttributeType( upType );
        }
        else
        {
            attributeType = schemaManager.getAttributeType( normType );
        }
    }

    if ( attributeType != null )
    {
        normType = attributeType.getOid();
    }
    else
    {
        normType = upType;
    }

    // Read the isHR flag
    boolean isHR = Serialize.deserializeBoolean( buffer, pos );
    pos++;

    if ( isHR )
    {
        // Read the upValue
        value = Value.createValue( attributeType );
        pos = value.deserialize( buffer, pos );
    }

    // Read the hashCode
    h = Serialize.deserializeInt( buffer, pos );
    pos += 4;

    return pos;
}