text:
package org.apache.directory.server.replication;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.directory.api.ldap.codec.api.LdapApiService;
import org.apache.directory.api.ldap.codec.api.LdapApiServiceFactory;
import org.apache.directory.api.ldap.extras.controls.SyncModifyDnType;
import org.apache.directory.api.ldap.extras.controls.SynchronizationModeEnum;
import org.apache.directory.api.ldap.extras.controls.syncrepl.syncDone.SyncDoneValue;
import org.apache.directory.api.ldap.extras.controls.syncrepl.syncInfoValue.SyncInfoValue;
import org.apache.directory.api.ldap.extras.controls.syncrepl.syncInfoValue.SyncRequestValue;
import org.apache.directory.api.ldap.extras.controls.syncrepl.syncState.SyncStateTypeEnum;
import org.apache.directory.api.ldap.extras.controls.syncrepl.syncState.SyncStateValue;
import org.apache.directory.api.ldap.extras.controls.syncrepl_impl.SyncInfoValueDecorator;
import org.apache.directory.api.ldap.extras.controls.syncrepl_impl.SyncRequestValueDecorator;
import org.apache.directory.api.ldap.model.constants.Loggers;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.entry.Attribute;
import org.apache.directory.api.ldap.model.entry.DefaultAttribute;
import org.apache.directory.api.ldap.model.entry.DefaultModification;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.entry.Modification;
import org.apache.directory.api.ldap.model.entry.ModificationOperation;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.filter.AndNode;
import org.apache.directory.api.ldap.model.filter.EqualityNode;
import org.apache.directory.api.ldap.model.filter.ExprNode;
import org.apache.directory.api.ldap.model.filter.NotNode;
import org.apache.directory.api.ldap.model.filter.OrNode;
import org.apache.directory.api.ldap.model.filter.PresenceNode;
import org.apache.directory.api.ldap.model.message.IntermediateResponse;
import org.apache.directory.api.ldap.model.message.Response;
import org.apache.directory.api.ldap.model.message.ResultCodeEnum;
import org.apache.directory.api.ldap.model.message.SearchRequest;
import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
import org.apache.directory.api.ldap.model.message.SearchResultDone;
import org.apache.directory.api.ldap.model.message.SearchResultEntry;
import org.apache.directory.api.ldap.model.message.SearchResultReference;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.api.ldap.model.name.Rdn;
import org.apache.directory.api.ldap.model.schema.AttributeType;
import org.apache.directory.api.ldap.model.schema.AttributeTypeOptions;
import org.apache.directory.api.ldap.model.schema.SchemaManager;
import org.apache.directory.api.util.Strings;
import org.apache.directory.ldap.client.api.ConnectionClosedEventListener;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.apache.directory.ldap.client.api.future.SearchFuture;
import org.apache.directory.server.core.api.DirectoryService;
import org.apache.directory.server.core.api.filtering.EntryFilteringCursor;
import org.apache.directory.server.ldap.LdapProtocolUtils;
import org.apache.directory.server.ldap.replication.ReplicationConsumerConfig;
import org.apache.directory.server.ldap.replication.SyncReplConfiguration;
import org.apache.directory.server.ldap.replication.consumer.ReplicationConsumer;
import org.apache.directory.server.ldap.replication.consumer.ReplicationStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * Implementation of syncrepl slave a.k.a consumer.
 *
 * @author Apache Directory Project
 */
public class MockSyncReplConsumer implements ConnectionClosedEventListener, ReplicationConsumer
{
    /** the logger */
    private static final Logger LOG = LoggerFactory.getLogger( MockSyncReplConsumer.class );

    /** A dedicated logger for the consumer */
    private static final Logger CONSUMER_LOG = LoggerFactory.getLogger( Loggers.CONSUMER_LOG.getName() );

    /** The codec */
    private LdapApiService ldapCodecService = LdapApiServiceFactory.getSingleton();

    /** the syncrepl configuration */
    private SyncReplConfiguration config;

    /** A field used to tell the thread it should stop */
    private volatile boolean stop = false;

    /** A mutex used to make the thread sleeping for a moment */
    private final Object mutex = new Object();

    /** the sync cookie sent by the server */
    private byte[] syncCookie;

    /** connection to the syncrepl provider */
    private LdapNetworkConnection connection;

    /** the search request with control */
    private SearchRequest searchRequest;

    /** the schema manager */
    private SchemaManager schemaManager;

    /** the cookie file */
    private File cookieFile;

    /** flag to indicate whether the consumer was disconnected */
    private boolean disconnected;

    /** The number of added entries */
    private AtomicInteger nbAdded = new AtomicInteger( 0 );

    private File cookieDir;

    public static String COOKIES_DIR_NAME = "cookies";

    /** attributes on which modification should be ignored */
    private static final String[] MOD_IGNORE_AT = new String[]
        {
            SchemaConstants.ENTRY_UUID_AT,
            SchemaConstants.ENTRY_CSN_AT,
            SchemaConstants.MODIFIERS_NAME_AT,
            SchemaConstants.MODIFY_TIMESTAMP_AT,
            SchemaConstants.CREATE_TIMESTAMP_AT,
            SchemaConstants.CREATORS_NAME_AT,
            SchemaConstants.ENTRY_PARENT_ID_AT
    };

    /** A thread used to refresh in refreshOnly mode */
    private RefresherThread refreshThread;

    /** the cookie that was saved last time */
    private byte[] lastSavedCookie;

    /** The (entrtyUuid=*) filter */
    private static final PresenceNode ENTRY_UUID_PRESENCE_FILTER = new PresenceNode( SchemaConstants.ENTRY_UUID_AT );

    /** The set used for search attributes, containing only the entryUuid AT */
    private static final Set<AttributeTypeOptions> ENTRY_UUID_ATOP_SET = new HashSet<AttributeTypeOptions>();

    private List<Modification> cookieModLst;

    /** AttributeTypes used for replication */
    private static AttributeType COOKIE_AT_TYPE;
    private static AttributeType ENTRY_UUID_AT;

    /**
     * @return the config
     */
    public SyncReplConfiguration getConfig()
    {
        return config;
    }

    /**
     * Init the replication service
     * @param directoryservice The directory service
     */
    public void init( DirectoryService directoryService ) throws Exception
    {
        this.schemaManager = directoryService.getSchemaManager();
        ENTRY_UUID_AT = schemaManager.lookupAttributeTypeRegistry( SchemaConstants.ENTRY_UUID_AT );
        COOKIE_AT_TYPE = schemaManager.lookupAttributeTypeRegistry( SchemaConstants.ADS_REPL_COOKIE );

        ENTRY_UUID_ATOP_SET.add( new AttributeTypeOptions( ENTRY_UUID_AT ) );

        Attribute cookieAttr = new DefaultAttribute( COOKIE_AT_TYPE );

        Modification cookieMod = new DefaultModification( ModificationOperation.REPLACE_ATTRIBUTE, cookieAttr );
        cookieModLst = new ArrayList<Modification>( 1 );
        cookieModLst.add( cookieMod );

        cookieDir = new File( System.getProperty( "java.io.tmpdir" ) + "/" + COOKIES_DIR_NAME );
        cookieDir.mkdirs();

        prepareSyncSearchRequest();
    }

    /**
     * Connect to the remote server. Note that a SyncRepl consumer will be connected to only
     * one remote server
     *
     * @return true if the connections have been successful.
     */
    public boolean connect()
    {
        try
        {
            String providerHost = config.getRemoteHost();
            int port = config.getRemotePort();

            // Create a connection
            if ( connection == null )
            {
                connection = new LdapNetworkConnection( providerHost, port );
                connection.setTimeOut( -1L );

                if ( config.isUseTls() )
                {
                    connection.getConfig().setTrustManagers( config.getTrustManager() );
                    connection.startTls();
                }

                connection.addConnectionClosedEventListener( this );
            }

            // Try to connect
            if ( connection.connect() )
            {
                CONSUMER_LOG.info( "Consumer {} connected to producer {}", config.getReplicaId(), config.getProducer() );

                // Do a bind
                try
                {
                    connection.bind( config.getReplUserDn(), Strings.utf8ToString( config.getReplUserPassword() ) );
                    disconnected = false;

                    return true;
                }
                catch ( LdapException le )
                {
                    CONSUMER_LOG.warn( "Failed to bind to the producer {} with the given bind Dn {}",
                        config.getProducer(), config.getReplUserDn() );
                    LOG.warn( "Failed to bind to the server with the given bind Dn {}", config.getReplUserDn() );
                    LOG.warn( "", le );
                    disconnected = true;
                }
            }
            else
            {
                CONSUMER_LOG.warn( "Consumer {} cannot connect to producer {}", config.getReplicaId(),
                    config.getProducer() );
                disconnected = true;

                return false;
            }
        }
        catch ( Exception e )
        {
            CONSUMER_LOG.error( "Failed to connect to the server {}, cause : {}", config.getProducer(), e.getMessage() );
            LOG.error( "Failed to connect to the server {}, cause : {}", config.getProducer(), e.getMessage() );
            disconnected = true;
        }

        return false;
    }

    /**
     *
     *  prepares a SearchRequest for syncing DIT content.
     *
     */
    public void prepareSyncSearchRequest() throws LdapException
    {
        String baseDn = config.getBaseDn();

        searchRequest = new SearchRequestImpl();

        searchRequest.setBase( new Dn( baseDn ) );
        searchRequest.setFilter( config.getFilter() );
        searchRequest.setSizeLimit( config.getSearchSizeLimit() );
        searchRequest.setTimeLimit( config.getSearchTimeout() );

        searchRequest.setDerefAliases( config.getAliasDerefMode() );
        searchRequest.setScope( config.getSearchScope() );
        searchRequest.setTypesOnly( false );

        searchRequest.addAttributes( config.getAttributes() );
    }

