/*
(non-Javadoc)

@see
com.impetus.kundera.persistence.TransactionBinder#bind(com.impetus.kundera
.persistence.TransactionResource)
491980
@Override
    public void bind(TransactionResource resource)
    {
        // Not checking for type of TransactionRes
        if (resource != null && resource instanceof RedisTransaction)
        {
            this.resource = resource;
        }
        else
        {
            throw new KunderaTransactionException("Invalid transaction resource provided:" + resource
                    + " Should have been an instance of :" + RedisTransaction.class);
        }
    }
423112
@Override
	public void bind(Name name, Object obj) throws NamingException
    {
        if (name.isEmpty())
            throw new InvalidNameException("Cannot bind empty name");

        // Extract components that belong to this namespace
        String nm = name.toString();

        // Find object in internal hash table
        if (bindings.get(nm) != null)
        {
            throw new NameAlreadyBoundException("Use rebind to override");
        }

        // Add object to internal hash table
        bindings.put(nm, obj);
    }
1145811
protected void bindClass(PersistentEntity domainClass, PersistentClass persistentClass, InFlightMetadataCollector mappings) {

        // set lazy loading for now
        persistentClass.setLazy(true);
        final String entityName = domainClass.getName();
        persistentClass.setEntityName(entityName);
        persistentClass.setJpaEntityName(unqualify(entityName));
        persistentClass.setProxyInterfaceName(entityName);
        persistentClass.setClassName(entityName);

        // set dynamic insert to false
        persistentClass.setDynamicInsert(false);
        // set dynamic update to false
        persistentClass.setDynamicUpdate(false);
        // set select before update to false
        persistentClass.setSelectBeforeUpdate(false);

        // add import to mappings
        String en = persistentClass.getEntityName();
        if (mappings.getMetadataBuildingOptions().getMappingDefaults().isAutoImportEnabled() && en.indexOf('.') > 0) {
            String unqualified = unqualify(en);
            mappings.addImport(unqualified, en);
        }
    }
5443
@NonNull @UiThread
  public static Unbinder bind(@NonNull Activity target) {
    View sourceView = target.getWindow().getDecorView();
    return bind(target, sourceView);
  }
837685
static void joinExtendedPC(JPAExPcBindingContext bindingContext, AbstractJPAComponent jpaComponent) {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(tc, "enlistExtendedPC: " + bindingContext.thisToString());

        if (bindingContext.isBmt()) {
            if (isTraceOn && tc.isEntryEnabled())
                Tr.exit(tc, "enlistExtendedPC: incorrectly called with BMT context");
            throw new IllegalArgumentException();
        }

        UOWCoordinator uowCoord = jpaComponent.getUOWCurrent().getUOWCoord();
        if (!uowCoord.isGlobal()) {
            if (isTraceOn && tc.isEntryEnabled())
                Tr.exit(tc, "enlistExtendedPC: incorrectly called outside global tx");
            throw new IllegalStateException();
        }

        SynchronizationRegistryUOWScope uowSyncRegistry = getSynchronizationRegistryUOWScope(uowCoord);

        // New this binding key only once and update the puid in the loop
        ExPcBindingKey bindingKey = new ExPcBindingKey(bindingContext.getBindId(), null);
        for (JPAPuId puId : bindingContext.getExPcPuIds()) {
            bindingKey.puId = puId;
            ExPcBindingInfo exPcBindingInfo = getExPcBindingInfo(bindingKey);
            boolean txUnsynchronized = exPcBindingInfo.isTxUnsynchronized();

            if (exPcBindingInfo.em == null) {
                if (isTraceOn && tc.isDebugEnabled())
                    Tr.debug(tc, "not joining unused lazy persistence context");

                // Per spec, we should associate an invocation with the
                // transaction to either give an error now if an incompatible
                // EM is already associated with the transaction, to give an
                // error if a subsequent SFSB is enlisted with a different ExPC,
                // or to ensure that this ExPC is used by all EMs (ExPC or
                // otherwise) that access the PU from this transaction.  We have
                // never done this eager enlistment (and instead done lazy
                // enlistment and lazy EM acquisition), so we can't change now
                // without risking a change in behavior.
            } else {
                JPAExEmInvocation invocationEm = getInvocation(uowSyncRegistry, exPcBindingInfo.txKeyPuId);
                if (invocationEm == null) {
                    if (isTraceOn && tc.isDebugEnabled())
                        Tr.debug(tc, "joining " + exPcBindingInfo.txKeyPuId);

                    invocationEm = jpaComponent.getJPARuntime().createExEmInvocation(uowCoord, exPcBindingInfo.em, txUnsynchronized);
                    setInvocation(uowSyncRegistry, exPcBindingInfo.txKeyPuId, invocationEm);

                    // JPA 5.9.1 Container Responsibilities
                    //
                    // For stateful session beans with extended persistence contexts:
                    // ** When a business method of the stateful session bean is invoked, if the stateful
                    //    session bean uses container managed transaction demarcation, and the entity
                    //    manager is not already associated with the current JTA transaction, the
                    //    container associates the entity manager with the current JTA transaction and
                    //    calls EntityManager.joinTransaction.

                    // Verify that the tx synchronizations are compatible
                    if (txUnsynchronized != invocationEm.ivUnsynchronized) {
                        Tr.error(tc, "JPATXSYNC_ILLEGAL_PROPAGATION_CWWJP0046E");
                        String msgTxt = "CWWJP0046E: An UNSYNCHRONIZED JPA persistence context cannot be propagated into a SYNCHRONIZED EntityManager.";
                        throw new IllegalStateException(msgTxt);
                    }
                    if (!txUnsynchronized) {
                        exPcBindingInfo.em.joinTransaction();
                    }
                } else {
                    // JPA 5.9.1 Container Responsibilities
                    //
                    // For stateful session beans with extended persistence contexts:
                    // ** If there is a different persistence context already associated with the JTA
                    //    transaction, the container throws the EJBException.
                    if (invocationEm.ivEm != exPcBindingInfo.em) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                            Tr.exit(tc, "enlistExtendedPC : Different persistence context already associate with a JTA tx.");
                        throw jpaComponent.getExPcBindingContext().newEJBException
                                        ("5.9.1 A persistence context is associated to the current JTA transaction " +
                                         "and it is different than the extend-scoped persistence context bound to this SFSB.");
                    }

                    // Verify that the tx synchronizations are compatible
                    if (txUnsynchronized != invocationEm.ivUnsynchronized) {
                        Tr.error(tc, "JPATXSYNC_INCOMPATIBLE_PROPAGATION_CWWJP0047E",
                                 exPcBindingInfo.txKeyPuId,
                                 (invocationEm.ivUnsynchronized ? "UNSYNCHRONIZED" : "SYNCHRONIZED"),
                                 bindingContext.getName());

                        StringBuilder sb = new StringBuilder();
                        sb.append("CWWJP0047E: The persistence context associated with persistence unit '");
                        sb.append(exPcBindingInfo.txKeyPuId);
                        sb.append("' has SynchronizationType of type ");
                        sb.append((invocationEm.ivUnsynchronized ? "UNSYNCHRONIZED" : "SYNCHRONIZED"));
                        sb.append(", which is incompatible with the extended persistence context ");
                        sb.append("declared by ");
                        sb.append(bindingContext.getName());
                        throw new IllegalStateException(new String(sb));
                    }
                }
            }
        }

        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(tc, "enlistExtendedPC");
    }
720090
public void unbind(String name) throws ObjectNameNotFoundException
    {
        /**
         * Is DB open? ODMG 3.0 says it has to be to call unbind.
         */
        if (!this.isOpen())
        {
            throw new DatabaseClosedException("Database is not open. Must have an open DB to call unbind");
        }
        TransactionImpl tx = getTransaction();
        if (tx == null || !tx.isOpen())
        {
            throw new TransactionNotInProgressException("Tx is not open. Must have an open TX to call lookup.");
        }

        tx.getNamedRootsMap().unbind(name);
    }
