text:
package org.apache.directory.server.core.shared.partition;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.cursor.EmptyCursor;
import org.apache.directory.api.ldap.model.cursor.SingletonCursor;
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.DefaultEntry;
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.entry.Value;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.exception.LdapNoSuchAttributeException;
import org.apache.directory.api.ldap.model.exception.LdapNoSuchObjectException;
import org.apache.directory.api.ldap.model.exception.LdapOperationErrorException;
import org.apache.directory.api.ldap.model.exception.LdapOtherException;
import org.apache.directory.api.ldap.model.filter.ExprNode;
import org.apache.directory.api.ldap.model.filter.ObjectClassNode;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.message.extended.NoticeOfDisconnect;
import org.apache.directory.api.ldap.model.name.Dn;
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.Normalizer;
import org.apache.directory.api.ldap.model.schema.UsageEnum;
import org.apache.directory.api.ldap.util.tree.DnNode;
import org.apache.directory.api.util.DateUtils;
import org.apache.directory.api.util.exception.MultiException;
import org.apache.directory.server.constants.ServerDNConstants;
import org.apache.directory.server.core.api.DirectoryService;
import org.apache.directory.server.core.api.InterceptorEnum;
import org.apache.directory.server.core.api.entry.ClonedServerEntry;
import org.apache.directory.server.core.api.filtering.BaseEntryFilteringCursor;
import org.apache.directory.server.core.api.filtering.CursorList;
import org.apache.directory.server.core.api.filtering.EntryFilteringCursor;
import org.apache.directory.server.core.api.interceptor.context.AddOperationContext;
import org.apache.directory.server.core.api.interceptor.context.CompareOperationContext;
import org.apache.directory.server.core.api.interceptor.context.DeleteOperationContext;
import org.apache.directory.server.core.api.interceptor.context.GetRootDseOperationContext;
import org.apache.directory.server.core.api.interceptor.context.HasEntryOperationContext;
import org.apache.directory.server.core.api.interceptor.context.LookupOperationContext;
import org.apache.directory.server.core.api.interceptor.context.ModifyOperationContext;
import org.apache.directory.server.core.api.interceptor.context.MoveAndRenameOperationContext;
import org.apache.directory.server.core.api.interceptor.context.MoveOperationContext;
import org.apache.directory.server.core.api.interceptor.context.RenameOperationContext;
import org.apache.directory.server.core.api.interceptor.context.SearchOperationContext;
import org.apache.directory.server.core.api.interceptor.context.UnbindOperationContext;
import org.apache.directory.server.core.api.partition.AbstractPartition;
import org.apache.directory.server.core.api.partition.Partition;
import org.apache.directory.server.core.api.partition.PartitionNexus;
import org.apache.directory.server.i18n.I18n;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A root {@link Partition} that contains all other partitions, and
 * routes all operations to the child partition that matches to its base suffixes.
 * It also provides some extended operations such as accessing rootDSE and
 * listing base suffixes.
 *
 * @author Apache Directory Project
 */
public class DefaultPartitionNexus extends AbstractPartition implements PartitionNexus
{
    /** A logger for this class */
    private static final Logger LOG = LoggerFactory.getLogger( DefaultPartitionNexus.class );

    /** the fixed id: 'NEXUS' */
    private static final String ID = "NEXUS";

    /** Speedup for logs */
    private static final boolean IS_DEBUG = LOG.isDebugEnabled();

    /** the vendorName string proudly set to: Apache Software Foundation*/
    private static final String ASF = "Apache Software Foundation";

    /** the read only rootDSE attributes */
    private final Entry rootDse;

    /** The DirectoryService instance */
    private DirectoryService directoryService;

    /** the partitions keyed by normalized suffix strings */
    private Map<String, Partition> partitions = new HashMap<String, Partition>();

    /** A structure to hold all the partitions */
    private DnNode<Partition> partitionLookupTree = new DnNode<Partition>();

    /** the system partition */
    //private Partition system;

    /** A reference to the EntryCSN attributeType */
    private static AttributeType ENTRY_CSN_AT;

    /** A reference to the ObjectClass attributeType */
    private static AttributeType OBJECT_CLASS_AT;

    private final List<Modification> mods = new ArrayList<Modification>( 2 );

    private String lastSyncedCtxCsn = null;

    /** The cn=schema Dn */
    private Dn subschemSubentryDn;

    /**
     * Creates the root nexus singleton of the entire system.  The root DSE has
     * several attributes that are injected into it besides those that may
     * already exist.  As partitions are added to the system more namingContexts
     * attributes are added to the rootDSE.
     *
     * @see Vendor Information
     * @param rootDse the root entry for the DSA
     * @throws javax.naming.Exception on failure to initialize
     */
    public DefaultPartitionNexus( Entry rootDse ) throws Exception
    {
        id = ID;
        suffixDn = null;

        // setup that root DSE
        this.rootDse = rootDse;

        // Add the basic informations
        rootDse.put( SchemaConstants.SUBSCHEMA_SUBENTRY_AT, ServerDNConstants.CN_SCHEMA_DN );
        rootDse.put( SchemaConstants.SUPPORTED_LDAP_VERSION_AT, "3" );
        rootDse.put( SchemaConstants.SUPPORTED_FEATURES_AT, SchemaConstants.FEATURE_ALL_OPERATIONAL_ATTRIBUTES );
        rootDse.put( SchemaConstants.SUPPORTED_EXTENSION_AT, NoticeOfDisconnect.EXTENSION_OID );

        // Add the objectClasses
        rootDse.put( SchemaConstants.OBJECT_CLASS_AT, SchemaConstants.TOP_OC, SchemaConstants.EXTENSIBLE_OBJECT_OC );

        // Add the 'vendor' name and version infos
        rootDse.put( SchemaConstants.VENDOR_NAME_AT, ASF );

        Properties props = new Properties();

        try
        {
            props.load( getClass().getResourceAsStream( "version.properties" ) );
        }
        catch ( IOException e )
        {
            LOG.error( I18n.err( I18n.ERR_33 ) );
        }

        rootDse.put( SchemaConstants.VENDOR_VERSION_AT, props.getProperty( "apacheds.version", "UNKNOWN" ) );

        // The rootDSE uuid has been randomly created
        rootDse.put( SchemaConstants.ENTRY_UUID_AT, "f290425c-8272-4e62-8a67-92b06f38dbf5" );
    }

    /* (non-Javadoc)
     * @see org.apache.directory.server.core.partition.PartitionNexus#initialize()
     */
    protected void doInit()
    {
        // NOTE: We ignore ContextPartitionConfiguration parameter here.
        if ( !initialized )
        {
            // Add the supported controls
            Iterator<String> ctrlOidItr = directoryService.getLdapCodecService().registeredControls();

            while ( ctrlOidItr.hasNext() )
            {
                rootDse.add( SchemaConstants.SUPPORTED_CONTROL_AT, ctrlOidItr.next() );
            }

            schemaManager = directoryService.getSchemaManager();
            ENTRY_CSN_AT = schemaManager.getAttributeType( SchemaConstants.ENTRY_CSN_AT );
            OBJECT_CLASS_AT = schemaManager.getAttributeType( SchemaConstants.OBJECT_CLASS_AT );

            // Initialize and normalize the localy used DNs
            Dn adminDn = directoryService.getDnFactory().create( ServerDNConstants.ADMIN_SYSTEM_DN );
            adminDn.apply( schemaManager );

            Value<?> attr = rootDse.get( SchemaConstants.SUBSCHEMA_SUBENTRY_AT ).get();
            subschemSubentryDn = directoryService.getDnFactory().create( attr.getString() );

            List<Partition> initializedPartitions = new ArrayList<Partition>();

            initializedPartitions.add( 0, directoryService.getSystemPartition() );
            addContextPartition( directoryService.getSystemPartition() );

            try
            {
                for ( Partition partition : directoryService.getPartitions() )
                {
                    addContextPartition( partition );
                    initializedPartitions.add( partition );
                }

                createContextCsnModList();

                initialized = true;
            }
            finally
            {
                if ( !initialized )
                {
                    Iterator<Partition> i = initializedPartitions.iterator();

                    while ( i.hasNext() )
                    {
                        Partition partition = i.next();
                        i.remove();

                        try
                        {
                            partition.destroy();
                        }
                        catch ( Exception e )
                        {
                            LOG.warn( "Failed to destroy a partition: " + partition.getSuffixDn(), e );
                        }
                        finally
                        {
                            unregister( partition );
                        }
                    }
                }
            }
        }
    }

    /* (non-Javadoc)
     * @see org.apache.directory.server.core.partition.PartitionNexus#destroy()
     */
    protected synchronized void doDestroy()
    {
        if ( !initialized )
        {
            return;
        }

        // make sure this loop is not fail fast so all backing stores can
        // have an attempt at closing down and synching their cached entries
        for ( String suffix : new HashSet<String>( this.partitions.keySet() ) )
        {
            try
            {
                removeContextPartition( directoryService.getDnFactory().create( suffix ) );
            }
            catch ( Exception e )
            {
                LOG.warn( "Failed to destroy a partition: " + suffix, e );
            }
        }

        initialized = false;
    }

    /**
     * {@inheritDoc}
     */
    public void setId( String id )
    {
        throw new UnsupportedOperationException( I18n.err( I18n.ERR_264 ) );
    }

    /**
     * {@inheritDoc}
     */
    public void setSuffixDn( Dn suffix )
    {
        throw new UnsupportedOperationException();
    }

    /* (non-Javadoc)
     * @see org.apache.directory.server.core.partition.PartitionNexus#sync()
     */
    public void sync()
    {
        MultiException error = null;

        // store the contextCSN value in the entry ou=system
        // note that this modification shouldn't change the entryCSN value of ou=system entry
        try
        {
            String currentCtxCsn = directoryService.getContextCsn();
            // update only if the CSN changes
            if ( ( currentCtxCsn != null ) && !currentCtxCsn.equals( lastSyncedCtxCsn ) )
            {
                lastSyncedCtxCsn = currentCtxCsn;

                Attribute contextCsnAt = mods.get( 0 ).getAttribute();
                contextCsnAt.clear();
                contextCsnAt.add( lastSyncedCtxCsn );

                Attribute timeStampAt = mods.get( 1 ).getAttribute();
                timeStampAt.clear();
                timeStampAt.add( DateUtils.getGeneralizedTime() );

                ModifyOperationContext csnModContext = new ModifyOperationContext( directoryService.getAdminSession(),
                    directoryService.getSystemPartition().getSuffixDn(), mods );
                directoryService.getSystemPartition().modify( csnModContext );
            }
        }
        catch ( Exception e )
        {
            LOG.warn( "Failed to save the contextCSN attribute value in ou=system entry.", e );
            if ( error == null )
            {
                error = new MultiException( I18n.err( I18n.ERR_265 ) );
            }

            error.addThrowable( e );
        }

        for ( Partition partition : this.partitions.values() )
        {
            try
            {
                partition.sync();
            }
            catch ( Exception e )
            {
                LOG.warn( "Failed to flush partition data out.", e );
                if ( error == null )
                {
                    //noinspection ThrowableInstanceNeverThrown
                    error = new MultiException( I18n.err( I18n.ERR_265 ) );
                }

                // @todo really need to send this info to a monitor
                error.addThrowable( e );
            }
        }

        if ( error != null )
        {
            throw error;
        }
    }