    public ResultCodeEnum handleSearchDone( SearchResultDone searchDone )
    {
        LOG.debug( "///////////////// handleSearchDone //////////////////" );

        SyncDoneValue ctrl = ( SyncDoneValue ) searchDone.getControls().get( SyncDoneValue.OID );

        if ( ( ctrl != null ) && ( ctrl.getCookie() != null ) )
        {
            syncCookie = ctrl.getCookie();
            LOG.debug( "assigning cookie from sync done value control: " + Strings.utf8ToString( syncCookie ) );
            storeCookie();
        }

        LOG.debug( "//////////////// END handleSearchDone//////////////////////" );

        return searchDone.getLdapResult().getResultCode();
    }

    public void handleSearchReference( SearchResultReference searchRef )
    {
        // this method won't be called cause the provider will serve the referrals as
        // normal entry objects due to the usage of ManageDsaITControl in the search request
    }

    public void handleSearchResult( SearchResultEntry syncResult )
    {
        LOG.debug( "------------- starting handleSearchResult ------------" );

        SyncStateValue syncStateCtrl = ( SyncStateValue ) syncResult.getControl( SyncStateValue.OID );

        try
        {
            Entry remoteEntry = syncResult.getEntry();

            if ( syncStateCtrl.getCookie() != null )
            {
                syncCookie = syncStateCtrl.getCookie();
                LOG.debug( "assigning the cookie from sync state value control: "
                    + Strings.utf8ToString( syncCookie ) );
            }

            SyncStateTypeEnum state = syncStateCtrl.getSyncStateType();

            LOG.debug( "state name {}", state.name() );

            // check to avoid conversion of UUID from byte[] to String
            if ( LOG.isDebugEnabled() )
            {
                LOG.debug( "entryUUID = {}", Strings.uuidToString( syncStateCtrl.getEntryUUID() ) );
            }

            switch ( state )
            {
                case ADD:
                    LOG.debug( "adding entry with dn {}, {}", remoteEntry.getDn().getName(), remoteEntry );
                    nbAdded.getAndIncrement();
                    break;

                case MODIFY:
                    LOG.debug( "modifying entry with dn {}", remoteEntry.getDn().getName() );
                    modify( remoteEntry );
                    break;

                case MODDN:
                    String entryUuid = Strings.uuidToString( syncStateCtrl.getEntryUUID() );
                    applyModDnOperation( remoteEntry, entryUuid );

                    break;

                case DELETE:
                    LOG.debug( "deleting entry with dn {}", remoteEntry.getDn().getName() );
                    // incase of a MODDN operation resulting in a branch to be moved out of scope
                    // ApacheDS replication provider sends a single delete event on the Dn of the moved branch
                    // so the branch needs to be recursively deleted here
                    deleteRecursive( remoteEntry.getDn(), null );
                    break;

                case PRESENT:
                    LOG.debug( "entry present {}", remoteEntry );
                    break;
            }

            // store the cookie only if the above operation was successful
            if ( syncStateCtrl.getCookie() != null )
            {
                storeCookie();
            }
        }
        catch ( Exception e )
        {
            LOG.error( e.getMessage(), e );
        }

        LOG.debug( "------------- Ending handleSearchResult ------------" );
    }

    /**
     * {@inheritDoc}
     */
    public void handleSyncInfo( IntermediateResponse syncInfoResp )
    {
        try
        {
            LOG.debug( "............... inside handleSyncInfo ..............." );

            byte[] syncInfoBytes = syncInfoResp.getResponseValue();

            if ( syncInfoBytes == null )
            {
                return;
            }

            SyncInfoValueDecorator decorator = new SyncInfoValueDecorator( ldapCodecService );
            SyncInfoValue syncInfoValue = ( SyncInfoValue ) decorator.decode( syncInfoBytes );

            byte[] cookie = syncInfoValue.getCookie();

            int replicaId = -1;

            if ( cookie != null )
            {
                LOG.debug( "setting the cookie from the sync info: " + Strings.utf8ToString( cookie ) );
                syncCookie = cookie;

                String cookieString = Strings.utf8ToString( syncCookie );
                replicaId = LdapProtocolUtils.getReplicaId( cookieString );
            }

            LOG.info( "refreshDeletes: " + syncInfoValue.isRefreshDeletes() );

            List<byte[]> uuidList = syncInfoValue.getSyncUUIDs();

            // if refreshDeletes set to true then delete all the entries with entryUUID
            // present in the syncIdSet
            if ( syncInfoValue.isRefreshDeletes() )
            {
                deleteEntries( uuidList, false );
            }
            else
            {
                deleteEntries( uuidList, true );
            }

            LOG.info( "refreshDone: " + syncInfoValue.isRefreshDone() );

            storeCookie();
        }
        catch ( Exception de )
        {
            LOG.error( "Failed to handle syncinfo message", de );
        }

        LOG.debug( ".................... END handleSyncInfo ..............." );
    }

    /**
     * {@inheritDoc}
     */
    public void connectionClosed()
    {
        if ( disconnected )
        {
            return;
        }

        boolean connected = false;

        while ( !connected )
        {
            try
            {
                Thread.sleep( config.getRefreshInterval() );
            }
            catch ( InterruptedException e )
            {
                LOG.error( "Interrupted while sleeping before trying to reconnect", e );
            }

            LOG.debug( "Trying to reconnect" );
            connected = connect();
        }

        startSync();
    }

    /**
     * starts the synchronization operation
     */
    public ReplicationStatusEnum startSync()
    {
        // read the cookie if persisted
        readCookie();

        if ( config.isRefreshNPersist() )
        {
            try
            {
                LOG.debug( "==================== Refresh And Persist ==========" );

                return doSyncSearch( SynchronizationModeEnum.REFRESH_AND_PERSIST, false );
            }
            catch ( Exception e )
            {
                LOG.error( "Failed to sync with refreshAndPersist mode", e );
                return ReplicationStatusEnum.DISCONNECTED;
            }
        }
        else
        {
            return doRefreshOnly();
        }
    }

    private ReplicationStatusEnum doRefreshOnly()
    {
        while ( !stop )
        {
            LOG.debug( "==================== Refresh Only ==========" );

            try
            {
                doSyncSearch( SynchronizationModeEnum.REFRESH_ONLY, false );

                LOG.info( "--------------------- Sleep for a little while ------------------" );
                mutex.wait( config.getRefreshInterval() );
                LOG.debug( "--------------------- syncing again ------------------" );

            }
            catch ( InterruptedException ie )
            {
                LOG.warn( "refresher thread interrupted" );
                return ReplicationStatusEnum.DISCONNECTED;
            }
            catch ( Exception e )
            {
                LOG.error( "Failed to sync with refresh only mode", e );
                return ReplicationStatusEnum.DISCONNECTED;
            }
        }

        return ReplicationStatusEnum.STOPPED;
    }

    /**
     * {@inheritDoc}
     */
    public void setConfig( ReplicationConsumerConfig config )
    {
        this.config = ( SyncReplConfiguration ) config;
    }

    /**
     * {@inheritDoc}
     */
    public void ping()
    {
        boolean connected = !disconnected;

        if ( disconnected )
        {
            connected = connect();
        }

        if ( connected )
        {
            CONSUMER_LOG.debug( "PING : The consumer {} is alive", config.getReplicaId() );

            try
            {
                Entry baseDn = connection.lookup( config.getBaseDn(), "1.1" );

                if ( baseDn == null )
                {
                    // Cannot get the entry : this is bad, but possible
                    CONSUMER_LOG.debug( "Cannot fetch '{}' from provider for consumer {}", config.getBaseDn(),
                        config.getReplicaId() );
                }
                else
                {
                    CONSUMER_LOG.debug( "Fetched '{}' from provider for consumer {}", config.getBaseDn(),
                        config.getReplicaId() );
                }
            }
            catch ( LdapException le )
            {
                // Error : we must disconnect
                disconnect();
            }
        }
        else
        {
            CONSUMER_LOG.debug( "PING : The consumer {} cannot be connected", config.getReplicaId() );
        }
    }

    /**
     * {@inheritDoc}
     */
    public boolean connect( boolean now )
    {
        boolean connected = false;

        if ( now )
        {
            connected = connect();
        }

        while ( !connected )
        {
            try
            {
                // try to establish a connection for every 5 seconds
                Thread.sleep( 5000 );
            }
            catch ( InterruptedException e )
            {
                LOG.warn( "Consumer {} Interrupted while trying to reconnect to the provider {}",
                    config.getReplicaId(), config.getProducer() );
            }

            connected = connect();
        }

        // TODO : we may have cases were we get here with the connected flag to false. With the above
        // code, thi sis not possible

        return connected;
    }

    /**
     * {@inheritDoc}
     */
    public void stop()
    {
        if ( !disconnected )
        {
            disconnect();
            nbAdded.getAndSet( 0 );
        }
    }

    /**
     * {@inheritDoc}
     */
    public String getId()
    {
        return String.valueOf( getConfig().getReplicaId() );
    }