514005
@Override
	public void bind(String name, Object obj) throws NamingException
    {
        bind(new CompositeName(name), obj);
    }
106016
@Override
    public void resolve(InjectionBinding<Context> binding)
                    throws InjectionException {
        final String methodName = "resolve";
        if (tc.isEntryEnabled()) {
            Tr.entry(tc, methodName, binding);
        }
        Class<?> injectionType = binding.getInjectionClassType();

        if (tc.isDebugEnabled()) {
            Tr.debug(tc,
                     "Setting the ContextObjectFactory on the ContextInjectionBinding for type {0}",
                     injectionType);
        }
        Reference ref = new Reference(injectionType.getName());
        binding.setReferenceObject(ref, ContextObjectFactory.class);

        if (tc.isEntryEnabled())
            Tr.exit(tc, methodName, binding);
    }
93563
@NonNull
    public <E extends T> MapperBuilder<T> bind(@NonNull Class<E> itemClass,
                                               @NonNull Binder<? super E, ?> binder) {
        //noinspection unchecked
        return bind(itemClass, 0, binder, ALWAYS);
    }
1274580
public void unbind(DataSource dataSource) throws NamingException {
        if (dataSource == null) {
            throw new IllegalArgumentException("dataSource cannot be null");
        }
        String jndiUrl = this.dataSourceBindings.get(dataSource);
        if (jndiUrl == null) {
            throw new NamingException("No such binding");
        }
        this.initialContext.unbind(jndiUrl);
        this.dataSourceBindings.remove(dataSource);
    }
