Note from Thaniga on 11/5.  DME2Client is not expected to be reused... need a fresh one
on each transaction, which is expected to cover the Async aspects.

@return
@throws APIException
@throws DME2Exception
5116
protected EClient<DME2Client> client() throws CadiException {
		try {
			DEClient dc = new DEClient(manager,getSecuritySetter(),uri,readTimeout);
			dc.setProxy(isProxy);
			return dc;
		} catch (DME2Exception e) {
			throw new CadiException(e);
		}
	}
1308428
@Override
    public JmsConnectionFactory createConnectionFactory() throws JMSException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "createConnectionFactory");
        JmsConnectionFactory jmscf = null;

        // get a jca managed connection factory, which is used to construct
        // the jms connection factory.
        JmsJcaFactory jcaFact = JmsJcaFactory.getInstance();

        if (jcaFact == null) {
            // This indicates that the jmsra.impl class could not be loaded by their
            // static initializer. Nothing we can do about that...

            // d238447 FFDC review. FFDC has already been generated by JmsJcaFactory, so
            //   don't generate one here.
            throw (JMSException) JmsErrorUtils.newThrowable(
                                                            JMSException.class,
                                                            "UNABLE_TO_CREATE_FACTORY_CWSIA0008",
                                                            new Object[] { "JmsJcaFactoryImpl", "sib.api.jmsraOutboundImpl.jar" },
                                                            tc
                            );
        }

        JmsJcaManagedConnectionFactory jcamcf = jcaFact.createManagedConnectionFactory();

        // invoke the construction of a jms connection factory - the jca managed
        // connection factory will call back into the jms api code by getting a
        // JmsRAFactoryFactory, and calling a create jms connection factory
        // method on it with jca connection factory and jca managed connection
        // factory objects as parameters (the jms cf will keep references to the
        // jca cf and jca mcf).
        try {
            jmscf = (JmsConnectionFactory) jcamcf.createConnectionFactory();
        } catch (ResourceException re) {
            // No FFDC code needed
            // d222942 review - no documentation for when a RE will be thrown, so
            // default exception ok. (A quick look at the RA suggests the exception isn't
            // ever thrown).
            // d238447 FFDC review. From the above comment, generating an FFDC seems ok.
            throw (JMSException) JmsErrorUtils.newThrowable(
                                                            JMSException.class,
                                                            "EXCEPTION_RECEIVED_CWSIA0007",
                                                            new Object[] { re, "JmsFactoryFactoryImpl.createConnectionFactory (#2)" },
                                                            re,
                                                            "JmsFactoryFactoryImpl.createConnectionFactory#2",
                                                            this,
                                                            tc
                            );
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "createConnectionFactory", jmscf);
        return jmscf;
    }
919811
Future<HeaderCacheElement> asyncRefresh() {
    LOG.trace("asyncRefresh");

    synchronized (lock) {
      try {
        if (futureToken != null) {
          return futureToken;
        }
        if (headerCache.getCacheState() == CacheState.Good) {
          return Futures.immediateFuture(headerCache);
        }

        Future<HeaderCacheElement> future = executor.submit(new Callable<HeaderCacheElement>() {
          @Override
          public HeaderCacheElement call() {
            return updateToken();
          }
        });

        if (!future.isDone()) {
          this.futureToken = future;
        }
        return future;
      } catch (RuntimeException e) {
        futureToken = null;
        LOG.warn("Got an unexpected exception while trying to refresh google credentials.", e);
        return Futures.immediateFuture(new HeaderCacheElement(
          Status.UNAUTHENTICATED
              .withDescription("Unexpected error trying to authenticate")
              .withCause(e)));
      }
    }
  }
156959
private function singleUseState()
    {
        if ($this->type === self::TYPE_SINGLE_USE) {
            if ($this->state === self::STATE_SINGLE_USE_USED) {
                throw new \BadMethodCallException('This single-use transaction has already been used.');
            }

            $this->state = self::STATE_SINGLE_USE_USED;

            return true;
        }

        return false;
    }
4345
public function setApiClient($api_client)
    {
        if (! class_exists($api_client) || ! method_exists($api_client, 'call')) {
            throw new DataSift_Exception_InvalidData('Class "' . $api_client . '" does not exist');
        }

        $this->_api_client = $api_client;
    }
920641
public TrmClientAttachRequest2 createNewTrmClientAttachRequest2() throws MessageCreateFailedException {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createNewTrmClientAttachRequest2");
    TrmClientAttachRequest2 msg = null;
    try {
      msg = new TrmClientAttachRequest2Impl();
    }
    catch (MessageDecodeFailedException e) {
      /* No need to FFDC this as JsMsgObject will already have done so */
      // No FFDC code needed
      throw new MessageCreateFailedException(e);
    }
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "createNewTrmClientAttachRequest2");
    return msg;
  }