    /**
     * performs a search on connection with updated syncRequest control.
     *
     * @throws Exception in case of any problems encountered while searching
     */
    private ReplicationStatusEnum doSyncSearch( SynchronizationModeEnum syncType, boolean reloadHint ) throws Exception
    {
        SyncRequestValue syncReq = new SyncRequestValueDecorator( ldapCodecService );

        syncReq.setMode( syncType );
        syncReq.setReloadHint( reloadHint );

        if ( syncCookie != null )
        {
            LOG.debug( "searching with searchRequest, cookie '{}'", Strings.utf8ToString( syncCookie ) );
            syncReq.setCookie( syncCookie );
        }

        searchRequest.addControl( syncReq );

        // Do the search
        SearchFuture sf = connection.searchAsync( searchRequest );

        Response resp = sf.get();

        while ( !( resp instanceof SearchResultDone ) && !sf.isCancelled() && !disconnected )
        {
            if ( resp instanceof SearchResultEntry )
            {
                handleSearchResult( ( SearchResultEntry ) resp );
            }
            else if ( resp instanceof SearchResultReference )
            {
                handleSearchReference( ( SearchResultReference ) resp );
            }
            else if ( resp instanceof IntermediateResponse )
            {
                handleSyncInfo( ( IntermediateResponse ) resp );
            }

            resp = sf.get();
        }

        ResultCodeEnum resultCode = handleSearchDone( ( SearchResultDone ) resp );

        LOG.debug( "sync operation returned result code {}", resultCode );

        if ( resultCode == ResultCodeEnum.NO_SUCH_OBJECT )
        {
            // log the error and handle it appropriately
            LOG.warn( "given replication base Dn {} is not found on provider", config.getBaseDn() );

            LOG.warn( "disconnecting the consumer running in refreshAndPersist mode from the provider" );
            disconnect();

            return ReplicationStatusEnum.DISCONNECTED;
        }
        else if ( resultCode == ResultCodeEnum.E_SYNC_REFRESH_REQUIRED )
        {
            LOG.info( "unable to perform the content synchronization cause E_SYNC_REFRESH_REQUIRED" );

            try
            {
                deleteRecursive( new Dn( config.getBaseDn() ), null );
            }
            catch ( Exception e )
            {
                LOG
                    .error(
                        "Failed to delete the replica base as part of handling E_SYNC_REFRESH_REQUIRED, disconnecting the consumer",
                        e );
                disconnect();
            }

            removeCookie();

            return ReplicationStatusEnum.REFRESH_REQUIRED;
        }
        else
        {
            return ReplicationStatusEnum.DISCONNECTED;
        }
    }

    public void disconnect()
    {
        disconnected = true;

        if ( connection == null )
        {
            return;
        }

        if ( connection.isConnected() )
        {
            try
            {
                if ( refreshThread != null )
                {
                    refreshThread.stopRefreshing();
                }

                connection.unBind();
                LOG.info( "Unbound from the server {}", config.getRemoteHost() );

                connection.close();
                LOG.info( "Connection closed for the server {}", config.getRemoteHost() );

                connection = null;
            }
            catch ( Exception e )
            {
                LOG.error( "Failed to close the connection", e );
            }
            finally
            {
                // persist the cookie
                storeCookie();

                // reset the cookie
                syncCookie = null;
            }
        }
    }

    /**
     * stores the cookie.
     */
    private void storeCookie()
    {
        if ( syncCookie == null )
        {
            return;
        }

        if ( lastSavedCookie != null && Arrays.equals( syncCookie, lastSavedCookie ) )
        {
            return;
        }

        try
        {
            if ( cookieFile == null )
            {
                cookieFile = new File( cookieDir, String.valueOf( LdapProtocolUtils.getReplicaId( new String(
                    syncCookie ) ) ) );
            }

            FileOutputStream fout = new FileOutputStream( cookieFile );
            fout.write( syncCookie.length );
            fout.write( syncCookie );
            fout.close();

            lastSavedCookie = new byte[syncCookie.length];
            System.arraycopy( syncCookie, 0, lastSavedCookie, 0, syncCookie.length );

            LOG.debug( "stored the cookie" );
        }
        catch ( Exception e )
        {
            LOG.error( "Failed to store the cookie", e );
        }
    }

    /**
     * read the cookie
     */
    private void readCookie()
    {
        try
        {
            if ( ( cookieFile != null ) && cookieFile.exists() && ( cookieFile.length() > 0 ) )
            {
                FileInputStream fin = new FileInputStream( cookieFile );
                syncCookie = new byte[fin.read()];
                fin.read( syncCookie );
                fin.close();

                lastSavedCookie = new byte[syncCookie.length];
                System.arraycopy( syncCookie, 0, lastSavedCookie, 0, syncCookie.length );

                LOG.debug( "read the cookie from file: " + Strings.utf8ToString( syncCookie ) );
            }
        }
        catch ( Exception e )
        {
            LOG.error( "Failed to read the cookie", e );
        }
    }

    /**
     * deletes the cookie and resets the syncCookie to null
     */
    public void removeCookie()
    {
        if ( cookieFile.exists() && ( cookieFile.length() > 0 ) )
        {
            boolean deleted = cookieFile.delete();
            LOG.info( "deleted cookie file {}", deleted );
        }

        LOG.info( "resetting sync cookie" );

        syncCookie = null;
        lastSavedCookie = null;
    }

    private void applyModDnOperation( Entry remoteEntry, String entryUuid ) throws Exception
    {
        LOG.debug( "MODDN for entry {}, new entry : {}", entryUuid, remoteEntry );

        // First, compute the MODDN type
        SyncModifyDnType modDnType = null;

        try
        {
            // Retrieve locally the moved or renamed entry
            String filter = "(entryUuid=" + entryUuid + ")";
            EntryCursor cursor = connection.search( Dn.ROOT_DSE, filter, SearchScope.SUBTREE,
                SchemaConstants.ALL_ATTRIBUTES_ARRAY );

            Entry localEntry = cursor.get();

            // Compute the DN, parentDn and Rdn for both entries
            Dn localDn = localEntry.getDn();
            Dn remoteDn = remoteEntry.getDn();

            Dn localParentDn = localDn.getParent();
            Dn remoteParentDn = remoteDn.getParent();

            Rdn localRdn = localDn.getRdn();
            Rdn remoteRdn = remoteDn.getRdn();

            // If the RDN are equals, it's a MOVE
            if ( localRdn.equals( remoteRdn ) )
            {
                modDnType = SyncModifyDnType.MOVE;
            }

            // If the parentDn are equals, it's a RENAME
            if ( localParentDn.equals( remoteParentDn ) )
            {
                modDnType = SyncModifyDnType.RENAME;
            }

            // Otherwise, it's a MOVE and RENAME
            if ( modDnType == null )
            {
                modDnType = SyncModifyDnType.MOVE_AND_RENAME;
            }

            // Check if the OldRdn has been deleted
            boolean deleteOldRdn = remoteEntry.contains( localRdn.getNormType(), localRdn.getNormValue() );

            switch ( modDnType )
            {
                case MOVE:
                    LOG.debug( "moving {} to the new parent {}", localDn, remoteParentDn );

                    break;

                case RENAME:
                    LOG.debug( "renaming the Dn {} with new Rdn {} and deleteOldRdn flag set to {}", new String[]
                        { localDn.getName(), remoteRdn.getName(), String.valueOf( deleteOldRdn ) } );

                    break;

                case MOVE_AND_RENAME:
                    LOG.debug(
                        "moveAndRename on the Dn {} with new newParent Dn {}, new Rdn {} and deleteOldRdn flag set to {}",
                        new String[]
                            {
                                localDn.getName(),
                                remoteParentDn.getName(),
                                remoteRdn.getName(),
                                String.valueOf( deleteOldRdn ) } );

                    break;
            }
        }
        catch ( Exception e )
        {
            throw e;
        }
    }

    private void modify( Entry remoteEntry ) throws Exception
    {
        /*
        Entry localEntry = session.lookup( remoteEntry.getDn() );

        remoteEntry.removeAttributes( MOD_IGNORE_AT );

        List<Modification> mods = new ArrayList<Modification>();
        Iterator<Attribute> itr = localEntry.iterator();

        while ( itr.hasNext() )
        {
            Attribute localAttr = itr.next();
            String attrId = localAttr.getId();
            Modification mod;
            Attribute remoteAttr = remoteEntry.get( attrId );

            if ( remoteAttr != null ) // would be better if we compare the values also? or will it consume more time?
            {
                mod = new DefaultModification( ModificationOperation.REPLACE_ATTRIBUTE, remoteAttr );
                remoteEntry.remove( remoteAttr );
            }
            else
            {
                mod = new DefaultModification( ModificationOperation.REMOVE_ATTRIBUTE, localAttr );
            }

            mods.add( mod );
        }

        if ( remoteEntry.size() > 0 )
        {
            itr = remoteEntry.iterator();
            while ( itr.hasNext() )
            {
                mods.add( new DefaultModification( ModificationOperation.ADD_ATTRIBUTE, itr.next() ) );
            }
        }

        session.modify( remoteEntry.getDn(), mods );
        */
    }

    /**
     * deletes the entries having the UUID given in the list
     *
     * @param uuidList the list of UUIDs
     * @throws Exception in case of any problems while deleting the entries
     */
    public void deleteEntries( List<byte[]> uuidList, boolean isRefreshPresent ) throws Exception
    {
        if ( uuidList == null || uuidList.isEmpty() )
        {
            return;
        }

        for ( byte[] uuid : uuidList )
        {
            LOG.info( "uuid: {}", Strings.uuidToString( uuid ) );
        }

        // if it is refreshPresent list then send all the UUIDs for
        // filtering, otherwise breaking the list will cause the
        // other present entries to be deleted from DIT
        if ( isRefreshPresent )
        {
            LOG.debug( "refresh present syncinfo list has {} UUIDs", uuidList.size() );
            _deleteEntries_( uuidList, isRefreshPresent );
            return;
        }

        int NODE_LIMIT = 10;

        int count = uuidList.size() / NODE_LIMIT;

        int startIndex = 0;
        int i = 0;
        for ( ; i < count; i++ )
        {
            startIndex = i * NODE_LIMIT;
            _deleteEntries_( uuidList.subList( startIndex, startIndex + NODE_LIMIT ), isRefreshPresent );
        }

        if ( ( uuidList.size() % NODE_LIMIT ) != 0 )
        {
            // remove the remaining entries
            if ( count > 0 )
            {
                startIndex = i * NODE_LIMIT;
            }
            _deleteEntries_( uuidList.subList( startIndex, uuidList.size() ), isRefreshPresent );
        }
    }