    // ------------------------------------------------------------------------
    // DirectoryPartition Interface Method Implementations
    // ------------------------------------------------------------------------
    /**
     * {@inheritDoc}
     */
    public void add( AddOperationContext addContext ) throws LdapException
    {
        Partition partition = getPartition( addContext.getDn() );
        partition.add( addContext );

        // MyVD doesn't care about csn
        // Attribute at = addContext.getEntry().get( SchemaConstants.ENTRY_CSN_AT );
        // directoryService.setContextCsn( at.getString() );
    }

    /**
     * {@inheritDoc}
     */
    public boolean compare( CompareOperationContext compareContext ) throws LdapException
    {
        Attribute attr = compareContext.getOriginalEntry().get( compareContext.getAttributeType() );

        // complain if the attribute being compared does not exist in the entry
        if ( attr == null )
        {
            throw new LdapNoSuchAttributeException();
        }

        // see first if simple match without normalization succeeds
        if ( attr.contains( compareContext.getValue() ) )
        {
            return true;
        }

        // now must apply normalization to all values (attr and in request) to compare

        /*
         * Get ahold of the normalizer for the attribute and normalize the request
         * assertion value for comparisons with normalized attribute values.  Loop
         * through all values looking for a match.
         */
        Normalizer normalizer = compareContext.getAttributeType().getEquality().getNormalizer();
        Value<?> reqVal = normalizer.normalize( compareContext.getValue() );

        for ( Value<?> value : attr )
        {
            Value<?> attrValObj = normalizer.normalize( value );

            if ( attrValObj.equals( reqVal ) )
            {
                return true;
            }
        }

        return false;
    }

    /**
     * {@inheritDoc}
     */
    public Entry delete( DeleteOperationContext deleteContext ) throws LdapException
    {
        Partition partition = getPartition( deleteContext.getDn() );
        Entry deletedEntry = partition.delete( deleteContext );

        Entry entry = deleteContext.getEntry();

        // MyVD doesn't care about csn
        // Attribute csn = entry.get( ENTRY_CSN_AT );
        // can be null while doing subentry deletion
        // //TODO verify if this gets in the way of replication
        // if ( csn != null )
        // {
        //     directoryService.setContextCsn( csn.getString() );
        // }

        return deletedEntry;
    }

    /**
     * {@inheritDoc}
     */
    public boolean hasEntry( HasEntryOperationContext hasEntryContext ) throws LdapException
    {
        Dn dn = hasEntryContext.getDn();

        if ( IS_DEBUG )
        {
            LOG.debug( "Check if Dn '" + dn + "' exists." );
        }

        if ( dn.isRootDse() )
        {
            return true;
        }

        Partition partition = getPartition( dn );

        return partition.hasEntry( hasEntryContext );
    }

    /**
     * {@inheritDoc}
     */
    public Entry lookup( LookupOperationContext lookupContext ) throws LdapException
    {
        Dn dn = lookupContext.getDn();

        if ( dn.equals( subschemSubentryDn ) )
        {
            return new ClonedServerEntry( rootDse.clone() );
        }

        // This is for the case we do a lookup on the rootDSE
        if ( dn.isRootDse() )
        {
            Entry retval = new ClonedServerEntry( rootDse );

            return retval;
        }

        Partition partition = getPartition( dn );
        Entry entry = partition.lookup( lookupContext );

        if ( entry == null )
        {
            LdapNoSuchObjectException e = new LdapNoSuchObjectException( "Attempt to lookup non-existant entry: "
                + dn.getName() );

            throw e;
        }

        return entry;
    }

    /**
     * {@inheritDoc}
     */
    public void modify( ModifyOperationContext modifyContext ) throws LdapException
    {
        // Special case : if we don't have any modification to apply, just return
        if ( modifyContext.getModItems().size() == 0 )
        {
            return;
        }

        Partition partition = getPartition( modifyContext.getDn() );

        partition.modify( modifyContext );

        if ( modifyContext.isPushToEvtInterceptor() )
        {
            directoryService.getInterceptor( InterceptorEnum.EVENT_INTERCEPTOR.getName() ).modify( modifyContext );
        }

        Entry alteredEntry = modifyContext.getAlteredEntry();

        if ( alteredEntry != null )
        {
            // MyVD doesn't care about csn
        	// directoryService.setContextCsn( alteredEntry.get( ENTRY_CSN_AT ).getString() );
        }
    }

    /**
     * {@inheritDoc}
     */
    public void move( MoveOperationContext moveContext ) throws LdapException
    {
        // Get the current partition
        Partition partition = getPartition( moveContext.getDn() );

        partition.move( moveContext );

        Entry entry = moveContext.getModifiedEntry();

        // MyVD doesn't care about csn
        // directoryService.setContextCsn( entry.get( ENTRY_CSN_AT ).getString() );
    }

    /**
     * {@inheritDoc}
     */
    public void moveAndRename( MoveAndRenameOperationContext moveAndRenameContext ) throws LdapException
    {
        Partition partition = getPartition( moveAndRenameContext.getDn() );
        partition.moveAndRename( moveAndRenameContext );

        Entry entry = moveAndRenameContext.getModifiedEntry();

        // MyVD doesn't care about csn
        // directoryService.setContextCsn( entry.get( ENTRY_CSN_AT ).getString() );
    }

    /**
     * {@inheritDoc}
     */
    public void rename( RenameOperationContext renameContext ) throws LdapException
    {
        Partition partition = getPartition( renameContext.getDn() );
        partition.rename( renameContext );

        Entry entry = renameContext.getModifiedEntry();

        // MyVD doesn't care about csn
        // directoryService.setContextCsn( entry.get( ENTRY_CSN_AT ).getString() );
    }

    private EntryFilteringCursor searchRootDse( SearchOperationContext searchContext ) throws LdapException
    {
        Set<AttributeTypeOptions> ids = searchContext.getReturningAttributes();

        // -----------------------------------------------------------
        // If nothing is asked for then we just return the entry asis.
        // We let other mechanisms filter out operational attributes.
        // -----------------------------------------------------------
        if ( ( ids == null ) || ( ids.size() == 0 ) )
        {
            Entry rootDse = getRootDse( null );
            return new BaseEntryFilteringCursor( new SingletonCursor<Entry>( rootDse ), searchContext,
                directoryService.getSchemaManager() );
        }

        // -----------------------------------------------------------
        // Collect all the real attributes besides 1.1, +, and * and
        // note if we've seen these special attributes as well.
        // -----------------------------------------------------------

        Set<String> realIds = new HashSet<String>();
        boolean allUserAttributes = searchContext.isAllUserAttributes();
        boolean allOperationalAttributes = searchContext.isAllOperationalAttributes();
        boolean noAttribute = searchContext.isNoAttributes();

        for ( AttributeTypeOptions id : ids )
        {
            try
            {
                realIds.add( id.getAttributeType().getOid() );
            }
            catch ( Exception e )
            {
                realIds.add( id.getAttributeType().getName() );
            }
        }

        // return nothing
        if ( noAttribute )
        {
            Entry serverEntry = new TremoloEntry( schemaManager, Dn.ROOT_DSE );
            return new BaseEntryFilteringCursor( new SingletonCursor<Entry>( serverEntry ), searchContext,
                directoryService.getSchemaManager() );
        }

        // return everything
        if ( allUserAttributes && allOperationalAttributes )
        {
            Entry rootDse = getRootDse( null );
            return new BaseEntryFilteringCursor( new SingletonCursor<Entry>( rootDse ), searchContext,
                directoryService.getSchemaManager() );
        }

        Entry serverEntry = new TremoloEntry( schemaManager, Dn.ROOT_DSE );

        Entry rootDse = getRootDse( new GetRootDseOperationContext( searchContext.getSession() ) );

        for ( Attribute attribute : rootDse )
        {
            AttributeType type = schemaManager.lookupAttributeTypeRegistry( attribute.getUpId() );

            if ( realIds.contains( type.getOid() ) )
            {
                serverEntry.put( attribute );
            }
            else if ( allUserAttributes && ( type.getUsage() == UsageEnum.USER_APPLICATIONS ) )
            {
                serverEntry.put( attribute );
            }
            else if ( allOperationalAttributes && ( type.getUsage() != UsageEnum.USER_APPLICATIONS ) )
            {
                serverEntry.put( attribute );
            }
        }

        return new BaseEntryFilteringCursor( new SingletonCursor<Entry>( serverEntry ), searchContext,
            directoryService.getSchemaManager() );
    }

    /**
     * {@inheritDoc}
     */
    public EntryFilteringCursor search( SearchOperationContext searchContext ) throws LdapException
    {
        Dn base = searchContext.getDn();

        // TODO since we're handling the *, and + in the EntryFilteringCursor
        // we may not need this code: we need see if this is actually the
        // case and remove this code.
        if ( base.size() == 0 )
        {
            return searchFromRoot( searchContext );
        }

        // Not sure we need this code...
        base.apply( schemaManager );

        // Normal case : do a search on the specific partition
        Partition backend = getPartition( base );

        return backend.search( searchContext );
    }