664731
@Override
    public void messagingEngineReloaded(JsMessagingEngine engine)
    {
        final String methodName = "messagingEngineReloaded";
        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.entry(this, TRACE, methodName, engine);
        }

        // We are now catching problems when ME's are not started and not throwing an error.
        // As such this check is not needed and is causing problems. The problem is that
        // we could have a cluster of MEs with only one ME running. If a queue is deleted
        // then recreated only the MDB that is sitting alongside the ME will reconnect, 
        // the other MEs will wait for the local ME to start to try to reconnect but this
        // may never happen so we need to try to reconnect at this point.
        try
        {
            clearTimer();
            timerLoop();
        } catch (final ResourceException exception)
        {
            // No FFDC code needed
            if (TraceComponent.isAnyTracingEnabled() && TRACE.isEventEnabled())
            {
                SibTr.exception(this, TRACE, exception);
            }

            SibTr.error(TRACE, "RELOAD_FAILED_CWSIV0773", new Object[] {
                                                                        exception, engine.getName(), engine.getBusName(), this });
        }

        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled())
        {
            SibTr.exit(this, TRACE, methodName);
        }
    }
1269346
@SuppressWarnings("unchecked")
    public T get() {
        if (HystrixRequestContext.getContextForCurrentThread() == null) {
            throw new IllegalStateException(HystrixRequestContext.class.getSimpleName() + ".initializeContext() must be called at the beginning of each request before RequestVariable functionality can be used.");
        }
        ConcurrentHashMap<HystrixRequestVariableDefault<?>, LazyInitializer<?>> variableMap = HystrixRequestContext.getContextForCurrentThread().state;

        // short-circuit the synchronized path below if we already have the value in the ConcurrentHashMap
        LazyInitializer<?> v = variableMap.get(this);
        if (v != null) {
            return (T) v.get();
        }

        /*
         * Optimistically create a LazyInitializer to put into the ConcurrentHashMap.
         * 
         * The LazyInitializer will not invoke initialValue() unless the get() method is invoked
         * so we can optimistically instantiate LazyInitializer and then discard for garbage collection
         * if the putIfAbsent fails.
         * 
         * Whichever instance of LazyInitializer succeeds will then have get() invoked which will call
         * the initialValue() method once-and-only-once.
         */
        LazyInitializer<T> l = new LazyInitializer<T>(this);
        LazyInitializer<?> existing = variableMap.putIfAbsent(this, l);
        if (existing == null) {
            /*
             * We won the thread-race so can use 'l' that we just created.
             */
            return l.get();
        } else {
            /*
             * We lost the thread-race so let 'l' be garbage collected and instead return 'existing'
             */
            return (T) existing.get();
        }
    }
640540
private synchronized int getNewClientID() {
        if ((clientIDGenerator + 1) >= Integer.MAX_VALUE) {
            //if we can't find a reusable ID within the first 100 slots, then fail.
            //Revisit: I don't want to loop through all 2+ billion entries to find that they are all taken, as this
            //could be seem as a DoS, but maybe some better heuristics for finding an empty ID? not sure if we will ever be
            //in this situation...
            final int limit = Integer.MIN_VALUE + 100;
            for (int i = Integer.MIN_VALUE; i < limit; i++) {
                if (inboxes.get(i) == null) {
                    return i;
                }
            }

            //Emit the warning
            Tr.warning(tc, "jmx.connector.server.rest.notification.limit.warning");

            throw ErrorHelper.createRESTHandlerJsonException(new RuntimeException("The server has reached its limit of new client notifications."),
                                                             JSONConverter.getConverter(),
                                                             APIConstants.STATUS_SERVICE_UNAVAILABLE);
        }

        return clientIDGenerator++;
    }
451015
public void create() throws APIException {
        CreateDirectoryRequest reqObj = new CreateDirectoryRequest(this.getName(), null);
        Gson gson = new Gson();
        JsonElement inputJson = gson.toJsonTree(reqObj);

        String url = this.getParent().getUrl();
        HttpResponse response = this.client.post(url, new StringEntity(inputJson.toString(), ContentType.APPLICATION_JSON));
        HttpClientHelpers.throwIfNotOk(response);
    }
1365509
@Override
    protected List populateEntities(EntityMetadata m, Client client)
    {
        ClientMetadata clientMetadata = ((ClientBase) client).getClientMetadata();
        this.useLuceneOrES = !MetadataUtils.useSecondryIndex(clientMetadata);
        if (useLuceneOrES)
        {
            return populateUsingLucene(m, client, null, kunderaQuery.getResult());
        }
        else
        {
            CouchDBQueryInterpreter interpreter = onTranslation(getKunderaQuery().getFilterClauseQueue(), m);
            return ((CouchDBClient) client).createAndExecuteQuery(interpreter);
        }
    }
1225781
public ApiKey regenerateApiKey(final ApiKey apiKey) {
        pm.currentTransaction().begin();
        apiKey.setKey(ApiKeyGenerator.generate());
        pm.currentTransaction().commit();
        return pm.getObjectById(ApiKey.class, apiKey.getId());
    }