    /**
     * do not call this method directly, instead call deleteEntries()
     *
     * @param limitedUuidList a list of UUIDs whose size is less than or equal to #NODE_LIMIT (node limit applies only for refreshDeletes list)
     * @param isRefreshPresent a flag indicating the type of entries present in the UUID list
     */
    private void _deleteEntries_( List<byte[]> limitedUuidList, boolean isRefreshPresent ) throws Exception
    {
        ExprNode filter = null;
        int size = limitedUuidList.size();
        if ( size == 1 )
        {
            String uuid = Strings.uuidToString( limitedUuidList.get( 0 ) );
            filter = new EqualityNode<String>( SchemaConstants.ENTRY_UUID_AT,
                new org.apache.directory.api.ldap.model.entry.StringValue( uuid ) );
            if ( isRefreshPresent )
            {
                filter = new NotNode( filter );
            }
        }
        else
        {
            if ( isRefreshPresent )
            {
                filter = new AndNode();
            }
            else
            {
                filter = new OrNode();
            }

            for ( int i = 0; i < size; i++ )
            {
                String uuid = Strings.uuidToString( limitedUuidList.get( i ) );
                ExprNode uuidEqNode = new EqualityNode<String>( SchemaConstants.ENTRY_UUID_AT,
                    new org.apache.directory.api.ldap.model.entry.StringValue( uuid ) );

                if ( isRefreshPresent )
                {
                    uuidEqNode = new NotNode( uuidEqNode );
                    ( ( AndNode ) filter ).addNode( uuidEqNode );
                }
                else
                {
                    ( ( OrNode ) filter ).addNode( uuidEqNode );
                }
            }
        }

        Dn dn = new Dn( schemaManager, config.getBaseDn() );

        /*
        LOG.debug( "selecting entries to be deleted using filter {}", filter.toString() );
        EntryFilteringCursor cursor = session.search( dn, SearchScope.SUBTREE, filter,
            AliasDerefMode.NEVER_DEREF_ALIASES, ENTRY_UUID_ATOP_SET );
        cursor.beforeFirst();

        while ( cursor.next() )
        {
            Entry entry = cursor.get();
            deleteRecursive( entry.getDn(), null );
        }

        cursor.close();
        */
    }

    /**
     * A Thread implementation for synchronizing the DIT in refreshOnly mode
     */
    private class RefresherThread extends Thread
    {

        public RefresherThread()
        {
            setDaemon( true );
        }

        public void run()
        {
            while ( !stop )
            {
                LOG.debug( "==================== Refresh Only ==========" );

                try
                {
                    doSyncSearch( SynchronizationModeEnum.REFRESH_ONLY, false );

                    LOG.info( "--------------------- Sleep for a little while ------------------" );
                    mutex.wait( config.getRefreshInterval() );
                    LOG.debug( "--------------------- syncing again ------------------" );

                }
                catch ( InterruptedException ie )
                {
                    LOG.warn( "refresher thread interrupted" );
                }
                catch ( Exception e )
                {
                    LOG.error( "Failed to sync with refresh only mode", e );
                }
            }
        }

        public void stopRefreshing()
        {
            stop = true;

            // just in case if it is sleeping, wake up the thread
            mutex.notify();
        }
    }

    /**
     * removes all child entries present under the given Dn and finally the Dn itself
     *
     * Working:
     *          This is a recursive function which maintains a Map<Dn,Cursor>.
     *          The way the cascade delete works is by checking for children for a
     *          given Dn(i.e opening a search cursor) and if the cursor is empty
     *          then delete the Dn else for each entry's Dn present in cursor call
     *          deleteChildren() with the Dn and the reference to the map.
     *
     *          The reason for opening a search cursor is based on an assumption
     *          that an entry *might* contain children, consider the below DIT fragment
     *
     *          parent
     *          /     \
     *        child1   child2
     *                 /     \
     *               grand21  grand22
     *
     *           The below method works better in the case where the tree depth is >1
     *
     *   In the case of passing a non-null DeleteListener, the return value will always be null, cause the
     *   operation is treated as asynchronous and response result will be sent using the listener callback
     *
     * @param rootDn the Dn which will be removed after removing its children
     * @param map a map to hold the Cursor related to a Dn
     * @throws Exception If the Dn is not valid or if the deletion failed
     */
    private void deleteRecursive( Dn rootDn, Map<Dn, EntryFilteringCursor> cursorMap ) throws Exception
    {
        LOG.debug( "searching for {}", rootDn.getName() );
        EntryFilteringCursor cursor = null;

        try
        {
            if ( cursorMap == null )
            {
                cursorMap = new HashMap<Dn, EntryFilteringCursor>();
            }

            /*
            cursor = cursorMap.get( rootDn );

            if ( cursor == null )
            {
                cursor = session.search( rootDn, SearchScope.ONELEVEL, ENTRY_UUID_PRESENCE_FILTER,
                    AliasDerefMode.NEVER_DEREF_ALIASES, ENTRY_UUID_ATOP_SET );
                cursor.beforeFirst();
                LOG.debug( "putting cursor for {}", rootDn.getName() );
                cursorMap.put( rootDn, cursor );
            }

            if ( !cursor.next() ) // if this is a leaf entry's Dn
            {
                LOG.debug( "deleting {}", rootDn.getName() );
                cursorMap.remove( rootDn );
                cursor.close();
                session.delete( rootDn );
            }
            else
            {
                do
                {
                    Entry entry = cursor.get();

                    deleteRecursive( entry.getDn(), cursorMap );
                }
                while ( cursor.next() );

                cursorMap.remove( rootDn );
                cursor.close();
                LOG.debug( "deleting {}", rootDn.getName() );
                session.delete( rootDn );
            }
            */
        }
        catch ( Exception e )
        {
            String msg = "Failed to delete child entries under the Dn " + rootDn.getName();
            LOG.error( msg, e );
            throw e;
        }
    }

    /**
     * @return the nbAdded
     */
    public int getNbAdded()
    {
        return nbAdded.get();
    }

    /**
     * @return the nbAdded
     */
    public void resetNbAdded()
    {
        nbAdded.getAndSet( 0 );
    }
}


text:
using RefactoringEssentials.CSharp.CodeRefactorings;
using Xunit;

namespace RefactoringEssentials.Tests.CSharp.CodeRefactorings
{
    public class AutoLinqSumActionTests : CSharpCodeRefactoringTestBase
    {
        [Fact]
        public void TestSimpleIntegerLoop()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        $foreach (var x in list)
            result += x;
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        result += list.Sum();
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestMergedIntegerLoop()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        var list = new int[] { 1, 2, 3 };
        int result = 0;
        $foreach (var x in list)
            result += x;
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        var list = new int[] { 1, 2, 3 };
        int result = list.Sum();
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestNonZeroMergedIntegerLoop()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        var list = new int[] { 1, 2, 3 };
        int result = 1;
        $foreach (var x in list)
            result += x;
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        var list = new int[] { 1, 2, 3 };
        int result = 1 + list.Sum();
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestMergedAssignmentIntegerLoop()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        var list = new int[] { 1, 2, 3 };
        int result;
        result = 1;
        $foreach (var x in list)
            result += x;
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        var list = new int[] { 1, 2, 3 };
        int result;
        result = 1 + list.Sum();
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestMergedDecimal()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        var list = new int[] { 1, 2, 3 };
        decimal result = 0.0m;
        $foreach (var x in list)
            result += x;
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        var list = new int[] { 1, 2, 3 };
        decimal result = list.Sum();
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestIntegerLoopInBlock()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        $foreach (var x in list) {
            result += x;
        }
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        result += list.Sum();
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestExpression()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        $foreach (var x in list) {
            result += x * 2;
        }
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        result += list.Sum(x => x * 2);
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestDisabledForStrings()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        string result = string.Empty;
        var list = new string[] { ""a"", ""b"" };
        $foreach (var x in list) {
            result += x;
        }
    }
}";
            TestWrongContext<AutoLinqSumAction>(source);
        }

        [Fact]
        public void TestShort()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        short result = 0;
        var list = new short[] { 1, 2, 3 };
        $foreach (var x in list)
            result += x;
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        short result = 0;
        var list = new short[] { 1, 2, 3 };
        result += list.Sum();
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestLong()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        long result = 0;
        var list = new long[] { 1, 2, 3 };
        $foreach (var x in list)
            result += x;
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        long result = 0;
        var list = new long[] { 1, 2, 3 };
        result += list.Sum();
    }
}";
            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestUnsignedLong()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        ulong result = 0;
        var list = new ulong[] { 1, 2, 3 };
        $foreach (var x in list)
            result += x;
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        ulong result = 0;
        var list = new ulong[] { 1, 2, 3 };
        result += list.Sum();
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestFloat()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        float result = 0;
        var list = new float[] { 1, 2, 3 };
        $foreach (var x in list)
            result += x;
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        float result = 0;
        var list = new float[] { 1, 2, 3 };
        result += list.Sum();
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestDouble()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        double result = 0;
        var list = new double[] { 1, 2, 3 };
        $foreach (var x in list)
            result += x;
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        double result = 0;
        var list = new double[] { 1, 2, 3 };
        result += list.Sum();
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestDecimal()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        decimal result = 0;
        var list = new decimal[] { 1, 2, 3 };
        $foreach (var x in list)
            result += x;
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        decimal result = 0;
        var list = new decimal[] { 1, 2, 3 };
        result += list.Sum();
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestMinus()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        $foreach (var x in list) {
            result -= x;
        }
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        result += list.Sum(x => -x);
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestCombined()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        $foreach (var x in list) {
            result += x;
            result += 2 * x;
        }
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        result += list.Sum(x => x + (2 * x));
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestCombinedPrecedence()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        $foreach (var x in list) {
            result += x;
            result += x << 1;
        }
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        result += list.Sum(x => x + (x << 1));
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestEmptyStatements()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        $foreach (var x in list) {
            result += x;
            ;
        }
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        result += list.Sum();
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestSimpleConditional()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        $foreach (var x in list) {
            if (x > 0)
                result += x;
        }
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        result += list.Where(x => x > 0).Sum();
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestInvertedConditional()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        $foreach (var x in list) {
            if (x > 0)
                ;
            else
                result += x;
        }
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        result += list.Where(x => x <= 0).Sum();
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestIncrement()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        $foreach (var x in list) {
            result++;
        }
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        result += list.Count();
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestCompleteConditional()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        $foreach (var x in list) {
            if (x > 0)
                result += x * 2;
            else
                result += x;
        }
    }
}";

            string result = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2, 3 };
        result += list.Sum(x => x > 0 ? x * 2 : x);
    }
}";

            Test<AutoLinqSumAction>(source, result);
        }

        [Fact]
        public void TestDisabledForSideEffects()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        string result = string.Empty;
        var list = new string[] { ""a"", ""b"" };
        $foreach (var x in list) {
            TestMethod();
            result += x;
        }
    }
}";
            TestWrongContext<AutoLinqSumAction>(source);
        }

        [Fact]
        public void TestDisabledForInnerAssignments()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2 };
        int p = 0;
        $foreach (var x in list) {
            result += (p = x);
        }
    }
}";
            TestWrongContext<AutoLinqSumAction>(source);
        }

        [Fact]
        public void TestDisabledForInnerIncrements()
        {
            string source = @"
using System.Linq;

class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2 };
        int p = 0;
        $foreach (var x in list) {
            result += (p++);
        }
    }
}";
            TestWrongContext<AutoLinqSumAction>(source);
        }

        [Fact]
        public void TestDisabledForNoLinq()
        {
            string source = @"
class TestClass
{
    void TestMethod() {
        int result = 0;
        var list = new int[] { 1, 2 };
        $foreach (var x in list) {
            result += x;
        }
    }
}";
            TestWrongContext<AutoLinqSumAction>(source);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace SimpleBus\SymfonyBridge\DependencyInjection;

use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;

class DoctrineOrmBridgeConfiguration implements ConfigurationInterface
{
    private $alias;

    public function __construct($alias)
    {
        $this->alias = $alias;
    }

    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();

        $rootNode = $treeBuilder->root($this->alias);

        $rootNode
            ->addDefaultsIfNotSet()
            ->children()
                ->scalarNode('entity_manager')
                    ->defaultValue('default')
                ->end()
                ->scalarNode('connection')
                    ->defaultValue('default')
                ->end()
            ->end();

        return $treeBuilder;
    }
}