    /**
     * Do a search from the root of the DIT. We have a few use cases to consider :
     * A) The scope is OBJECT
     * If the filter is (ObjectClass = *), then this is a RootDSE fetch, otherwise, we just
     * return nothing.
     * B) The scope is ONELEVEL
     * We just return the contextEntries of all the existing partitions
     * C) The scope is SUBLEVEL :
     * In this case, we have to do a search in each of the existing partition. We will get
     * back a list of cursors and we will wrap this list in the resulting EntryFilteringCursor.
     *
     * @param searchContext
     * @return
     * @throws LdapException
     */
    private EntryFilteringCursor searchFromRoot( SearchOperationContext searchContext )
        throws LdapException
    {
        ExprNode filter = searchContext.getFilter();

        // We are searching from the rootDSE. We have to distinguish three cases :
        // 1) The scope is OBJECT : we have to return the rootDSE entry, filtered
        // 2) The scope is ONELEVEL : we have to return all the Naming Contexts
        boolean isObjectScope = searchContext.getScope() == SearchScope.OBJECT;

        boolean isOnelevelScope = searchContext.getScope() == SearchScope.ONELEVEL;

        // test for (objectClass=*)
        boolean isSearchAll = false;

        // We have to be careful, as we may have a filter which is not a PresenceFilter
        if ( filter instanceof ObjectClassNode )
        {
            isSearchAll = true;
        }

        if ( isObjectScope )
        {
            if ( isSearchAll )
            {
                // if basedn is "", filter is "(objectclass=*)" and scope is object
                // then we have a request for the rootDSE
                return searchRootDse( searchContext );
            }
            else
            {
                // Nothing to return in this case
                return new BaseEntryFilteringCursor( new EmptyCursor<Entry>(), searchContext,
                    directoryService.getSchemaManager() );
            }
        }
        else if ( isOnelevelScope )
        {
            // Loop on all the partitions
            // We will look into all the partitions, thus we create a list of cursors.
            List<EntryFilteringCursor> cursors = new ArrayList<EntryFilteringCursor>();

            for ( Partition partition : partitions.values() )
            {
                Dn contextDn = partition.getSuffixDn();
                HasEntryOperationContext hasEntryContext = new HasEntryOperationContext(
                    searchContext.getSession(), contextDn );

                // search only if the context entry exists
                if ( partition.hasEntry( hasEntryContext ) )
                {
                    searchContext.setDn( contextDn );
                    searchContext.setScope( SearchScope.OBJECT );
                    cursors.add( partition.search( searchContext ) );
                }
            }

            return new CursorList( cursors, searchContext );
        }
        else
        {
            // This is a SUBLEVEL search. We will do multiple searches and wrap
            // a CursorList into the EntryFilteringCursor
            List<EntryFilteringCursor> cursors = new ArrayList<EntryFilteringCursor>();

            for ( Partition partition : partitions.values() )
            {
                Dn contextDn = partition.getSuffixDn();
                HasEntryOperationContext hasEntryContext = new HasEntryOperationContext(
                    searchContext.getSession(), contextDn );

                if ( partition.hasEntry( hasEntryContext ) )
                {
                    searchContext.setDn( contextDn );
                    EntryFilteringCursor cursor = partition.search( searchContext );
                    cursors.add( cursor );
                }
            }

            // don't feed the above Cursors' list to a BaseEntryFilteringCursor it is skipping the naming context entry of each partition
            return new CursorList( cursors, searchContext );
        }
    }

    /**
     * {@inheritDoc}
     */
    public void unbind( UnbindOperationContext unbindContext ) throws LdapException
    {
        Dn unbindContextDn = unbindContext.getDn();

        if ( !Dn.isNullOrEmpty( unbindContextDn ) )
        {
            Partition partition = getPartition( unbindContext.getDn() );
            partition.unbind( unbindContext );
        }
    }

    /**
     * {@inheritDoc}
     */
    public Entry getRootDse( GetRootDseOperationContext getRootDseContext )
    {
        return rootDse.clone();
    }