773354
public ClientInterfaceHandleManager bindAdapter(final Connection adapter, final ClientInterfaceRepairCallback repairCallback) {
        return bindAdapter(adapter, repairCallback, false);
    }
960037
public static void bind(Class clazz, Class<? extends Extension> implementation) {
        bind.put(clazz, implementation);
    }
823479
public void bindSelect(PreparedStatement stmt, Identity oid, ClassDescriptor cld, boolean callableStmt) throws SQLException
    {
        ValueContainer[] values = null;
        int i = 0;
        int j = 0;

        if (cld == null)
        {
            cld = m_broker.getClassDescriptor(oid.getObjectsRealClass());
        }
        try
        {
            if(callableStmt)
            {
                // First argument is the result set
                m_platform.registerOutResultSet((CallableStatement) stmt, 1);
                j++;
            }

            values = getKeyValues(m_broker, cld, oid);
            for (/*void*/; i < values.length; i++, j++)
            {
                setObjectForStatement(stmt, j + 1, values[i].getValue(), values[i].getJdbcType().getType());
            }
        }
        catch (SQLException e)
        {
            m_log.error("bindSelect failed for: " + oid.toString() + ", PK: " + i + ", value: " + values[i]);
            throw e;
        }
    }
796947
@Override
    public /*final*/ void bind(ResourceAddress address, IoHandler handler, BridgeSessionInitializer<? extends IoFuture> initializer) {

        // bind only address with matching scheme
        URI location = address.getResource();
        String schemeName = location.getScheme();
        if (!canBind(schemeName)) {
            throw new IllegalArgumentException(format("Unexpected scheme \"%s\" for URI: %s", schemeName, location));
        }
        
        if (!started.get()) {
            synchronized (started) {
                if (!started.get()) {
                    init();
                    started.set(true);
                }
            }
        }

        boolean bindAlternate;
        do {
            bindAlternate = address.getOption(BIND_ALTERNATE);
            //
            // add binding, expecting no clashing (according to BINDINGS_COMPARATOR)
            //
            Binding newBinding = new Binding(address, handler, initializer);
            Binding oldBinding = bindings.addBinding(newBinding);

            //System.out.println(getClass().getSimpleName()+"@"+hashCode()+" binding: "+address.getExternalURI()+" -- "+address.getOption(NEXT_PROTOCOL));

            if (oldBinding != null) {
                throw new RuntimeException("Unable to bind address " + address
                        + " because it collides with an already bound address " + oldBinding.bindAddress());
            }

            bindInternal(address, handler, initializer);
            address = address.getOption(ALTERNATE);
            
        } while (address != null && bindAlternate);
    }