text:
Clazz.declarePackage ("JSV.exception");
Clazz.load (["JSV.exception.JDXSourceException"], "JSV.exception.LDRNotFoundException", null, function () {
c$ = Clazz.declareType (JSV.exception, "LDRNotFoundException", JSV.exception.JDXSourceException);
Clazz.makeConstructor (c$,
function (label) {
Clazz.superConstructor (this, JSV.exception.LDRNotFoundException, ["Label Data Record for " + label + " Not Found"]);
}, "~S");
});


text:
declare namespace Example.TodoMVC {
    import BeanPostProcessor = Typejector.Component.Factory.BeanPostProcessor;
    import BeanDefinition = Typejector.Component.Factory.Config.BeanDefinition;
    class ClickableBeanPostProcessor extends BeanPostProcessor {
        postProcessBeforeInitialization<T extends Object>(bean: T, beanDefinition: BeanDefinition): T;
        postProcessAfterInitialization<T extends Object>(bean: T, beanDefinition: BeanDefinition): T;
    }
    interface Observable<T> {
        subscribe(observer: Observer<T>): void;
    }
    interface Observer<T> {
        onChange(target: T, propertyKey: any): any;
    }
    class Model implements Observable<Model> {
        private taskList;
        subscribers: Array<Observer<Model>>;
        subscribe(observer: Observer<Model>): void;
        addTask(task: string): void;
        private notifyAll(propKey);
    }
    class Controller {
        private model;
        addTask(element: HTMLInputElement): void;
        updateList(element: HTMLElement): void;
    }
}


text:
import { Component, Input, OnInit, QueryList, ContentChildren, AfterContentInit } from '@angular/core';
import { AngularComplexAction } from '../types';

@Component({
    selector: 'plrsBreadcrumbs',
    templateUrl: 'breadcrumbs.component.html',
    styles: [':host {display: block;}'],
    host: {
        '[attr.role]': '"navigation"',
    },
})
export class BreadcrumbsComponent implements OnInit, AfterContentInit {

    @Input() public breadcrumbs:AngularComplexAction[];

    ngOnInit() { }

    ngAfterContentInit() {

    }

    public get action(): AngularComplexAction {
        if (this.breadcrumbs && this.breadcrumbs.length > 0) {
            return this.breadcrumbs[this.breadcrumbs.length - 1];
        }
        return null;
    }

}


text:
.line {
  stroke-linecap: round;
  stroke-linejoin: round;
  stroke-width: 2;
}

.willAnimate .line {
  stroke-dasharray: 1000;
  stroke-dashoffset: 1000;
  animation-iteration-count: 1;
  animation-fill-mode: forwards;
  animation-duration: 1500ms;
  animation-timing-function: ease-in-out;
}

.animate .line {
  animation-name: draw;
}

.willAnimate .fill {
  opacity: 0;
  animation-iteration-count: 1;
  animation-fill-mode: forwards;
  animation-duration: 800ms;
  animation-timing-function: ease-in-out;
  animation-delay: 300ms;
}

.animate .fill {
  animation-name: fillIn;
}

@keyframes draw {
  to {
    stroke-dashoffset: 0;
  }
}