    /**
     * {@inheritDoc}
     */
    public synchronized void addContextPartition( Partition partition ) throws LdapException
    {
        // Turn on default indices
        String key = partition.getSuffixDn().getNormName();

        if ( partitions.containsKey( key ) )
        {
            throw new LdapOtherException( I18n.err( I18n.ERR_263, key ) );
        }

        if ( !partition.isInitialized() )
        {
            partition.setCacheService( directoryService.getCacheService() );
            partition.initialize();
        }

        synchronized ( partitionLookupTree )
        {
            Dn partitionSuffix = partition.getSuffixDn();

            if ( partitionSuffix == null )
            {
                throw new LdapOtherException( I18n.err( I18n.ERR_267, partition.getId() ) );
            }

            partitions.put( partitionSuffix.getNormName(), partition );
            partitionLookupTree.add( partition.getSuffixDn(), partition );

            Attribute namingContexts = rootDse.get( SchemaConstants.NAMING_CONTEXTS_AT );

            if ( namingContexts == null )
            {
                namingContexts = new DefaultAttribute( schemaManager
                    .lookupAttributeTypeRegistry( SchemaConstants.NAMING_CONTEXTS_AT ), partitionSuffix.getName() );
                rootDse.put( namingContexts );
            }
            else
            {
                namingContexts.add( partitionSuffix.getName() );
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    public synchronized void removeContextPartition( Dn partitionDn )
        throws LdapException
    {
        // Get the Partition name. It's a Dn.
        String key = partitionDn.getNormName();

        // Retrieve this partition from the aprtition's table
        Partition partition = partitions.get( key );

        if ( partition == null )
        {
            String msg = I18n.err( I18n.ERR_34, key );
            LOG.error( msg );
            throw new LdapNoSuchObjectException( msg );
        }

        String partitionSuffix = partition.getSuffixDn().getName();

        // Retrieve the namingContexts from the RootDSE : the partition
        // suffix must be present in those namingContexts
        Attribute namingContexts = rootDse.get( SchemaConstants.NAMING_CONTEXTS_AT );

        if ( namingContexts != null )
        {
            if ( namingContexts.contains( partitionSuffix ) )
            {
                namingContexts.remove( partitionSuffix );
            }
            else
            {
                String msg = I18n.err( I18n.ERR_35, key );
                LOG.error( msg );
                throw new LdapNoSuchObjectException( msg );
            }
        }

        // Update the partition tree
        synchronized ( partitionLookupTree )
        {
            partitionLookupTree.remove( partition.getSuffixDn() );
        }

        partitions.remove( key );

        try
        {
            partition.destroy();
        }
        catch ( Exception e )
        {
            throw new LdapOperationErrorException( e.getMessage(), e );
        }
    }

    /**
     * {@inheritDoc}
     */
    public Partition getPartition( Dn dn ) throws LdapException
    {
        Partition parent = null;

        synchronized ( partitionLookupTree )
        {
            parent = partitionLookupTree.getElement( dn );
        }

        if ( parent == null )
        {
            throw new LdapNoSuchObjectException( I18n.err( I18n.ERR_268, dn ) );
        }
        else
        {
            return parent;
        }
    }

    /**
     * {@inheritDoc}
     */
    public Dn getSuffixDn( Dn dn ) throws LdapException
    {
        Partition partition = getPartition( dn );

        return partition.getSuffixDn();
    }

    /* (non-Javadoc)
     */
    public Set<String> listSuffixes() throws LdapException
    {
        return Collections.unmodifiableSet( partitions.keySet() );
    }

    /**
     * {@inheritDoc}
     */
    public void registerSupportedExtensions( Set<String> extensionOids ) throws LdapException
    {
        Attribute supportedExtension = rootDse.get( SchemaConstants.SUPPORTED_EXTENSION_AT );

        if ( supportedExtension == null )
        {
            rootDse.put( SchemaConstants.SUPPORTED_EXTENSION_AT, ( String ) null );
            supportedExtension = rootDse.get( SchemaConstants.SUPPORTED_EXTENSION_AT );
        }

        for ( String extensionOid : extensionOids )
        {
            supportedExtension.add( extensionOid );
        }
    }

    /**
     * {@inheritDoc}
     */
    public void registerSupportedSaslMechanisms( Set<String> supportedSaslMechanisms ) throws LdapException
    {
        Attribute supportedSaslMechanismsAt = null;

        supportedSaslMechanismsAt = new DefaultAttribute(
            schemaManager.lookupAttributeTypeRegistry( SchemaConstants.SUPPORTED_SASL_MECHANISMS_AT ) );

        for ( String saslMechanism : supportedSaslMechanisms )
        {
            supportedSaslMechanismsAt.add( saslMechanism );
        }

        rootDse.add( supportedSaslMechanismsAt );
    }

    /**
     * Unregisters an ContextPartition with this BackendManager.  Called for each
     * registered Backend right befor it is to be stopped.  This prevents
     * protocol server requests from reaching the Backend and effectively puts
     * the ContextPartition's naming context offline.
     *
     * Operations against the naming context should result in an LDAP BUSY
     * result code in the returnValue if the naming context is not online.
     *
     * @param partition ContextPartition component to unregister with this
     * BackendNexus.
     * @throws Exception if there are problems unregistering the partition
     */
    private void unregister( Partition partition ) throws Exception
    {
        Attribute namingContexts = rootDse.get( SchemaConstants.NAMING_CONTEXTS_AT );

        if ( namingContexts != null )
        {
            namingContexts.remove( partition.getSuffixDn().getName() );
        }

        partitions.remove( partition.getSuffixDn().getName() );
    }

    /**
     * @return the directoryService
     */
    public DirectoryService getDirectoryService()
    {
        return directoryService;
    }

    /**
     * @param directoryService the directoryService to set
     */
    public void setDirectoryService( DirectoryService directoryService )
    {
        this.directoryService = directoryService;
    }

    private void createContextCsnModList() throws LdapException
    {
        Modification contextCsnMod = new DefaultModification();
        contextCsnMod.setOperation( ModificationOperation.REPLACE_ATTRIBUTE );
        DefaultAttribute contextCsnAt = new DefaultAttribute( schemaManager
            .lookupAttributeTypeRegistry( SchemaConstants.CONTEXT_CSN_AT ) );
        contextCsnMod.setAttribute( contextCsnAt );

        mods.add( contextCsnMod );

        Modification timeStampMod = new DefaultModification();
        timeStampMod.setOperation( ModificationOperation.REPLACE_ATTRIBUTE );
        DefaultAttribute timeStampAt = new DefaultAttribute( schemaManager
            .lookupAttributeTypeRegistry( SchemaConstants.MODIFY_TIMESTAMP_AT ) );
        timeStampMod.setAttribute( timeStampAt );

        mods.add( timeStampMod );
    }
}


text:
package parquet.thrift;

import static parquet.schema.ConversionPatterns.listType;
import static parquet.schema.ConversionPatterns.mapType;
import static parquet.schema.OriginalType.ENUM;
import static parquet.schema.OriginalType.UTF8;
import static parquet.schema.PrimitiveType.PrimitiveTypeName.BINARY;
import static parquet.schema.PrimitiveType.PrimitiveTypeName.BOOLEAN;
import static parquet.schema.PrimitiveType.PrimitiveTypeName.DOUBLE;
import static parquet.schema.PrimitiveType.PrimitiveTypeName.INT32;
import static parquet.schema.PrimitiveType.PrimitiveTypeName.INT64;
import static parquet.schema.Type.Repetition.OPTIONAL;
import static parquet.schema.Type.Repetition.REPEATED;
import static parquet.schema.Type.Repetition.REQUIRED;
import static parquet.schema.Types.primitive;

import java.util.ArrayList;
import java.util.List;

import parquet.schema.GroupType;
import parquet.schema.MessageType;
import parquet.schema.OriginalType;
import parquet.schema.PrimitiveType;
import parquet.schema.PrimitiveType.PrimitiveTypeName;
import parquet.schema.Type;
import parquet.schema.Types.PrimitiveBuilder;
import parquet.thrift.projection.FieldProjectionFilter;
import parquet.thrift.projection.FieldsPath;
import parquet.thrift.projection.ThriftProjectionException;
import parquet.thrift.struct.ThriftField;
import parquet.thrift.struct.ThriftType;

/**
 * Visitor Class for converting a thrift definiton to parquet message type.
 * Projection can be done by providing a {@link FieldProjectionFilter}
 *
 * @author Tianshuo Deng
 */
public class ThriftSchemaConvertVisitor implements ThriftType.TypeVisitor {

  FieldProjectionFilter fieldProjectionFilter;
  Type currentType;
  FieldsPath currentFieldPath = new FieldsPath();
  Type.Repetition currentRepetition = Type.Repetition.REPEATED;//MessageType is repeated GroupType
  String currentName = "ParquetSchema";

  public ThriftSchemaConvertVisitor(FieldProjectionFilter fieldProjectionFilter) {
    this.fieldProjectionFilter = fieldProjectionFilter;
  }

  @Override
  public void visit(ThriftType.MapType mapType) {
    final ThriftField mapKeyField = mapType.getKey();
    final ThriftField mapValueField = mapType.getValue();

    //save env for map
    String mapName = currentName;
    Type.Repetition mapRepetition = currentRepetition;

    //=========handle key
    currentFieldPath.push(mapKeyField);
    currentName = "key";
    currentRepetition = REQUIRED;
    mapKeyField.getType().accept(this);
    Type keyType = currentType;//currentType is the already converted type
    currentFieldPath.pop();

    //=========handle value
    currentFieldPath.push(mapValueField);
    currentName = "value";
    currentRepetition = OPTIONAL;
    mapValueField.getType().accept(this);
    Type valueType = currentType;
    currentFieldPath.pop();

    if (keyType == null && valueType == null) {
      currentType = null;
      return;
    }

    if (keyType == null && valueType != null)
      throw new ThriftProjectionException("key of map is not specified in projection: " + currentFieldPath);

    //restore Env
    currentName = mapName;
    currentRepetition = mapRepetition;
    currentType = mapType(currentRepetition, currentName,
            keyType,
            valueType);
  }

  @Override
  public void visit(ThriftType.SetType setType) {
    final ThriftField setElemField = setType.getValues();
    String setName = currentName;
    Type.Repetition setRepetition = currentRepetition;
    currentName = currentName + "_tuple";
    currentRepetition = REPEATED;
    setElemField.getType().accept(this);
    //after conversion, currentType is the nested type
    if (currentType == null) {
      return;
    } else {
      currentType = listType(setRepetition, setName, currentType);
    }
  }

  @Override
  public void visit(ThriftType.ListType listType) {
    final ThriftField setElemField = listType.getValues();
    String listName = currentName;
    Type.Repetition listRepetition = currentRepetition;
    currentName = currentName + "_tuple";
    currentRepetition = REPEATED;
    setElemField.getType().accept(this);
    //after conversion, currentType is the nested type
    if (currentType == null) {
      return;
    } else {
      currentType = listType(listRepetition, listName, currentType);
    }

  }

  public MessageType getConvertedMessageType() {
    // the root should be a GroupType
    if (currentType == null)
      return new MessageType(currentName, new ArrayList<Type>());

    GroupType rootType = currentType.asGroupType();
    return new MessageType(currentName, rootType.getFields());
  }

  @Override
  public void visit(ThriftType.StructType structType) {
    List<ThriftField> fields = structType.getChildren();

    String oldName = currentName;
    Type.Repetition oldRepetition = currentRepetition;

    List<Type> types = getFieldsTypes(fields);

    currentName = oldName;
    currentRepetition = oldRepetition;
    if (types.size() > 0) {
      currentType = new GroupType(currentRepetition, currentName, types);
    } else {
      currentType = null;
    }
  }

  private List<Type> getFieldsTypes(List<ThriftField> fields) {
    List<Type> types = new ArrayList<Type>();
    for (int i = 0; i < fields.size(); i++) {
      ThriftField field = fields.get(i);
      Type.Repetition rep = getRepetition(field);
      currentRepetition = rep;
      currentName = field.getName();
      currentFieldPath.push(field);
      field.getType().accept(this);
      if (currentType != null) {
        // currentType is converted with the currentName(fieldName)
        types.add(currentType.withId(field.getFieldId()));
      }
      currentFieldPath.pop();
    }
    return types;
  }

  private boolean isCurrentlyMatchedFilter(){
     if(!fieldProjectionFilter.isMatched(currentFieldPath)){
       currentType = null;
       return false;
     }
    return true;
  }

  private void primitiveType(PrimitiveTypeName type) {
    primitiveType(type, null);
  }

  private void primitiveType(PrimitiveTypeName type, OriginalType orig) {
    if (isCurrentlyMatchedFilter()) {
      PrimitiveBuilder<PrimitiveType> b = primitive(type, currentRepetition);
      if (orig != null) {
        b = b.as(orig);
      }
      currentType = b.named(currentName);
    }
  }

  @Override
  public void visit(ThriftType.EnumType enumType) {
    primitiveType(BINARY, ENUM);
  }

  @Override
  public void visit(ThriftType.BoolType boolType) {
    primitiveType(BOOLEAN);
  }

  @Override
  public void visit(ThriftType.ByteType byteType) {
    primitiveType(INT32);
  }

  @Override
  public void visit(ThriftType.DoubleType doubleType) {
    primitiveType(DOUBLE);
  }

  @Override
  public void visit(ThriftType.I16Type i16Type) {
    primitiveType(INT32);
  }

  @Override
  public void visit(ThriftType.I32Type i32Type) {
    primitiveType(INT32);
  }

  @Override
  public void visit(ThriftType.I64Type i64Type) {
    primitiveType(INT64);
  }

  @Override
  public void visit(ThriftType.StringType stringType) {
    primitiveType(BINARY, UTF8);
  }

  /**
   * by default we can make everything optional
   *
   * @param thriftField
   * @return
   */
  private Type.Repetition getRepetition(ThriftField thriftField) {
    if (thriftField == null) {
      return OPTIONAL;
    }

    switch (thriftField.getRequirement()) {
      case REQUIRED:
        return REQUIRED;
      case OPTIONAL:
        return OPTIONAL;
      case DEFAULT:
        return OPTIONAL;
      default:
        throw new IllegalArgumentException("unknown requirement type: " + thriftField.getRequirement());
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
import logging
import os
import yaml

import cloudweatherreport.cloudresource.aws as aws
import cloudweatherreport.cloudresource.gce as gce
import cloudweatherreport.cloudresource.azure as azure
from cloudweatherreport.utils import juju_cmd

class UnknownCloudName(Exception):
    pass

class UnknownCredentialName(Exception):
    pass

class CloudNotSupported(Exception):
    pass

def get_credential_name(creds, cloud_name):
    cred_name = creds.get('credentials', {}).get(cloud_name, {}).get(
        'default-credential')
    if cred_name:
        return cred_name

    names = list(creds.get('credentials', {}).get(cloud_name, {}).keys())
    try:
        names.remove('default-region')
    except ValueError:
        pass
    if len(names) > 1:
        raise ValueError(
            'More than one credential is available. Set default juju '
            'credential or set JUJU_CREDENTIAL_NAME system variable.')
    return names[0]

def get_credentials(cloud, name=None):
    """Get cloud credentials from the juju credentials command."""
    cmd = 'list-credentials {} --format yaml --show-secrets'.format(cloud)
    creds = juju_cmd(cmd)
    creds = yaml.safe_load(creds)
    if not creds or not creds.get('credentials', {}).get(cloud):
        raise UnknownCloudName('Cloud not found: {}'.format(cloud))

    name = get_credential_name(creds, cloud) if not name else name
    try:
        credentials = creds['credentials'][cloud][name]
    except KeyError:
        raise UnknownCredentialName(
            'Credential name not found cloud:{} name:{}'.format(cloud, name))
    return credentials

def _aws_client(creds, region, instance_limit, security_group_limit):
    instance_limit = instance_limit or aws.INSTANCE_LIMIT
    security_group_limit = security_group_limit or aws.SECURITY_GROUP_LIMIT
    client = aws.AWS(
        access_key=creds['access-key'],
        secret_key=creds['secret-key'],
        region=region,
        instance_limit=instance_limit,
        security_group_limit=security_group_limit)
    return client

def _gce_client(creds, region, instance_limit, security_group_limit,
                cpu_limit):
    instance_limit = instance_limit or gce.INSTANCE_LIMIT
    security_group_limit = security_group_limit or gce.SECURITY_GROUP_LIMIT
    cpu_limit = cpu_limit or gce.CPU_LIMIT
    client = gce.GCE(
        sa_email=creds['client-email'],
        key=creds['private-key'],
        region=region,
        project_id=creds['project-id'],
        instance_limit=instance_limit,
        security_group_limit=security_group_limit,
        cpu_limit=cpu_limit
    )
    return client

def _azure_client(creds, region, instance_limit, security_group_limit,
                  cpu_limit, azure_tenant_id):
    instance_limit = instance_limit or azure.INSTANCE_LIMIT
    security_group_limit = security_group_limit or azure.SECURITY_GROUP_LIMIT
    cpu_limit = cpu_limit or azure.CORE_LIMIT
    client = azure.Azure(
        tenant_id=azure_tenant_id,
        subscription_id=creds['subscription-id'],
        application_id=creds['application-id'],
        application_password=creds['application-password'],
        region=region,
        instance_limit=instance_limit,
        security_group_limit=security_group_limit,
        core_limit=cpu_limit
    )
    return client

def is_resource_available(cloud, region,
                          num_of_instances,
                          num_of_security_groups,
                          num_of_cpus,
                          instance_limit=None,
                          security_group_limit=None,
                          cpu_limit=None,
                          credentials_name=None,
                          azure_tenant_id=None):
    """Determine if resources are available to perform tests.

    Check if instance/machine, security group and CPU resources
    are available before performing cwr tests.

    :param cloud: Cloud name
    :param region: Cloud region
    :param num_of_instances: Number of instances needed to perform tests.
    :param num_of_security_groups: Number of security groups needed.
    :param num_of_cpus: Number of CPUs needed
    :param instance_limit:  Instance or machine limit
    :param security_group_limit: Security group limit
    :param cpu_limit:  CPU or core limit. Ignored for AWS cloud.
    :param credentials_name:  Juju credentials name.
    :param azure_tenant_id: Azure tenant id if cloud is set to azure. If set to
      None, it tries to use the AZURE_TENANT_ID environment variable.
    :return boolean
    """
    logging.info('Checking resource for {}'.format(cloud))
    azure_tenant_id = azure_tenant_id or os.getenv('AZURE_TENANT_ID')
    creds = get_credentials(cloud, credentials_name)

    if 'aws' in cloud.lower():
        client = _aws_client(
            creds, region, instance_limit, security_group_limit)
        security_available = client.is_security_group_available(
            num_of_security_groups)
    elif 'google' in cloud.lower():
        client = _gce_client(
            creds, region, instance_limit, security_group_limit, cpu_limit)
        security_available = client.is_security_group_available(
            num_of_security_groups)
    elif 'azure' in cloud.lower():
        if azure_tenant_id is None:
            raise CloudNotSupported(
                'Tenant ID is required to check for Azure resources')
        client = _azure_client(
            creds, region, instance_limit, security_group_limit, cpu_limit,
            azure_tenant_id)
        # Azure does not support listing security groups
        security_available = True
    else:
        raise CloudNotSupported('Cloud not supported {}'.format(cloud))

    instance_available = client.is_instance_available(
        num_of_instances, num_of_cpus)

    return instance_available is True and security_available is True


text:
<?php
// +------------------------------------------------------------------------+
// | class.upload.xx_XX.php                                                 |
// +------------------------------------------------------------------------+
// | Copyright (c) xxxxxx 200x. All rights reserved.                        |
// | Version       0.25                                                     |
// | Last modified xx/xx/200x                                               |
// | Email         xxx@xxx.xxx                                              |
// | Web           http://www.xxxx.xxx                                      |
// +------------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify   |
// | it under the terms of the GNU General Public License version 2 as      |
// | published by the Free Software Foundation.                             |
// |                                                                        |
// | This program is distributed in the hope that it will be useful,        |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of         |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          |
// | GNU General Public License for more details.                           |
// |                                                                        |
// | You should have received a copy of the GNU General Public License      |
// | along with this program; if not, write to the                          |
// |   Free Software Foundation, Inc., 59 Temple Place, Suite 330,          |
// |   Boston, MA 02111-1307 USA                                            |
// |                                                                        |
// | Please give credit on sites that use class.upload and submit changes   |
// | of the script so other people can use them as well.                    |
// | This script is free to use, don't abuse.                               |
// +------------------------------------------------------------------------+

    $translation = array();
    $translation['file_error']                  = 'File error. Please try again.';
    $translation['local_file_missing']          = 'Local file doesn\'t exist.';
    $translation['local_file_not_readable']     = 'Local file is not readable.';
    $translation['uploaded_too_big_ini']        = 'File upload error (the uploaded file exceeds the upload_max_filesize directive in php.ini).';
    $translation['uploaded_too_big_html']       = 'File upload error (the uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form).';
    $translation['uploaded_partial']            = 'File upload error (the uploaded file was only partially uploaded).';
    $translation['uploaded_missing']            = 'File upload error (no file was uploaded).';
    $translation['uploaded_unknown']            = 'File upload error (unknown error code).';
    $translation['try_again']                   = 'File upload error. Please try again.';
    $translation['file_too_big']                = 'File too big.';
    $translation['no_mime']                     = 'MIME type can\'t be detected.';
    $translation['incorrect_file']              = 'Incorrect type of file.';
    $translation['image_too_wide']              = 'Image too wide.';
    $translation['image_too_narrow']            = 'Image too narrow.';
    $translation['image_too_high']              = 'Image too high.';
    $translation['image_too_short']             = 'Image too short.';
    $translation['ratio_too_high']              = 'Image ratio too high (image too wide).';
    $translation['ratio_too_low']               = 'Image ratio too low (image too high).';
    $translation['too_many_pixels']             = 'Image has too many pixels.';
    $translation['not_enough_pixels']           = 'Image has not enough pixels.';
    $translation['file_not_uploaded']           = 'File not uploaded. Can\'t carry on a process.';
    $translation['already_exists']              = '%s already exists. Please change the file name.';
    $translation['temp_file_missing']           = 'No correct temp source file. Can\'t carry on a process.';
    $translation['source_missing']              = 'No correct uploaded source file. Can\'t carry on a process.';
    $translation['destination_dir']             = 'Destination directory can\'t be created. Can\'t carry on a process.';
    $translation['destination_dir_missing']     = 'Destination directory doesn\'t exist. Can\'t carry on a process.';
    $translation['destination_path_not_dir']    = 'Destination path is not a directory. Can\'t carry on a process.';
    $translation['destination_dir_write']       = 'Destination directory can\'t be made writeable. Can\'t carry on a process.';
    $translation['destination_path_write']      = 'Destination path is not a writeable. Can\'t carry on a process.';
    $translation['temp_file']                   = 'Can\'t create the temporary file. Can\'t carry on a process.';
    $translation['source_not_readable']         = 'Source file is not readable. Can\'t carry on a process.';
    $translation['no_create_support']           = 'No create from %s support.';
    $translation['create_error']                = 'Error in creating %s image from source.';
    $translation['source_invalid']              = 'Can\'t read image source. Not an image?.';
    $translation['gd_missing']                  = 'GD doesn\'t seem to be present.';
    $translation['watermark_no_create_support'] = 'No create from %s support, can\'t read watermark.';
    $translation['watermark_create_error']      = 'No %s read support, can\'t create watermark.';
    $translation['watermark_invalid']           = 'Unknown image format, can\'t read watermark.';
    $translation['file_create']                 = 'No %s create support.';
    $translation['no_conversion_type']          = 'No conversion type defined.';
    $translation['copy_failed']                 = 'Error copying file on the server. copy() failed.';
    $translation['reading_failed']              = 'Error reading the file.';

?>


text:
var channel = postal.channel("test");

channel.subscribe("test", function(data){ });

channel.publish("test", {id:1, name:"Test user"});


text:
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta name="generator" content="Hugo 0.57.2" />
<meta property="og:title" content="Program" />
<meta name="twitter:title" content="Program"/>
<meta itemprop="name" content="Program"><meta property="og:description" content="Program for devopsdays Victoria 2018" />
  <meta name="twitter:description" content="Program for devopsdays Victoria 2018" />
  <meta itemprop="description" content="Program for devopsdays Victoria 2018"><meta name="twitter:site" content="@devopsdays">
<meta property="og:type" content="program" />
<meta property="og:url" content="/events/2018-victoria/program/" /><meta name="twitter:creator" content="@devopsdaysyyj" /><meta name="twitter:label1" value="Event" />
  <meta name="twitter:data1" value="devopsdays Victoria 2018" /><meta name="twitter:label2" value="Date" />
    <meta name="twitter:data2" value="May 25, 2018" /><meta property="og:image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta itemprop="image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta property="fb:app_id" content="1904065206497317" /><meta itemprop="wordCount" content="0">
<title>Program
</title>

<link href="/css/site.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300,400,700" rel="stylesheet"><link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192"  href="/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">

      <link href="/events/index.xml" rel="alternate" type="application/rss+xml" title="DevOpsDays" />
      <link href="/events/index.xml" rel="feed" type="application/rss+xml" title="DevOpsDays" />

  DevOpsDays

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

</button>

events

blog

sponsor

speaking

organizing

about

  Victoria
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar2">

</button>

                  propose

                  registration

                  program

                  sponsor

                  contact

                  conduct

Program

May 25, 2018

                            8:30
                            -
                            9:00

Registration Opens

                            9:00
                            -
                            9:30

Intro

                            9:30
                            -
                            10:30

Plum Room - Monolith to Microservices: Managing Organizational Change - Tobias Dunn-Krahn & Mattius McLaughlin

                            9:30
                            -
                            10:00

Studio - What It's Like to a be a Woman in a Male-Dominated Industry - Emily Brenner

                            10:00
                            -
                            10:30

Studio - Serverless - Jeffery Grajkowski

                            10:30
                            -
                            11:30

Plum Room - Taming Infrastructure Workflow at Scale - Anubhav Mishra

                            10:30
                            -
                            11:30

Studio - Agility In Software Engineering - Chris Holland

                            11:30
                            -
                            12:30

Plum Room - ECS and ALB: A pattern for easy and efficient microservices on AWS - Jamie Starke

                            11:30
                            -
                            12:30

Studio - Beyond Tools: A human approach to DevOps - Eduardo Augusto Alves Camargo

                            12:30
                            -
                            1:30

Lunch - Catered

                            1:30
                            -
                            2:30

Plum Room - Challenges to Writing Cloud Native Applications - Vallery Lancey

                            1:30
                            -
                            2:30

Studio - Distributed brute force login attack - Peter Locke

                            2:30
                            -
                            3:30

Plum Room - Bitrot: A Story of Maintenance Failure - Will Whittaker

                            2:30
                            -
                            3:30

Studio - Break Things to Fix Things - Ijeoma Ezeonyebuchi

                            3:30
                            -
                            4:30

Plum Room - Q&A Panel on the state of hiring in Devops

                            3:30
                            -
                            4:30

Studio - Fixing Production in the Hospital

                            4:30
                            -
                            5:30

Unconference

                            5:30
                            -
                            9:00

Social - Pizza and beverages

@DEVOPSDAYS

BLOG

10 years of devopsdays

by Kris Buytaert - 10 May, 2019

It’s hard to believe but it is almost 10 years ago since #devopsdays happened for the first time in Gent. Back then there were almost 70 of us talking about topics that were of interest to both Operations and Development, we were exchanging our ideas and experiences `on how we were improving the quality of software delivery.
Our ideas got started on the crossroads of Open Source, Agile and early Cloud Adoption.

Blogs

10 May, 2019

Feed

CFP OPEN
Campinas
Macapá
Shanghai
Recife
Charlotte
Prague
Tokyo
Salt Lake City

Propose a talk at an event near you!

About

    devopsdays is a worldwide community conference series for anyone interested in IT improvement.

    About devopsdays

    Privacy Policy

    Code of Conduct


text:
@interface IdleStatus : NSObject <StatusInterface>

@end


text:
package org.locationtech.geomesa.features.avro.serde

import org.apache.avro.io.Decoder
import org.locationtech.geomesa.features.ScalaSimpleFeature
import org.locationtech.geomesa.features.avro.AvroSimpleFeatureUtils
import org.locationtech.geomesa.utils.cache.SoftThreadLocal
import org.locationtech.geomesa.utils.text.WKBUtils

import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets
import java.util.Date

/**
 * Trait that encapsulates the methods needed to deserialize
 * an AvroSimpleFeature
 */
trait ASFDeserializer {

  protected val buffers = new SoftThreadLocal[(ByteBuffer, Array[Byte])]

  // note: we don't use the string reading methods, as internal avro state can get corrupted and cause
  // exceptions in BinaryDecoder.scratchUtf8
  def setString(sf: ScalaSimpleFeature, field: Int, in: Decoder): Unit = {
    var (bb, bytes) = buffers.getOrElseUpdate((ByteBuffer.allocate(16), Array.empty))
    bb = in.readBytes(bb)
    val length = bb.remaining
    if (bytes.length < length) {
      bytes = Array.ofDim(length)
    }
    buffers.put((bb, bytes))
    bb.get(bytes, 0, length)
    sf.setAttributeNoConvert(field, new String(bytes, 0, length, StandardCharsets.UTF_8))
  }

  // note: we don't use the string reading methods, as internal avro state can get corrupted and cause
  // exceptions in BinaryDecoder.scratchUtf8
  def consumeString(in: Decoder): Unit = in.skipBytes()

  def setInt(sf: ScalaSimpleFeature, field: Int, in: Decoder): Unit =
    sf.setAttributeNoConvert(field, Int.box(in.readInt()))

  def consumeInt(in: Decoder): Unit = in.readInt()

  def setDouble(sf: ScalaSimpleFeature, field: Int, in: Decoder): Unit =
    sf.setAttributeNoConvert(field, Double.box(in.readDouble()))

  def consumeDouble(in: Decoder): Unit = in.readDouble()

  def setLong(sf: ScalaSimpleFeature, field: Int, in: Decoder): Unit =
    sf.setAttributeNoConvert(field, Long.box(in.readLong()))

  def consumeLong(in: Decoder): Unit = in.readLong()

  def setFloat(sf: ScalaSimpleFeature, field: Int, in: Decoder): Unit =
    sf.setAttributeNoConvert(field, Float.box(in.readFloat()))

  def consumeFloat(in: Decoder): Unit = in.readFloat()

  def setBool(sf: ScalaSimpleFeature, field: Int, in: Decoder): Unit =
    sf.setAttributeNoConvert(field, Boolean.box(in.readBoolean()))

  def consumeBool(in: Decoder): Unit = in.readBoolean()

  def setUUID(sf: ScalaSimpleFeature, field: Int, in: Decoder): Unit = {
    var (bb, bytes) = buffers.getOrElseUpdate((ByteBuffer.allocate(16), Array.empty))
    bb = in.readBytes(bb)
    buffers.put((bb, bytes))
    sf.setAttributeNoConvert(field, AvroSimpleFeatureUtils.decodeUUID(bb))
  }

  def consumeUUID(in: Decoder): Unit = in.skipBytes()

  def setDate(sf: ScalaSimpleFeature, field: Int, in: Decoder): Unit =
    sf.setAttributeNoConvert(field, new Date(in.readLong()))

  def consumeDate(in: Decoder): Unit = in.readLong()

  def setList(sf: ScalaSimpleFeature, field: Int, in: Decoder): Unit = {
    var (bb, bytes) = buffers.getOrElseUpdate((ByteBuffer.allocate(16), Array.empty))
    bb = in.readBytes(bb)
    buffers.put((bb, bytes))
    sf.setAttributeNoConvert(field, AvroSimpleFeatureUtils.decodeList(bb))
  }

  def consumeList(in: Decoder): Unit = in.skipBytes()

  def setMap(sf: ScalaSimpleFeature, field: Int, in: Decoder): Unit = {
    var (bb, bytes) = buffers.getOrElseUpdate((ByteBuffer.allocate(16), Array.empty))
    bb = in.readBytes(bb)
    buffers.put((bb, bytes))
    sf.setAttributeNoConvert(field, AvroSimpleFeatureUtils.decodeMap(bb))
  }

  def consumeMap(in: Decoder): Unit = in.skipBytes()

  def setBytes(sf: ScalaSimpleFeature, field: Int, in: Decoder): Unit = {
    var (bb, bytes) = buffers.getOrElseUpdate((ByteBuffer.allocate(16), Array.empty))
    bb = in.readBytes(bb)
    buffers.put((bb, bytes))
    val value = Array.ofDim[Byte](bb.remaining)
    bb.get(value)
    sf.setAttributeNoConvert(field, value)
  }

  def consumeBytes(in: Decoder): Unit = in.skipBytes()

  def setGeometry(sf: ScalaSimpleFeature, field: Int, in: Decoder): Unit = {
    var (bb, bytes) = buffers.getOrElseUpdate((ByteBuffer.allocate(16), Array.empty))
    bb = in.readBytes(bb)
    val length = bb.remaining
    if (bytes.length < length) {
      bytes = Array.ofDim(length)
    }
    buffers.put((bb, bytes))
    bb.get(bytes, 0, length)
    // note: WKBReader ignores any bytes after the geom
    sf.setAttributeNoConvert(field, WKBUtils.read(bytes))
  }

  def consumeGeometry(in: Decoder): Unit = in.skipBytes()
}


text:
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.android_webview.test;

import android.graphics.Picture;
import android.webkit.ConsoleMessage;

import org.chromium.base.ThreadUtils;
import org.chromium.content.browser.test.util.CallbackHelper;
import org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnEvaluateJavaScriptResultHelper;
import org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnPageFinishedHelper;
import org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnPageStartedHelper;
import org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnReceivedErrorHelper;

/**
 * AwContentsClient subclass used for testing.
 */
public class TestAwContentsClient extends NullContentsClient {
    private String mUpdatedTitle;
    private final OnPageStartedHelper mOnPageStartedHelper;
    private final OnPageFinishedHelper mOnPageFinishedHelper;
    private final OnReceivedErrorHelper mOnReceivedErrorHelper;
    private final OnDownloadStartHelper mOnDownloadStartHelper;
    private final OnReceivedLoginRequestHelper mOnReceivedLoginRequestHelper;
    private final OnEvaluateJavaScriptResultHelper mOnEvaluateJavaScriptResultHelper;
    private final AddMessageToConsoleHelper mAddMessageToConsoleHelper;
    private final OnScaleChangedHelper mOnScaleChangedHelper;
    private final PictureListenerHelper mPictureListenerHelper;
    private final ShouldOverrideUrlLoadingHelper mShouldOverrideUrlLoadingHelper;
    private final DoUpdateVisitedHistoryHelper mDoUpdateVisitedHistoryHelper;

    public TestAwContentsClient() {
        super(ThreadUtils.getUiThreadLooper());
        mOnPageStartedHelper = new OnPageStartedHelper();
        mOnPageFinishedHelper = new OnPageFinishedHelper();
        mOnReceivedErrorHelper = new OnReceivedErrorHelper();
        mOnDownloadStartHelper = new OnDownloadStartHelper();
        mOnReceivedLoginRequestHelper = new OnReceivedLoginRequestHelper();
        mOnEvaluateJavaScriptResultHelper = new OnEvaluateJavaScriptResultHelper();
        mAddMessageToConsoleHelper = new AddMessageToConsoleHelper();
        mOnScaleChangedHelper = new OnScaleChangedHelper();
        mPictureListenerHelper = new PictureListenerHelper();
        mShouldOverrideUrlLoadingHelper = new ShouldOverrideUrlLoadingHelper();
        mDoUpdateVisitedHistoryHelper = new DoUpdateVisitedHistoryHelper();
    }

    public OnPageStartedHelper getOnPageStartedHelper() {
        return mOnPageStartedHelper;
    }

    public OnPageFinishedHelper getOnPageFinishedHelper() {
        return mOnPageFinishedHelper;
    }

    public OnReceivedErrorHelper getOnReceivedErrorHelper() {
        return mOnReceivedErrorHelper;
    }

    public OnDownloadStartHelper getOnDownloadStartHelper() {
        return mOnDownloadStartHelper;
    }

    public OnReceivedLoginRequestHelper getOnReceivedLoginRequestHelper() {
        return mOnReceivedLoginRequestHelper;
    }

    public OnEvaluateJavaScriptResultHelper getOnEvaluateJavaScriptResultHelper() {
        return mOnEvaluateJavaScriptResultHelper;
    }

    public ShouldOverrideUrlLoadingHelper getShouldOverrideUrlLoadingHelper() {
        return mShouldOverrideUrlLoadingHelper;
    }

    public AddMessageToConsoleHelper getAddMessageToConsoleHelper() {
        return mAddMessageToConsoleHelper;
    }

    public DoUpdateVisitedHistoryHelper getDoUpdateVisitedHistoryHelper() {
        return mDoUpdateVisitedHistoryHelper;
    }

    /**
     * Callback helper for onScaleChangedScaled.
     */
    public static class OnScaleChangedHelper extends CallbackHelper {
        private float mPreviousScale;
        private float mCurrentScale;
        public void notifyCalled(float oldScale, float newScale) {
            mPreviousScale = oldScale;
            mCurrentScale = newScale;
            super.notifyCalled();
        }

        public float getOldScale() {
            return mPreviousScale;
        }

        public float getNewScale() {
            return mCurrentScale;
        }

        public float getLastScaleRatio() {
            assert getCallCount() > 0;
            return mCurrentScale / mPreviousScale;
        }
    }

    public OnScaleChangedHelper getOnScaleChangedHelper() {
        return mOnScaleChangedHelper;
    }

    public PictureListenerHelper getPictureListenerHelper() {
        return mPictureListenerHelper;
    }

    @Override
    public void onReceivedTitle(String title) {
        mUpdatedTitle = title;
    }

    public String getUpdatedTitle() {
        return mUpdatedTitle;
    }

    @Override
    public void onPageStarted(String url) {
        mOnPageStartedHelper.notifyCalled(url);
    }

    @Override
    public void onPageFinished(String url) {
        mOnPageFinishedHelper.notifyCalled(url);
    }

    @Override
    public void onReceivedError(int errorCode, String description, String failingUrl) {
        mOnReceivedErrorHelper.notifyCalled(errorCode, description, failingUrl);
    }

    /**
     * CallbackHelper for OnDownloadStart.
     */
    public static class OnDownloadStartHelper extends CallbackHelper {
        private String mUrl;
        private String mUserAgent;
        private String mContentDisposition;
        private String mMimeType;
        long mContentLength;

        public String getUrl() {
            assert getCallCount() > 0;
            return mUrl;
        }

        public String getUserAgent() {
            assert getCallCount() > 0;
            return mUserAgent;
        }

        public String getContentDisposition() {
            assert getCallCount() > 0;
            return mContentDisposition;
        }

        public String getMimeType() {
            assert getCallCount() > 0;
            return mMimeType;
        }

        public long getContentLength() {
            assert getCallCount() > 0;
            return mContentLength;
        }

        public void notifyCalled(String url, String userAgent, String contentDisposition,
                String mimeType, long contentLength) {
            mUrl = url;
            mUserAgent = userAgent;
            mContentDisposition = contentDisposition;
            mMimeType = mimeType;
            mContentLength = contentLength;
            notifyCalled();
        }
    }

    @Override
    public void onDownloadStart(String url,
            String userAgent,
            String contentDisposition,
            String mimeType,
            long contentLength) {
        getOnDownloadStartHelper().notifyCalled(url, userAgent, contentDisposition, mimeType,
                contentLength);
    }

    /**
     * CallbackHelper for OnReceivedLoginRequest.
     */
    public static class OnReceivedLoginRequestHelper extends CallbackHelper {
        private String mRealm;
        private String mAccount;
        private String mArgs;

        public String getRealm() {
            assert getCallCount() > 0;
            return mRealm;
        }

        public String getAccount() {
            assert getCallCount() > 0;
            return mAccount;
        }

        public String getArgs() {
            assert getCallCount() > 0;
            return mArgs;
        }

        public void notifyCalled(String realm, String account, String args) {
            mRealm = realm;
            mAccount = account;
            mArgs = args;
            notifyCalled();
        }
    }

    @Override
    public void onReceivedLoginRequest(String realm, String account, String args) {
        getOnReceivedLoginRequestHelper().notifyCalled(realm, account, args);
    }

    @Override
    public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
        mAddMessageToConsoleHelper.notifyCalled(consoleMessage.messageLevel().ordinal(),
                consoleMessage.message(), consoleMessage.lineNumber(), consoleMessage.sourceId());
        return false;
    }

    /**
     * Callback helper for onScaleChangedScaled.
     */
    public static class AddMessageToConsoleHelper extends CallbackHelper {
        private int mLevel;
        private String mMessage;
        private int mLineNumber;
        private String mSourceId;

        public int getLevel() {
            assert getCallCount() > 0;
            return mLevel;
        }

        public String getMessage() {
            assert getCallCount() > 0;
            return mMessage;
        }

        public int getLineNumber() {
            assert getCallCount() > 0;
            return mLineNumber;
        }

        public String getSourceId() {
            assert getCallCount() > 0;
            return mSourceId;
        }

        void notifyCalled(int level, String message, int lineNumer, String sourceId) {
            mLevel = level;
            mMessage = message;
            mLineNumber = lineNumer;
            mSourceId = sourceId;
            notifyCalled();
        }
    }

    @Override
    public void onScaleChangedScaled(float oldScale, float newScale) {
        mOnScaleChangedHelper.notifyCalled(oldScale, newScale);
    }

    /**
     * Callback helper for onScaleChangedScaled.
     */
    public static class PictureListenerHelper extends CallbackHelper {
        // Generally null, depending on |invalidationOnly| in enableOnNewPicture()
        private Picture mPicture;

        public Picture getPicture() {
            assert getCallCount() > 0;
            return mPicture;
        }

        void notifyCalled(Picture picture) {
            mPicture = picture;
            notifyCalled();
        }
    }

    @Override
    public void onNewPicture(Picture picture) {
        mPictureListenerHelper.notifyCalled(picture);
    }

    /**
     * Callback helper for onScaleChangedScaled.
     */
    public static class ShouldOverrideUrlLoadingHelper extends CallbackHelper {
        private String mShouldOverrideUrlLoadingUrl;
        private String mPreviousShouldOverrideUrlLoadingUrl;
        private boolean mShouldOverrideUrlLoadingReturnValue = false;
        void setShouldOverrideUrlLoadingUrl(String url) {
            mShouldOverrideUrlLoadingUrl = url;
        }
        void setPreviousShouldOverrideUrlLoadingUrl(String url) {
            mPreviousShouldOverrideUrlLoadingUrl = url;
        }
        void setShouldOverrideUrlLoadingReturnValue(boolean value) {
            mShouldOverrideUrlLoadingReturnValue = value;
        }
        public String getShouldOverrideUrlLoadingUrl() {
            assert getCallCount() > 0;
            return mShouldOverrideUrlLoadingUrl;
        }
        public String getPreviousShouldOverrideUrlLoadingUrl() {
            assert getCallCount() > 1;
            return mPreviousShouldOverrideUrlLoadingUrl;
        }
        public boolean getShouldOverrideUrlLoadingReturnValue() {
            return mShouldOverrideUrlLoadingReturnValue;
        }
        public void notifyCalled(String url) {
            mPreviousShouldOverrideUrlLoadingUrl = mShouldOverrideUrlLoadingUrl;
            mShouldOverrideUrlLoadingUrl = url;
            notifyCalled();
        }
    }

    @Override
    public boolean shouldOverrideUrlLoading(String url) {
        super.shouldOverrideUrlLoading(url);
        boolean returnValue =
            mShouldOverrideUrlLoadingHelper.getShouldOverrideUrlLoadingReturnValue();
        mShouldOverrideUrlLoadingHelper.notifyCalled(url);
        return returnValue;
    }

    /**
     * Callback helper for doUpdateVisitedHistory.
     */
    public static class DoUpdateVisitedHistoryHelper extends CallbackHelper {
        String mUrl;
        boolean mIsReload;

        public String getUrl() {
            assert getCallCount() > 0;
            return mUrl;
        }

        public boolean getIsReload() {
            assert getCallCount() > 0;
            return mIsReload;
        }

        public void notifyCalled(String url, boolean isReload) {
            mUrl = url;
            mIsReload = isReload;
            notifyCalled();
        }
    }

    @Override
    public void doUpdateVisitedHistory(String url, boolean isReload) {
        getDoUpdateVisitedHistoryHelper().notifyCalled(url, isReload);
    }
}


text:
package com.hribol.bromium.replay.execution.scenario;

import com.google.common.collect.ImmutableMap;
import com.hribol.bromium.core.TestScenarioSteps;
import com.hribol.bromium.core.parsing.StepsReader;
import com.hribol.bromium.replay.actions.WebDriverAction;
import com.hribol.bromium.replay.execution.application.ApplicationAction;
import com.hribol.bromium.replay.execution.application.ApplicationActionFactory;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * Created by hvrigazov on 22.04.17.
 */
public class TestScenarioFactoryTest {

    @Test
    public void canCreateScenarioFromFile() throws IOException {
        String pathToTestCase = getClass().getResource("/testCase.json").getFile();

        WebDriverAction pageLoadingWebDriverAction = mock(WebDriverAction.class);
        ApplicationAction initialPageLoading = mock(ApplicationAction.class);
        when(initialPageLoading.getWebdriverAction()).thenReturn(Optional.of(pageLoadingWebDriverAction));
        ApplicationActionFactory applicationActionFactory = mock(ApplicationActionFactory.class);

        TestScenarioSteps testCaseSteps = createExpectedSteps();

        createMock(applicationActionFactory, testCaseSteps);

        StepsReader stepsReader = mock(StepsReader.class);
        when(stepsReader.readSteps(any())).thenReturn(testCaseSteps);
        TestScenarioFactory testScenarioFactory = new TestScenarioFactory(applicationActionFactory, stepsReader);
        TestScenario testScenario = testScenarioFactory.createFromFile(pathToTestCase);

        assertEquals(testCaseSteps.size(), testScenario.getActions().size());
    }

    @Test
    public void canCreateScenarioFromInput() throws IOException {
        String pathToTestCase = getClass().getResource("/testCase.json").getFile();
        try (FileInputStream fileInputStream = new FileInputStream(pathToTestCase)) {
            WebDriverAction pageLoadingWebDriverAction = mock(WebDriverAction.class);
            ApplicationAction initialPageLoading = mock(ApplicationAction.class);
            when(initialPageLoading.getWebdriverAction()).thenReturn(Optional.of(pageLoadingWebDriverAction));
            ApplicationActionFactory applicationActionFactory = mock(ApplicationActionFactory.class);

            TestScenarioSteps testCaseSteps = createExpectedSteps();

            createMock(applicationActionFactory, testCaseSteps);

            StepsReader stepsReader = mock(StepsReader.class);
            when(stepsReader.readSteps(fileInputStream)).thenReturn(testCaseSteps);
            TestScenarioFactory testScenarioFactory = new TestScenarioFactory(applicationActionFactory, stepsReader);
            TestScenario testScenario = testScenarioFactory.createFromInputStream(fileInputStream);

            assertEquals(testCaseSteps.size(), testScenario.getActions().size());
        }
    }

    private TestScenarioSteps createExpectedSteps() {
        TestScenarioSteps testScenarioSteps = new TestScenarioSteps();
        testScenarioSteps.add(createExpectedEventWithText("Григор Димитров"));
        testScenarioSteps.add(createExpectedEventWithText("Тенис оказион"));
        testScenarioSteps.add(createExpectedEventWithText("Любопитно"));
        return testScenarioSteps;
    }

    private Map<String, String> createExpectedEventWithText(String text) {
        return ImmutableMap.of("text", text, "event", "clickMegaMenu");
    }

    private void createMock(ApplicationActionFactory applicationActionFactory, TestScenarioSteps testCaseSteps) {
        for (Map<String, String> testCaseStep: testCaseSteps) {
            ApplicationAction domainSpecificAction = mock(ApplicationAction.class);
            String something = "something";
            WebDriverAction webDriverAction = mock(WebDriverAction.class);
            when(webDriverAction.getName()).thenReturn(something);
            when(domainSpecificAction.getPrecondition()).thenReturn(Optional.empty());
            when(domainSpecificAction.getWebdriverAction()).thenReturn(Optional.of(webDriverAction));
            when(domainSpecificAction.getPostcondition()).thenReturn(Optional.empty());
            when(applicationActionFactory.create(eq(testCaseStep), anyInt())).thenReturn(domainSpecificAction);
        }
    }
}


text:
package com.meteotester.entities;

import java.util.Date;

public class WeatherCache {

	String json;
	Date timestamp;
	int placeId;

	public WeatherCache(String json, Date timestamp, int placeId) {
		super();
		this.json = json;
		this.timestamp = timestamp;
		this.placeId = placeId;
	}

	public String getJson() {
		return json;
	}

	public void setJson(String json) {
		this.json = json;
	}

	public Date getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(Date timestamp) {
		this.timestamp = timestamp;
	}

	public int getPlaceId() {
		return placeId;
	}

	public void setPlaceId(int placeId) {
		this.placeId = placeId;
	}
}


text:
import axios, { AxiosResponse, CancelToken } from 'axios';
import { equals } from 'ramda';

import { Resource, ResourceCategory, ResourceType } from '../../models';
import { AcknowledgeFormValues } from '../Resource/Acknowledge';
import { DowntimeToPost } from '../Resource/Downtime';

import {
  acknowledgeEndpoint,
  checkEndpoint,
  commentEndpoint,
  downtimeEndpoint
} from './endpoint';

interface ResourcesWithAcknowledgeParams {
  cancelToken: CancelToken;
  params: AcknowledgeFormValues;
  resources: Array<Resource>;
}

const acknowledgeResources =
  (cancelToken: CancelToken) =>
  ({
    resources,
    params
  }: ResourcesWithAcknowledgeParams): Promise<Array<AxiosResponse>> => {
    const payload = resources.map(({ type, id, parent, service_id }) => ({
      id: equals(type, ResourceType.anomalydetection) ? service_id : id,
      parent: parent ? { id: parent?.id } : null,
      type: ResourceCategory[type]
    }));

    return axios.post(
      acknowledgeEndpoint,
      {
        acknowledgement: {
          comment: params.comment,
          is_notify_contacts: params.notify,
          is_persistent_comment: params.persistent,
          is_sticky: params.isSticky,
          with_services: params.acknowledgeAttachedResources
        },
        resources: payload
      },
      { cancelToken }
    );
  };

interface ResourcesWithDowntimeParams {
  params: DowntimeToPost;
  resources: Array<Resource>;
}

const setDowntimeOnResources =
  (cancelToken: CancelToken) =>
  ({
    resources,
    params
  }: ResourcesWithDowntimeParams): Promise<AxiosResponse> => {
    const payload = resources.map(({ type, id, parent, service_id }) => ({
      id: equals(type, ResourceType.anomalydetection) ? service_id : id,
      parent: parent ? { id: parent?.id } : null,
      type: ResourceCategory[type]
    }));

    return axios.post(
      downtimeEndpoint,
      {
        downtime: {
          comment: params.comment,
          duration: params.duration,
          end_time: params.endTime,
          is_fixed: params.fixed,
          start_time: params.startTime,
          with_services: params.isDowntimeWithServices
        },
        resources: payload
      },
      { cancelToken }
    );
  };

interface ResourcesWithRequestParams {
  cancelToken: CancelToken;
  resources: Array<Resource>;
}

const checkResources = ({
  resources,
  cancelToken
}: ResourcesWithRequestParams): Promise<AxiosResponse> => {
  const payload = resources.map(({ type, id, parent, service_id }) => ({
    id: equals(type, ResourceType.anomalydetection) ? service_id : id,
    parent: parent ? { id: parent?.id } : null,
    type: ResourceCategory[type]
  }));

  return axios.post(
    checkEndpoint,
    {
      resources: payload
    },
    { cancelToken }
  );
};

export interface CommentParameters {
  comment: string;
  date: string;
}

interface ResourcesWithCommentParams {
  parameters: CommentParameters;
  resources: Array<Resource>;
}

const commentResources =
  (cancelToken: CancelToken) =>
  ({
    resources,
    parameters
  }: ResourcesWithCommentParams): Promise<AxiosResponse> => {
    return axios.post(
      commentEndpoint,
      {
        resources: resources.map((resource) => ({
          comment: parameters.comment,
          date: parameters.date,
          id: equals(resource.type, ResourceType.anomalydetection)
            ? resource?.service_id
            : resource.id,
          parent: resource?.parent ? { id: resource?.parent?.id } : null,
          type: ResourceCategory[resource.type]
        }))
      },
      { cancelToken }
    );
  };

export {
  acknowledgeResources,
  setDowntimeOnResources,
  checkResources,
  commentResources
};


text:
"""
PythEOS
=======

PythEOS is an open source python toolbox for equation of state (EOS).
It includes:
- a range of different equations
- EOS fitting tools
- a range of pressure scales

Some important motivations are:
- reproducible error propagation for EOS
- flexible EOS fitting with a wide range of combinations of static, thermal, electronic, and anharmonic effects
- reliable conversion of pressure scale

**Notations**

:param n: number of elements in a chemical formula
:param z: number of formula unit in a unit cell
:param m: molar mass in gram

:param p: pressure in GPa
:param v: unit-cell volume in A^3
:param temp: temperature in K
:param rho: density in g/cm^3

:param k0: bulk modulus at reference conditions
:param k0p: pressure derivative of bulk modulus at reference conditions

:param c0: velocity at 1 bar in km/s
:param s: slope of the velocity change
:param rho0: density at 1 bar in g/cm^3
:param v0: unit-cell volume in A^3 at 1 bar
:param e0: parameter in K-1 for the Zharkov equation
:param g: parameter for the Zharkov equation
:param gamma0: Gruneisen parameter at 1 bar
:param q: logarithmic derivative of Gruneisen parameter
:param theta0: Debye temperature in K

:param t_ref: reference temperature, 300 K
:param three_r: 3 times gas constant.
    Jamieson modified this value to compensate for mismatches
:param c_v: heat capacity

:param min_strain: defining minimum v/v0 value to search volume for

:param params_hugoniot: hugoniot parameters.
    [rho0 in g/cm3, c0 in km/s, s] for linear case and
    [rho0 in g/cm3, a in km/s, b, c in s/km] for non-linear case.
    See Jamieson for detail.
:param params_therm: thermal parameters for the constq equations
    [v0 in A3, gamma0, q, theta0 in K]

:param c_v: heat capacity for hugoniot temperature calculation
:param nonlinear: nonlinear Us-Up fit particularly for Jamieson's gold
    scale
:param reference: reference for the EOS

"""
from .eqn_bm3 import bm3_p, bm3_v, bm3_k, bm3_g, \
    bm3_small_f, bm3_big_F, bm3_k_num  # , bm3_p_u, bm3_v_u, bm3_k_u
from .eqn_vinet import vinet_p, vinet_v, vinet_k, \
    vinet_k_num  # ,  vinet_p_u, vinet_v_u, vinet_k_u
from .eqn_kunc import kunc_p, kunc_v, kunc_k_num  # , kunc_p_u, kunc_v_u
from .eqn_hugoniot import hugoniot_p, hugoniot_t, hugoniot_rho
from .eqn_jamieson import jamieson_pst, jamieson_pth
from .eqn_debye import debye_E
from .eqn_therm_constq import constq_grun, \
    constq_debyetemp, constq_pth
from .eqn_therm_Tange import tange_grun, tange_debyetemp, \
    tange_pth
from .eqn_therm_Speziale import speziale_grun, speziale_debyetemp, \
    speziale_pth
from .eqn_therm_Dorogokupets2007 import altshuler_grun, altshuler_debyetemp,\
    dorogokupets2007_pth
from .eqn_therm_Dorogokupets2015 import dorogokupets2015_pth
from .eqn_anharmonic import zharkov_panh
from .eqn_electronic import zharkov_pel
from .fit_static import BM3Model, VinetModel, KuncModel
from .fit_thermal import ConstqModel, Dorogokupets2007Model, \
    Dorogokupets2015Model, SpezialeModel, TangeModel
from .fit_electronic import ZharkovElecModel
from .fit_anharmonic import ZharkovAnhModel
from .conversion import vol_uc2mol
from . import plot
from .scales import gold
from .scales import platinum
from .scales import periclase


text:
Name: {{customer.name}} Address: {{customer.address}}
<hr>
Name: {{vojta.name}} Address: {{vojta.address}}


text:
package com.dji.geodemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import dji.sdk.base.BaseProduct;
import dji.sdk.products.Aircraft;

public class ConnectionActivity extends Activity implements View.OnClickListener {

    private static final String TAG = ConnectionActivity.class.getName();

    private TextView mTextConnectionStatus;
    private TextView mTextProduct;
    private Button mBtnOpen;
    private Button mBtnSend;

    /*Pola dodane*/
    private TextView mTxtResult;
    private EditText mEdTxtAdres;
    private EditText mEdTxtPort;

    String ADRES_SERVER_PORT = "192.168.0.103";
    int UDP_SERVER_PORT = 8040;
    String keyIdentifer = "ConnectionActivity";
    int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // When the compile and target version is higher than 22, please request the
        // following permissions at runtime to ensure the
        // SDK work well.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.VIBRATE,
                            android.Manifest.permission.INTERNET, android.Manifest.permission.ACCESS_WIFI_STATE,
                            android.Manifest.permission.WAKE_LOCK, android.Manifest.permission.ACCESS_COARSE_LOCATION,
                            android.Manifest.permission.ACCESS_NETWORK_STATE, android.Manifest.permission.ACCESS_FINE_LOCATION,
                            android.Manifest.permission.CHANGE_WIFI_STATE, android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
                            android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.SYSTEM_ALERT_WINDOW,
                            android.Manifest.permission.READ_PHONE_STATE,
                    }
                    , 1);
        }

        setContentView(R.layout.activity_connection);

        initUI();

        // Register the broadcast receiver for receiving the device connection's changes.
        IntentFilter filter = new IntentFilter();
        filter.addAction(GEODemoApplication.FLAG_CONNECTION_CHANGE);
        registerReceiver(mReceiver, filter);
    }

    @Override
    public void onResume() {
        Log.e(TAG, "onResume");
        super.onResume();
    }

    @Override
    public void onPause() {
        Log.e(TAG, "onPause");
        super.onPause();
    }

    @Override
    public void onStop() {
        Log.e(TAG, "onStop");
        super.onStop();
    }

    public void onReturn(View view){
        Log.e(TAG, "onReturn");
        this.finish();
    }

    private void runUdpClient()  {

        /* Przerzutujmy dodane pola w tej funkcji*/
        TextView wynik = (TextView) findViewById(R.id.textViewResult);
        EditText adres = (EditText) findViewById(R.id.editTextAdresIP);
        EditText port = (EditText) findViewById(R.id.editTextPortUDP);

        /*wpisz adres i port z pol tekstowych do zmiennych globalnych*/
        ADRES_SERVER_PORT = adres.getText().toString();
        UDP_SERVER_PORT = Integer.parseInt(port.getText().toString());

        if(count <= 255)
            count++;
        else
            count = 0;

        //Paczka w postaci: Licznik, Nazwa, Czas, Long, Lat, Alt;
        String udpMsg = String.valueOf(count)+",Nazwa_Urządzenia,Numer_seryjny,Nazwa_operatora,12039.423423,52.21345,20.3414132,100.31,350.3,0,1.1,2.2,3.3";
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket();
            InetAddress serverAddr = InetAddress.getByName(ADRES_SERVER_PORT);
            DatagramPacket dp;
            dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), serverAddr, UDP_SERVER_PORT);
            ds.send(dp);
            wynik.setText("Wysłano...");
        } catch (SocketException e) {
            e.printStackTrace();
            wynik.setText("SocketException e");
        } catch (IOException e) {
            e.printStackTrace();
            wynik.setText("IOException e");
        } catch (Exception e) {
            e.printStackTrace();
            wynik.setText("Exception e");
        } finally {
            if (ds != null) {
                ds.close();
            }
        }
    }

    private void initUI() {

        mTextConnectionStatus = (TextView) findViewById(R.id.text_connection_status);
        mTextProduct = (TextView) findViewById(R.id.text_product_info);
        mBtnOpen = (Button) findViewById(R.id.btn_open);
        mBtnSend = (Button) findViewById(R.id.button_send_udp);
        mTxtResult = (TextView) findViewById(R.id.textViewResult);
        mBtnSend.setOnClickListener(this);
        mBtnOpen.setOnClickListener(this);
        mBtnOpen.setEnabled(false);

        /*Dodane pola*/
        mEdTxtAdres = (EditText) findViewById(R.id.editTextAdresIP);
        mEdTxtPort = (EditText) findViewById(R.id.editTextPortUDP);
        mTxtResult = (TextView) findViewById(R.id.textViewResult);

    }

    @Override
    protected void onDestroy() {
        Log.e(TAG, "onDestroy");
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    protected BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            refreshSDKRelativeUI();

        }
    };

    private void refreshSDKRelativeUI() {
        BaseProduct mProduct = GEODemoApplication.getProductInstance();

        if (null != mProduct && mProduct.isConnected()) {
            Log.v(TAG, "refreshSDK: True");
            mBtnOpen.setEnabled(true);

            String str = mProduct instanceof Aircraft ? "Aircraft" : "HandHeld";
            mTextConnectionStatus.setText("Status: " + str + " connected");

            if (null != mProduct.getModel()) {
                mTextProduct.setText("" + mProduct.getModel().getDisplayName());
            } else {
                mTextProduct.setText(R.string.product_information);
            }

        } else {
            Log.v(TAG, "refreshSDK: False");
            mBtnOpen.setEnabled(false);

            mTextProduct.setText(R.string.product_information);
            mTextConnectionStatus.setText(R.string.connection_loose);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btn_open: {
                runUdpClient();
                Intent intent = new Intent(this, MainActivity.class);
                String msg2Main = ADRES_SERVER_PORT + "," + String.valueOf(UDP_SERVER_PORT);
                intent.putExtra(keyIdentifer,msg2Main);
                startActivity(intent);
                break;
            }

            case R.id.button_send_udp:{

                runUdpClient();

                break;
            }
            default:
                break;
        }
    }

}