737614
public void prepare(PersistentTransaction transaction) throws PersistenceException, SevereMessageStoreException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "prepare", "Transaction="+transaction);

        // Defect 363755
        if (!_available)
        {
            MessageStoreUnavailableException msue = new MessageStoreUnavailableException("Operation not possible as MessageStore is unavailable!");
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "Operation not possible as MessageStore is unavailable!");
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare");
            throw msue;
        }

        //Get the task list from the transaction
        TaskList taskList = (TaskList) transaction.getWorkList();

        PersistentTranId       xid = transaction.getPersistentTranId();
        TransactionState tranState = transaction.getTransactionState();
        int          numberOfTasks = taskList.countLinks();

        boolean requiresSyncPersistence = false;

        // Defect 530772
        boolean requiresSpillPersistence = false;

        // Defect 298584
        // Batching context will only be created if we
        // have synchronous work to do.
        BatchingContext syncBatch = null;
        List             syncList = null;

        if (taskList.hasStoreAlways() || taskList.hasStoreEventually() || taskList.hasStoreMaybe())
        {
            // We have synchronous work to do so
            // we need to build up a list of tasks.
            Iterator iterator = taskList.iterator();
            while (iterator.hasNext())
            {
                Operation          task = (Operation) iterator.next();
                Persistable persistable = task.getPersistable();

                // Defect 451518
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Preparing Task: "+task);

                if (persistable != null && persistable.requiresPersistence())
                {
                    int     storageStrategy = persistable.getStorageStrategy();
                    TupleTypeEnum tupleType = persistable.getTupleType();

                    // Feature SIB0112i.ms.1
                    // We only need to persist our synchronous work at this point. If our
                    // transaction prepares successfully then at commit time we can make
                    // sure our STORE_MAYBE work is persisted.

                    // Defect 530772
                    // Are we a STORE_MAYBE Item? If so then we can be dispatched to the
                    // spill dispatcher. If not then we need to be persisted synchronously.
                    // This is to avoid adding complication to the spill dispatcher as it
                    // does not worry about the order in which things are persisted so an
                    // Item on a stream can be hardened to disk before the stream. This will
                    // not work in the filestore case.
                    if (tupleType != TupleTypeEnum.ITEM_STREAM &&
                        tupleType != TupleTypeEnum.REFERENCE_STREAM &&
                        storageStrategy == AbstractItem.STORE_MAYBE)
                    {
                        if (requiresSpillPersistence == false)
                        {
                            requiresSpillPersistence = true;
                        }
                    }
                    // If not we are synchronous.
                    else
                    {
                        // Defect 298584
                        // Only create our batching context once we know for sure
                        // that we have some synchronous work to do.
                        if (requiresSyncPersistence == false)
                        {
                            syncList  = new ArrayList(numberOfTasks);
                            syncBatch = new BatchingContextImpl(_objectManager, _permanentStore, transaction);
                            transaction.setBatchingContext(syncBatch);
                            requiresSyncPersistence = true;
                        }

                        //Associate the global tran id with the persistable
                        persistable.setPersistentTranId(xid);

                        task.persist(syncBatch, tranState);
                        syncList.add(persistable);
                    }
                }
            }
        }


        // Defect 530772
        // Check the health of the spill dispatcher to minimise the risk
        // of splitting a transaction.
        if (requiresSpillPersistence)
        {
            if (!_spillDispatcher.isHealthy())
            {
                // Defect 345250
                // The dispatcher is not currently accepting new work as it has
                // hit a problem. Details of the problem should have been output
                // to the logs by the dispatcher thread at the point where it
                // occurred.
                PersistenceException pe = new PersistenceException("SPILL_DISPATCHER_CANNOT_ACCEPT_WORK_SIMS1578");
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "The spill dispatcher cannot accept work!", pe);
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare");
                throw pe;
            }
        }

        // Feature SIB0112i.ms.1
        // We only have to do some work in prepare if we have
        // synchronous work to add to the file store.
        if (requiresSyncPersistence)
        {
            try
            {
                // As this is a prepare we use the addIndoubtXid()
                // method to inform the batching context that we only
                // wish to prepare during this executeUpdate() call.
                syncBatch.addIndoubtXID(xid);

                // Submit the batch and trigger the prepare in the
                // object manager.
                syncBatch.executeBatch();

                // If we get to this point then the prepare was successful, so we need to
                // notify the cache layer
                Iterator iterator = syncList.iterator();
                while (iterator.hasNext())
                {
                    Tuple tuple = (Tuple)iterator.next();

                    // Both these methods need to be called to indicate to the cache
                    // that it can soften its in-memory reference to the persistable
                    tuple.persistableOperationBegun();
                    tuple.persistableOperationCompleted();
                }
            }
            catch (PersistenceException pe)
            {
                com.ibm.ws.ffdc.FFDCFilter.processException(pe, "com.ibm.ws.sib.msgstore.persistence.objectManager.PersistableMessageStoreImpl.prepare", "1:1615:1.81.1.6", this);
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "Exception caught preparing transaction in object store!", pe);
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare");
                throw pe;
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare");
    }
435442
public final void persist(BatchingContext batchingContext, TransactionState tranState)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "persist", new Object[] { batchingContext, tranState});

        if ((tranState == TransactionState.STATE_COMMITTED)
            || (tranState == TransactionState.STATE_COMMITTING_1PC)
            || (tranState == TransactionState.STATE_PREPARING)
            || (tranState == TransactionState.STATE_PREPARED))
        {
            batchingContext.insert(getPersistable());
        }
        else if ((tranState == TransactionState.STATE_ROLLEDBACK)
                 || (tranState == TransactionState.STATE_ROLLINGBACK))
        {
            batchingContext.delete(getPersistable());
        }
        else if (tranState == TransactionState.STATE_COMMITTING_2PC)
        {
            //Do nothing.
        }
        else
        {
            throw new IllegalStateException(nls.getFormattedMessage("INVALID_TASK_OPERATION_SIMS1520", new Object[] {tranState}, null));
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "persist");
    }
951774
public EbeanQueryWrapper bind(EbeanQueryWrapper query) {

        Assert.notNull(query, "EbeanQueryWrapper must not be null!");

        int bindableParameterIndex = 0;
        int queryParameterPosition = 1;

        for (Parameter parameter : parameters) {

            if (canBindParameter(parameter)) {

                Object value = accessor.getBindableValue(bindableParameterIndex);
                bind(query, parameter, value, queryParameterPosition++);
                bindableParameterIndex++;
            }
        }

        return query;
    }