@keyframes fillIn {
  to {
    opacity: 0.18;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using MetaDslx.CodeAnalysis;
using MetaDslx.CodeAnalysis.Symbols;
using MetaDslx.CodeAnalysis.Antlr4Test.Languages.TestLexerMode;
using MetaDslx.CodeAnalysis.Antlr4Test.Languages.TestLexerMode.Syntax.InternalSyntax;

namespace MetaDslx.CodeAnalysis.Antlr4Test.Languages.TestLexerMode.Symbols
{
    public class TestLexerModeSymbolFacts : SymbolFacts
    {
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
           "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Coverage Report Classes</title>
<link title="Style" type="text/css" rel="stylesheet" href="css/main.css"/>

com.emfeld.mvptest.views.interfaces

Classes

MainView (N/A)


text:
$.init = function(_params) {

	$.avatarLabel.setText('OpenCard');

	var settings = {
		id: 'settings',
		image: WPATH('images/menu_option-settings.png'),
		title: 'Configuración'
	};
	_params.tabs.push(settings);

	$.tabs = [];

	for(var i = 0; i < _params.tabs.length; i++) {
		var tab = Ti.UI.createTableViewRow({
			id: _params.tabs[i].id
		});

		var _image = _params.tabs[i].image && _params.tabs[i].image != '' ? _params.tabs[i].image : WPATH('images/menu_option-default.png');
		var icon = Ti.UI.createImageView({
			top: '12dp',
			left: '10dp',
			width: '23dp',
			height: '23dp',
			touchEnabled: false,
			preventDefaultImage: true,
			image: _image
		});

		var label = Ti.UI.createLabel({
			text: _params.tabs[i].title,
			top: "0dp",
			left: "47dp",
			right: "7dp",
			bottom: "0dp",
			touchEnabled: false
		});

		$.addClass(tab, 'tabRow');
		$.addClass(label, 'optionLabel');

		tab.add(icon);
		tab.add(label);

		$.tabs.push(tab);
	}

	$.Tabs.setData($.tabs);
};

$.clear = function() {
	$.Tabs.setData([]);
};

$.setIndex = function(_index) {
	$.Tabs.selectRow(_index);
};

$.Tabs.addEventListener("click", function(_event) {
	if(typeof _event.index !== "undefined") {
		$.setIndex(_event.index);
	}
});


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

<!--

    Copyright 2016 Alexey Ragozin

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->

  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.gridkit.lab</groupId>
    <artifactId>grid-lab-pom</artifactId>
    <version>2</version>
  </parent>

  <groupId>org.gridkit.heapunit</groupId>
  <artifactId>heapunit-pom</artifactId>
  <version>0.3-SNAPSHOT</version>
  <name>${project.groupId}::${project.artifactId}</name>
  <description>HeapUnit parent pom</description>
  <packaging>pom</packaging>

  <modules>
    <module>heapunit</module>
  </modules>

  <scm>
    <connection>scm:git:https://github.com/aragozin/heapunit.git</connection>
    <developerConnection>scm:git:https://github.com/aragozin/heapunit.git</developerConnection>
    <url>https://github.com/aragozin/heapunit</url>
    <tag>HEAD</tag>
  </scm>

  <licenses>
    <license>
      <name>The Apache Software License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <developers>
    <developer>
      <id>alexey.ragozin</id>
      <name>Alexey Ragozin</name>
      <email>alexey.ragozin@gmail.com</email>
    </developer>
  </developers>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.0</version>
          <configuration>
            <source>1.6</source>
            <target>1.6</target>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-release-plugin</artifactId>
          <version>2.4</version>
          <configuration>
            <autoVersionSubmodules>true</autoVersionSubmodules>
            <pushChanges>true</pushChanges>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.14</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-javadoc-plugin</artifactId>
          <version>2.9</version>
          <executions>
            <execution>
              <id>attach-javadoc</id>
              <goals>
                <goal>jar</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-source-plugin</artifactId>
          <version>2.2.1</version>
          <executions>
            <execution>
              <id>attach-source</id>
              <goals>
                <goal>jar</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-resources-plugin</artifactId>
          <version>2.6</version>
          <configuration>
            <encoding>UTF-8</encoding>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>


text:
@interface DFRelationshipsViewController : SYScrollPageViewController

@property(nonatomic) NSInteger userId;
@property(nonatomic, strong) NSString* nickname;

- (id) initWithUserId:(NSInteger)userId;

@end


text:
% some calculations with the implemented classes

% test dual Quaternions

D = Dualquaternion(Quaternion(2,[0 0 0]),Quaternion(0,[1 1 1]));
E = Dualquaternion(Quaternion(1,[0 0 1]),Quaternion);

% test RotationMatrix class

% construct a RotationMatrix by using EULER coordinates
A = RotationMatrix('EULER',[.5 .5 .5 .5]);
% construct a RotationMatrix by giving the axis and the angle
A = RotationMatrix('GENERAL',pi/2,[0; 0; 1]);
% construct a RotationMatrix by using RODRIGUES coordinates
A = RotationMatrix('RODRIGUES',[-1; 2; 1]);
% construct a RotationMatrix by using exponential coordinates
A = RotationMatrix('EXPONENTIAL',[0; 1; 1],pi/4);

%% test spatial displacements with dual quaternions
% default constructor of class Dualquaternion
Q = Dualquaternion;

% halbe translation
% T = Dualquaternion(Quaternion(1,[0 0 0]),Quaternion(0,[.5 .5 0]));

T = Dualquaternion(Quaternion(1,[0 0 0]),Quaternion(0,[0.5 0 0.5]));

R = Dualquaternion(Quaternion(0.9239,[0 0 0.3827]),Quaternion);
Q = T*R;
x = Dualquaternion(Quaternion(1,[0 0 0]),Quaternion(0,[1 0 0]));
displaceRT(Q,x)
displaceTR(Q,x)
%% test study paramter functionality
    B = Q;
    plotCube();
    b={};
for i=1:10
%     hold on;
    plotCube(Q);
    b{i} = double(Q.getStudyParameters);
    Q = Q*B;
    drawnow
end
% plotCube(R.getStudyParameters.homogeneousMatrix);

%% test class HomogeneousTransformationMatrix
% Eulercoordinates from the formula E = cos(phi/2) + sin(phi/2)*r
% d = [0 0 1], phi = pi/4
a = getEulerCoords(pi/4,[0 0 1]);
rotation = HomogeneousVector(a);
translation = HomogeneousVector([1 1 1 0]);
A = HomogeneousTransformationMatrix(translation, rotation);
x = HomogeneousVector([1 1 0 0]);
A*x

%% test interpolation on sphere
% attention the matrix of the quadric has to fit in interpolateOnQuadric.m
% call aitkenPicture for subdaivision picture
M = diag([-1 1 1 1]);
a = {};
controlPoints.coords = getSphereCoords(0,0);
controlPoints.value = 0;
a{1} = controlPoints;
controlPoints.coords = getSphereCoords(pi/10,-pi/12);
controlPoints.value = 0.166666666;
a{2} = controlPoints;
controlPoints.coords = getSphereCoords(pi/6,pi/8);
controlPoints.value = 0.333333332;
a{3} = controlPoints;
controlPoints.coords = getSphereCoords(pi/4,pi/4);
controlPoints.value = .5;
a{4} = controlPoints;
controlPoints.coords = getSphereCoords(pi/2,pi/2);
controlPoints.value = 0.66666666;
a{5} = controlPoints;
controlPoints.coords = getSphereCoords(pi/3,pi/4);
controlPoints.value = 0.83333333;
a{6} = controlPoints;
controlPoints.coords = getSphereCoords(pi/3,pi/7);
controlPoints.value = 1;
a{7} = controlPoints;

point2 = [];
tic
for i = 0:0.001:1
%     point2 = [point2,interpolateOnQuadric(a,i,M)];
    point2 = [point2,aitken(a,i,M)];
%     point2 = [point2,QBinterpolation(a,i,M)];
end
toc

for i=1:size(point2,2)
%     point1(:,i)=1/point1(1,i).*point1(:,i);
    point2(:,i)=1/point2(1,i).*point2(:,i);
end
sphere;
axis equal;
hold on;
% X=point1(2,:);
% Y=point1(3,:);
% Z=point1(4,:);
% plot3(X,Y,Z);
X=point2(2,:);
Y=point2(3,:);
Z=point2(4,:);
plot3(X,Y,Z);

for i=1:length(a)
    p = plot3(a{i}.coords(2),a{i}.coords(3),a{i}.coords(4));
    set(p,'Marker','.');
    set(p,'MarkerSize',30);
end

% calculate point with cross ratio 0.4
point = aitken(a,0.4,M);
point = 1/point(1).*point;
p = plot3(point(2),point(3),point(4));
set(p,'Marker','.');
set(p,'MarkerSize',25);
set(p,'Color','red');
aitkenPicture(a,0.4,M);


text:
using System.Collections.Generic;
using Newtonsoft.Json;

namespace IBM.Watson.Assistant.v1.Model
{
    /// <summary>
    /// An array of dialog nodes.
    /// </summary>
    public class DialogNodeCollection
    {
        /// <summary>
        /// An array of objects describing the dialog nodes defined for the workspace.
        /// </summary>
        [JsonProperty("dialog_nodes", NullValueHandling = NullValueHandling.Ignore)]
        public List<DialogNode> DialogNodes { get; set; }
        /// <summary>
        /// The pagination data for the returned objects.
        /// </summary>
        [JsonProperty("pagination", NullValueHandling = NullValueHandling.Ignore)]
        public Pagination Pagination { get; set; }
    }

}


text:
define({
  "instruction": "Stvorite sadržaj koji se prikazuje u ovom widgetu.",
  "defaultContent": "Ovdje dodajte tekst, poveznice i male grafičke elemente.",
  "productVersion": "Verzija proizvoda: ",
  "kernelVersion": "Verzija jezgre sustava: "
});


text:
package org.apache.nifi.processors.rethinkdb;

import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.annotation.behavior.EventDriven;
import org.apache.nifi.annotation.behavior.InputRequirement;
import org.apache.nifi.annotation.behavior.WritesAttribute;
import org.apache.nifi.annotation.behavior.WritesAttributes;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.SeeAlso;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.annotation.lifecycle.OnStopped;
import org.apache.nifi.components.AllowableValue;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.expression.ExpressionLanguageScope;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.processor.DataUnit;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.exception.ProcessException;

import com.google.gson.Gson;

import java.io.ByteArrayInputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
@EventDriven
@Tags({"rethinkdb", "get", "read", "fetch"})
@CapabilityDescription("Processor to get a JSON document from RethinkDB (https://www.rethinkdb.com/) using the document id. The FlowFile will contain the retrieved document")
@WritesAttributes({
    @WritesAttribute(attribute = GetRethinkDB.RETHINKDB_ERROR_MESSAGE, description = "RethinkDB error message"),
    })
@SeeAlso({PutRethinkDB.class,DeleteRethinkDB.class})
public class GetRethinkDB extends AbstractRethinkDBProcessor {

    public static AllowableValue READ_MODE_SINGLE = new AllowableValue("single", "Single", "Read values from memory from primary replica (Default)");
    public static AllowableValue READ_MODE_MAJORITY = new AllowableValue("majority", "Majority", "Read values committed to disk on majority of replicas");
    public static AllowableValue READ_MODE_OUTDATED = new AllowableValue("outdated", "Outdated", "Read values from memory from an arbitrary replica ");

    protected static final PropertyDescriptor READ_MODE = new PropertyDescriptor.Builder()
            .name("rethinkdb-read-mode")
            .displayName("Read Mode")
            .description("Read mode used for consistency")
            .required(true)
            .defaultValue(READ_MODE_SINGLE.getValue())
            .allowableValues(READ_MODE_SINGLE, READ_MODE_MAJORITY, READ_MODE_OUTDATED)
            .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
            .build();

    protected String READ_MODE_KEY = "read_mode";

    private static final Set<Relationship> relationships;
    private static final List<PropertyDescriptor> propertyDescriptors;

    protected Gson gson = new Gson();

    static {
        final Set<Relationship> tempRelationships = new HashSet<>();
        tempRelationships.add(REL_SUCCESS);
        tempRelationships.add(REL_FAILURE);
        tempRelationships.add(REL_NOT_FOUND);
        relationships = Collections.unmodifiableSet(tempRelationships);

        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
        tempDescriptors.add(DB_NAME);
        tempDescriptors.add(DB_HOST);
        tempDescriptors.add(DB_PORT);
        tempDescriptors.add(USERNAME);
        tempDescriptors.add(PASSWORD);
        tempDescriptors.add(TABLE_NAME);
        tempDescriptors.add(CHARSET);
        tempDescriptors.add(RETHINKDB_DOCUMENT_ID);
        tempDescriptors.add(READ_MODE);
        tempDescriptors.add(MAX_DOCUMENTS_SIZE);
        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    }

    @Override
    public Set<Relationship> getRelationships() {
        return relationships;
    }

    @Override
    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
        return propertyDescriptors;
    }

    @OnScheduled
    public void onScheduled(final ProcessContext context) {
        maxDocumentsSize = context.getProperty(MAX_DOCUMENTS_SIZE).asDataSize(DataUnit.B).longValue();
        super.onScheduled(context);
    }

    @Override
    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
        FlowFile flowFile = session.get();
        if (flowFile == null) {
            return;
        }

        Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());
        String id = context.getProperty(RETHINKDB_DOCUMENT_ID).evaluateAttributeExpressions(flowFile).getValue();
        String readMode = context.getProperty(READ_MODE).evaluateAttributeExpressions(flowFile).getValue();

        if ( StringUtils.isEmpty(id) ) {
            getLogger().error(DOCUMENT_ID_EMPTY_MESSAGE);
            flowFile = session.putAttribute(flowFile, RETHINKDB_ERROR_MESSAGE, DOCUMENT_ID_EMPTY_MESSAGE);
            session.transfer(flowFile, REL_FAILURE);
            return;
        }

        try {
            long startTimeMillis = System.currentTimeMillis();
            Map<String,Object> document = getDocument(id, readMode);

            if ( document == null ) {
                getLogger().debug("Document with id '" + id + "' not found");
                flowFile = session.putAttribute(flowFile, RETHINKDB_ERROR_MESSAGE, "Document with id '" + id + "' not found");
                session.transfer(flowFile, REL_NOT_FOUND);
                return;
            }

            String json = gson.toJson(document);

            byte [] documentBytes = json.getBytes(charset);

            if ( documentBytes.length > maxDocumentsSize ) {
                getLogger().error("Document too big with size " + documentBytes.length + " and max limit is " + maxDocumentsSize );
                flowFile = session.putAttribute(flowFile, RETHINKDB_ERROR_MESSAGE, "Document too big size " + documentBytes.length + " bytes");
                session.transfer(flowFile, REL_FAILURE);
                return;
            }

            ByteArrayInputStream bais = new ByteArrayInputStream(documentBytes);
            session.importFrom(bais, flowFile);
            final long endTimeMillis = System.currentTimeMillis();

            getLogger().debug("Json document {} retrieved Result: {}", new Object[] {id, document});

            session.transfer(flowFile, REL_SUCCESS);
            session.getProvenanceReporter().fetch(flowFile,
                new StringBuilder("rethinkdb://").append(databaseName).append("/").append(tableName).append("/").append(id).toString(),
                (endTimeMillis - startTimeMillis));

        } catch (Exception exception) {
            getLogger().error("Failed to get document from RethinkDB due to error {}",
                    new Object[]{exception.getLocalizedMessage()}, exception);
            flowFile = session.putAttribute(flowFile, RETHINKDB_ERROR_MESSAGE, exception.getMessage() + "");
            session.transfer(flowFile, REL_FAILURE);
            context.yield();
        }
    }

    protected Map<String,Object> getDocument(String id, String readMode) {
        return getRdbTable().optArg(READ_MODE_KEY,readMode).get(id).run(rethinkDbConnection);
    }

    @OnStopped
    public void close() {
        super.close();
    }
}


text:
#include <wx/wx.h>

#ifndef _MAIN_H_
#define _MAIN_H_

class VRenderApp : public wxApp
{
public:
	virtual bool OnInit();
	void OnInitCmdLine(wxCmdLineParser& parser);
	bool OnCmdLineParsed(wxCmdLineParser& parser);

private:
	wxArrayString m_files;
	int m_file_num;
};

DECLARE_APP(VRenderApp)

#endif//_MAIN_H_


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Results;

namespace DotJEM.Web.Host.Results
{
    public class ForbiddenErrorMessageResult : NegotiatedContentResult<string>
    {
        public ForbiddenErrorMessageResult(HttpStatusCode statusCode, string message, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
            : base(statusCode, message, contentNegotiator, request, formatters)
        {
        }

        public ForbiddenErrorMessageResult(HttpStatusCode statusCode, string message, ApiController controller)
            : base(statusCode, message, controller)
        {
        }
    }
}


text:
package org.onosproject.provider.lldpcommon;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import io.netty.util.internal.StringUtil;
import org.onlab.packet.Ethernet;
import org.onlab.packet.MacAddress;
import org.onlab.packet.ONOSLLDP;
import org.onlab.util.Timer;
import org.onlab.util.Tools;
import org.onosproject.net.AnnotationKeys;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Link.Type;
import org.onosproject.net.LinkKey;
import org.onosproject.net.Port;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.link.DefaultLinkDescription;
import org.onosproject.net.link.LinkDescription;
import org.onosproject.net.link.ProbedLinkProvider;
import org.onosproject.net.packet.DefaultOutboundPacket;
import org.onosproject.net.packet.OutboundPacket;
import org.onosproject.net.packet.PacketContext;
import org.slf4j.Logger;

import java.nio.ByteBuffer;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.onosproject.net.AnnotationKeys.PORT_NAME;
import static org.onosproject.net.PortNumber.portNumber;
import static org.onosproject.net.flow.DefaultTrafficTreatment.builder;
import static org.slf4j.LoggerFactory.getLogger;

/**
 * Run discovery process from a physical switch. Ports are initially labeled as
 * slow ports. When an LLDP is successfully received, label the remote port as
 * fast. Every probeRate milliseconds, loop over all fast ports and send an
 * LLDP, send an LLDP for a single slow port. Based on FlowVisor topology
 * discovery implementation.
 */
public class LinkDiscovery implements TimerTask {

    private static final String SCHEME_NAME = "linkdiscovery";
    private static final String ETHERNET = "ETHERNET";

    private final Logger log = getLogger(getClass());

    private final DeviceId deviceId;
    private final LinkDiscoveryContext context;

    private final Ethernet ethPacket;
    private final Ethernet bddpEth;

    private Timeout timeout;
    private volatile boolean isStopped;

    // Set of ports to be probed
    private final Map<Long, String> portMap = Maps.newConcurrentMap();
    /**
     * Instantiates discovery manager for the given physical switch. Creates a
     * generic LLDP packet that will be customized for the port it is sent out on.
     * Starts the the timer for the discovery process.
     *
     * @param deviceId  the physical switch
     * @param context discovery context
     */
    public LinkDiscovery(DeviceId deviceId, LinkDiscoveryContext context) {
        this.deviceId = deviceId;
        this.context = context;

        ethPacket = new Ethernet();
        ethPacket.setEtherType(Ethernet.TYPE_LLDP);
        ethPacket.setDestinationMACAddress(MacAddress.ONOS_LLDP);
        ethPacket.setPad(true);

        bddpEth = new Ethernet();
        bddpEth.setEtherType(Ethernet.TYPE_BSN);
        bddpEth.setDestinationMACAddress(MacAddress.BROADCAST);
        bddpEth.setPad(true);

        isStopped = true;
        start();
        log.debug("Started discovery manager for switch {}", deviceId);

    }

    public synchronized void stop() {
        if (!isStopped) {
            isStopped = true;
            timeout.cancel();
        } else {
            log.warn("LinkDiscovery stopped multiple times?");
        }
    }

    public synchronized void start() {
        if (isStopped) {
            isStopped = false;
            timeout = Timer.newTimeout(this, 0, MILLISECONDS);
        } else {
            log.warn("LinkDiscovery started multiple times?");
        }
    }

    public synchronized boolean isStopped() {
        return isStopped || timeout.isCancelled();
    }

    /**
     * Add physical port to discovery process.
     * Send out initial LLDP and label it as slow port.
     *
     * @param port the port
     */
    public void addPort(Port port) {
        Long portNum = port.number().toLong();
        String portName = port.annotations().value(PORT_NAME);
        if (portName == null) {
            portName = StringUtil.EMPTY_STRING;
        }

        boolean newPort = !containsPort(portNum);
        portMap.put(portNum, portName);

        boolean isMaster = context.mastershipService().isLocalMaster(deviceId);
        if (newPort && isMaster) {
            log.debug("Sending initial probe to port {}@{}", port.number().toLong(), deviceId);
            sendProbes(portNum, portName);
        }
    }

    /**
     * removed physical port from discovery process.
     * @param port the port number
     */
    public void removePort(PortNumber port) {
        portMap.remove(port.toLong());
    }

    /**
     * Handles an incoming LLDP packet. Creates link in topology and adds the
     * link for staleness tracking.
     *
     * @param packetContext packet context
     * @return true if handled
     */
    public boolean handleLldp(PacketContext packetContext) {
        Ethernet eth = packetContext.inPacket().parsed();
        if (eth == null) {
            return false;
        }

        if (processOnosLldp(packetContext, eth)) {
            return true;
        }

        if (processLldp(packetContext, eth)) {
            return true;
        }

        ONOSLLDP lldp = ONOSLLDP.parseLLDP(eth);

        if (lldp == null) {
            log.debug("Cannot parse the packet. It seems that it is not the lldp or bsn packet.");
        } else {
            log.debug("LLDP packet is dropped due to there are no handlers that properly handle this packet: {}",
                    lldp.toString());
        }

        return false;
    }

    private boolean processOnosLldp(PacketContext packetContext, Ethernet eth) {
        ONOSLLDP onoslldp = ONOSLLDP.parseONOSLLDP(eth);
        if (onoslldp != null) {
            Type lt;
            if (notMy(eth.getSourceMAC().toString())) {
                lt = Type.EDGE;
            } else {
                lt = eth.getEtherType() == Ethernet.TYPE_LLDP ?
                        Type.DIRECT : Type.INDIRECT;

                /* Verify MAC in LLDP packets */
                if (!ONOSLLDP.verify(onoslldp, context.lldpSecret(), context.maxDiscoveryDelay())) {
                    log.warn("LLDP Packet failed to validate!");
                    return true;
                }
            }

            PortNumber srcPort = portNumber(onoslldp.getPort());
            PortNumber dstPort = packetContext.inPacket().receivedFrom().port();

            String idString = onoslldp.getDeviceString();
            if (!isNullOrEmpty(idString)) {
                try {
                    DeviceId srcDeviceId = DeviceId.deviceId(idString);
                    DeviceId dstDeviceId = packetContext.inPacket().receivedFrom().deviceId();

                    ConnectPoint src = new ConnectPoint(srcDeviceId, srcPort);
                    ConnectPoint dst = new ConnectPoint(dstDeviceId, dstPort);

                    LinkDescription ld = new DefaultLinkDescription(src, dst, lt);
                    context.providerService().linkDetected(ld);
                    context.touchLink(LinkKey.linkKey(src, dst));
                } catch (IllegalStateException | IllegalArgumentException e) {
                    log.warn("There is a exception during link creation: {}", e.getMessage());
                    return true;
                }
                return true;
            }
        }
        return false;
    }

    private boolean processLldp(PacketContext packetContext, Ethernet eth) {
        ONOSLLDP onoslldp = ONOSLLDP.parseLLDP(eth);
        if (onoslldp != null) {
            Type lt = eth.getEtherType() == Ethernet.TYPE_LLDP ?
                    Type.DIRECT : Type.INDIRECT;

            DeviceService deviceService = context.deviceService();
            MacAddress srcChassisId = onoslldp.getChassisIdByMac();
            String srcPortName = onoslldp.getPortNameString();
            String srcPortDesc = onoslldp.getPortDescString();

            log.debug("srcChassisId:{}, srcPortName:{}, srcPortDesc:{}", srcChassisId, srcPortName, srcPortDesc);

            if (srcChassisId == null && srcPortDesc == null) {
                log.warn("there are no valid port id");
                return false;
            }

            Optional<Device> srcDevice = findSourceDeviceByChassisId(deviceService, srcChassisId);

            if (!srcDevice.isPresent()) {
                log.warn("source device not found. srcChassisId value: {}", srcChassisId);
                return false;
            }
            Optional<Port> sourcePort = findSourcePortByName(
                    srcPortName == null ? srcPortDesc : srcPortName,
                    deviceService,
                    srcDevice.get());

            if (!sourcePort.isPresent()) {
                log.warn("source port not found. sourcePort value: {}", sourcePort);
                return false;
            }

            PortNumber srcPort = sourcePort.get().number();
            PortNumber dstPort = packetContext.inPacket().receivedFrom().port();

            DeviceId srcDeviceId = srcDevice.get().id();
            DeviceId dstDeviceId = packetContext.inPacket().receivedFrom().deviceId();

            if (!sourcePort.get().isEnabled()) {
                log.debug("Ports are disabled. Cannot create a link between {}/{} and {}/{}",
                        srcDeviceId, sourcePort.get(), dstDeviceId, dstPort);
                return false;
            }

            ConnectPoint src = new ConnectPoint(srcDeviceId, srcPort);
            ConnectPoint dst = new ConnectPoint(dstDeviceId, dstPort);

            DefaultAnnotations annotations = DefaultAnnotations.builder()
                    .set(AnnotationKeys.PROTOCOL, SCHEME_NAME.toUpperCase())
                    .set(AnnotationKeys.LAYER, ETHERNET)
                    .build();

            LinkDescription ld = new DefaultLinkDescription(src, dst, lt, true, annotations);
            try {
                context.providerService().linkDetected(ld);
                context.setTtl(LinkKey.linkKey(src, dst), onoslldp.getTtlBySeconds());
            } catch (IllegalStateException e) {
                log.debug("There is a exception during link creation: {}", e);
                return true;
            }
            return true;
        }
        return false;
    }

    private Optional<Device> findSourceDeviceByChassisId(DeviceService deviceService, MacAddress srcChassisId) {
        Supplier<Stream<Device>> deviceStream = () ->
                StreamSupport.stream(deviceService.getAvailableDevices().spliterator(), false);
        Optional<Device> remoteDeviceOptional = deviceStream.get()
                .filter(device -> device.chassisId() != null
                        && MacAddress.valueOf(device.chassisId().value()).equals(srcChassisId))
                .findAny();

        if (remoteDeviceOptional.isPresent()) {
            log.debug("sourceDevice found by chassis id: {}", srcChassisId);
            return remoteDeviceOptional;
        } else {
            remoteDeviceOptional = deviceStream.get().filter(device ->
                    Tools.stream(deviceService.getPorts(device.id()))
                            .anyMatch(port -> port.annotations().keys().contains(AnnotationKeys.PORT_MAC)
                                    && MacAddress.valueOf(port.annotations().value(AnnotationKeys.PORT_MAC))
                                    .equals(srcChassisId)))
                    .findAny();
            if (remoteDeviceOptional.isPresent()) {
                log.debug("sourceDevice found by port mac: {}", srcChassisId);
                return remoteDeviceOptional;
            } else {
                return Optional.empty();
            }
        }
    }

    private Optional<Port> findSourcePortByName(String remotePortName,
                                                DeviceService deviceService,
                                                Device remoteDevice) {
        if (remotePortName == null) {
            return Optional.empty();
        }
        Optional<Port> remotePort = deviceService.getPorts(remoteDevice.id())
                .stream().filter(port -> Objects.equals(remotePortName,
                                                        port.annotations().value(AnnotationKeys.PORT_NAME)))
                .findAny();

        if (remotePort.isPresent()) {
            return remotePort;
        } else {
            return Optional.empty();
        }
    }

    // true if *NOT* this cluster's own probe.
    private boolean notMy(String mac) {
        // if we are using DEFAULT_MAC, clustering hadn't initialized, so conservative 'yes'
        String ourMac = context.fingerprint();
        if (ProbedLinkProvider.defaultMac().equalsIgnoreCase(ourMac)) {
            return true;
        }
        return !mac.equalsIgnoreCase(ourMac);
    }

    /**
     * Execute this method every t milliseconds. Loops over all ports
     * labeled as fast and sends out an LLDP. Send out an LLDP on a single slow
     * port.
     *
     * @param t timeout
     */
    @Override
    public void run(Timeout t) {
        if (isStopped()) {
            return;
        }

        if (context.mastershipService().isLocalMaster(deviceId)) {
            log.trace("Sending probes from {}", deviceId);
            ImmutableMap.copyOf(portMap).forEach(this::sendProbes);
        }

        if (!isStopped()) {
            timeout = t.timer().newTimeout(this, context.probeRate(), MILLISECONDS);
        }
    }

    /**
     * Creates packet_out LLDP for specified output port.
     *
     * @param portNumber the port
     * @param portDesc the port description
     * @return Packet_out message with LLDP data
     */
    private OutboundPacket createOutBoundLldp(Long portNumber, String portDesc) {
        if (portNumber == null) {
            return null;
        }
        ONOSLLDP lldp = getLinkProbe(portNumber, portDesc);
        if (lldp == null) {
            log.warn("Cannot get link probe with portNumber {} and portDesc {} for {} at LLDP packet creation.",
                    portNumber, portDesc, deviceId);
            return null;
        }
        ethPacket.setSourceMACAddress(context.fingerprint()).setPayload(lldp);
        return new DefaultOutboundPacket(deviceId,
                                         builder().setOutput(portNumber(portNumber)).build(),
                                         ByteBuffer.wrap(ethPacket.serialize()));
    }

    /**
     * Creates packet_out BDDP for specified output port.
     *
     * @param portNumber the port
     * @param portDesc the port description
     * @return Packet_out message with LLDP data
     */
    private OutboundPacket createOutBoundBddp(Long portNumber, String portDesc) {
        if (portNumber == null) {
            return null;
        }
        ONOSLLDP lldp = getLinkProbe(portNumber, portDesc);
        if (lldp == null) {
            log.warn("Cannot get link probe with portNumber {} and portDesc {} for {} at BDDP packet creation.",
                    portNumber, portDesc, deviceId);
            return null;
        }
        bddpEth.setSourceMACAddress(context.fingerprint()).setPayload(lldp);
        return new DefaultOutboundPacket(deviceId,
                                         builder().setOutput(portNumber(portNumber)).build(),
                                         ByteBuffer.wrap(bddpEth.serialize()));
    }

    private ONOSLLDP getLinkProbe(Long portNumber, String portDesc) {
        Device device = context.deviceService().getDevice(deviceId);
        if (device == null) {
            log.warn("Cannot find the device {}", deviceId);
            return null;
        }
        return ONOSLLDP.onosSecureLLDP(deviceId.toString(), device.chassisId(), portNumber.intValue(), portDesc,
                                       context.lldpSecret());
    }

    private void sendProbes(Long portNumber, String portDesc) {
        if (context.packetService() == null) {
            return;
        }
        log.trace("Sending probes out of {}@{}", portNumber, deviceId);
        OutboundPacket pkt = createOutBoundLldp(portNumber, portDesc);
        if (pkt != null) {
            context.packetService().emit(pkt);
        } else {
            log.warn("Cannot send lldp packet due to packet is null {}", deviceId);
        }
        if (context.useBddp()) {
            OutboundPacket bpkt = createOutBoundBddp(portNumber, portDesc);
            if (bpkt != null) {
                context.packetService().emit(bpkt);
            } else {
                log.warn("Cannot send bddp packet due to packet is null {}", deviceId);
            }
        }
    }

    public boolean containsPort(long portNumber) {
        return portMap.containsKey(portNumber);
    }
}


text:
package net.sourceforge.squirrel_sql.client.update.xmlbeans;

public class ChannelXmlBean {

    private String name;

    private ReleaseXmlBean currentRelease;

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the currentRelease
     */
    public ReleaseXmlBean getCurrentRelease() {
        return currentRelease;
    }

    /**
     * @param currentRelease the currentRelease to set
     */
    public void setCurrentRelease(ReleaseXmlBean currentRelease) {
        this.currentRelease = currentRelease;
    }

    /**
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((currentRelease == null) ? 0 : currentRelease.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    /**
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final ChannelXmlBean other = (ChannelXmlBean) obj;
        if (currentRelease == null) {
            if (other.currentRelease != null)
                return false;
        } else if (!currentRelease.equals(other.currentRelease))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

	/**
	  * Constructs a String with all attributes
	  * in name = value format.
	  *
	  * @return a String representation
	  * of this object.
	  */
	 @Override
	 public String toString()
	 {
	     final String TAB = "    ";

	     StringBuilder retValue = new StringBuilder();

	     retValue.append("ChannelXmlBean ( ")
	         .append(super.toString()).append(TAB)
	         .append("name = ").append(this.name).append(TAB)
	         .append("currentRelease = ").append(this.currentRelease).append(TAB)
	         .append(" )");

	     return retValue.toString();
	 }

}