656300
protected Object createMyInstance() throws IOException {
        // would like to uninherit from AbstractFactoryBean (but it's final!)
        if (!isSingleton()) {
            throw new RuntimeException("ReloadablePropertiesFactoryBean only works as singleton");
        }

        // set listener
        reloadableProperties = new ReloadablePropertiesImpl();
        if (preListeners != null) {
            reloadableProperties.setListeners(preListeners);
        }

        // reload
        reload(true);

        // add for monitor
        ReloadConfigurationMonitor.addReconfigurableBean((ReconfigurableBean) reloadableProperties);

        return reloadableProperties;
    }
383415
@Override
    public Client getClientInstance()
    {
        // if threadsafe recycle the same single instance; if not create a new
        // instance

        if (isThreadSafe())
        {
            logger.info("Returning threadsafe used client instance for persistence unit : " + persistenceUnit);
            if (client == null)
            {
                client = instantiateClient(persistenceUnit);
            }
        }
        else
        {
            logger.debug("Returning fresh client instance for persistence unit : " + persistenceUnit);
            // no need to hold a client reference.
            return instantiateClient(persistenceUnit);
        }

        return client;
    }
229049
protected void refresh()
    {
        if (log.isDebugEnabled())
                log.debug("Refresh this transaction for reuse: " + this);
        try
        {
            // we reuse ObjectEnvelopeTable instance
            objectEnvelopeTable.refresh();
        }
        catch (Exception e)
        {
            if (log.isDebugEnabled())
            {
                log.debug("error closing object envelope table : " + e.getMessage());
                e.printStackTrace();
            }
        }
        cleanupBroker();
        // clear the temporary used named roots map
        // we should do that, because same tx instance
        // could be used several times
        broker = null;
        clearRegistrationList();
        unmaterializedLocks.clear();
        txStatus = Status.STATUS_NO_TRANSACTION;
    }
1322010
@Override
    public T get() throws InterruptedException, ExecutionException {
        // when get returns without an exception the synchronisation is complete
        // and else the exception will be thrown
        if (isInitialized()) {
            synchronisationFuture.get();
        }
        return internalFuture.get();
    }
437073
@Override
	// TODO This is executed for each client connected. Should we have only one client connected?
	// TODO Call queryPurchases() at least twice in your code:
	// - Every time your app launches so that you can restore any purchases that a user has made since the app last stopped.
	// - In your onResume() method because a user can make a purchase when your app is in the background (for example, redeeming a promo code in Play Store app).
	// Calling queryPurchases() on startup and resume guarantees that your app finds out about all purchases and redemptions
	// the user may have made while the app wasn't running. Furthermore, if a user makes a purchase while the app is running
	// and your app misses it for any reason, your app still finds out about the purchase the next time the activity resumes and calls queryPurchases().
	// The simplest approach is to call queryPurchases() in your activity's onResume() method, since that callback fires
	// when the activity is created, as well as when the activity is unpaused.
	public void onPurchasesUpdated(@BillingClient.BillingResponse int resultCode, @Nullable List<Purchase> purchases) {
		InAppBillingErrorCode inAppBillingErrorCode = InAppBillingErrorCode.findByErrorResponseCode(resultCode);
		if (inAppBillingErrorCode == null) {
			if (purchases != null) {
				for (Purchase purchase : purchases) {
					String productId = purchase.getSku();
					Product product = inventory.getProduct(productId);
					try {
						if (product != null) {
							product.setPurchase(signatureBase64, purchase.getOriginalJson(), purchase.getSignature(), InAppBillingAppModule.get().getDeveloperPayloadVerificationStrategy());
							InAppBillingAppModule.get().getInAppBillingContext().addPurchasedProductType(product.getProductType());
							
							// TODO Add logic here to see if we are replacing the same purchase. If yes, dont track
							InAppBillingAppModule.get().getModuleAnalyticsSender().trackInAppBillingPurchase(product);
							
							if (listener != null) {
								listener.onPurchaseFinished(product);
							}
							if (product.isWaitingToConsume()) {
								consume(product);
							} else if (listener != null) {
								listener.onProvideProduct(product);
							}
						} else {
							AbstractApplication.get().getExceptionHandler().logWarningException(
									"The purchased product [" + productId + "] is not supported by the app, so it is ignored");
						}
					} catch (ErrorCodeException e) {
						AbstractApplication.get().getExceptionHandler().logHandledException(e);
						if (listener != null) {
							listener.onPurchaseFailed(e);
						}
					} catch (JSONException e) {
						AbstractApplication.get().getExceptionHandler().logHandledException(e);
						if (listener != null) {
							listener.onPurchaseFailed(InAppBillingErrorCode.BAD_PURCHASE_DATA.newErrorCodeException(e));
						}
					}
				}
			}
		} else if (inAppBillingErrorCode.equals(InAppBillingErrorCode.USER_CANCELED)) {
			LOGGER.warn("User cancelled the purchase flow.");
			if (listener != null) {
				listener.onPurchaseFailed(InAppBillingErrorCode.USER_CANCELED.newErrorCodeException("User cancelled the purchase flow."));
			}
		} else {
			AbstractApplication.get().getExceptionHandler().logHandledException(inAppBillingErrorCode.newErrorCodeException());
			if (listener != null) {
				listener.onPurchaseFailed(inAppBillingErrorCode.newErrorCodeException("Purchase failed."));
			}
			
		}
	}