Method to send the entity to default email for the given id in asynchronous fashion
@param entity
@param callbackHandler
@param <T>
@throws FMSException
4385
public <T extends IEntity> void sendEmailAsync(T entity, CallbackHandler callbackHandler) throws FMSException {
        sendEmailAsync(entity,null,callbackHandler);
    }
693306
private void pushServerNotRespondingException(EventChannelStruct eventChannelStruct, EventCallBackStruct callbackStruct) {
        try {
            if (eventChannelStruct != null) {
                if (eventChannelStruct.consumer instanceof NotifdEventConsumer) {
                    if (!callbackStruct.filter_ok) {
                        callbackStruct.filter_id = NotifdEventConsumer.getInstance().add_filter_for_channel(
                                eventChannelStruct, callbackStruct.filter_constraint);
                        callbackStruct.filter_ok = true;
                    }
                }
            } else
                return;

            CallBack callback = callbackStruct.callback;
            DevError[] errors = {new DevError()};
            errors[0].severity = ErrSeverity.ERR;
            errors[0].origin = "EventConsumer.KeepAliveThread";
            errors[0].reason = "API_EventTimeout";
            errors[0].desc = "Event channel is not responding any more, maybe the server or event system is down";
            String domain_name = callbackStruct.device.name() + "/" + callbackStruct.attr_name.toLowerCase();
            EventData event_data =
                    new EventData(eventChannelStruct.adm_device_proxy,
                            domain_name, callbackStruct.event_name, EventData.NOTIFD_EVENT,
                            callbackStruct.event_type, null, null, null, null, null, errors);

            event_data.device = callbackStruct.device;
            event_data.name = callbackStruct.device.name();
            event_data.event = callbackStruct.event_name;

            if (callbackStruct.use_ev_queue) {
                EventQueue ev_queue = callbackStruct.device.getEventQueue();
                ev_queue.insert_event(event_data);
            } else
                callback.push_event(event_data);
        } catch (DevFailed e) { /* */ }
    }
271627
public <T> void refresh(T entity) {
        DocumentInfo documentInfo = documentsByEntity.get(entity);
        if (documentInfo == null) {
            throw new IllegalStateException("Cannot refresh a transient instance");
        }

        incrementRequestCount();

        GetDocumentsCommand command = new GetDocumentsCommand(new String[]{documentInfo.getId()}, null, false);
        _requestExecutor.execute(command, sessionInfo);

        refreshInternal(entity, command, documentInfo);
    }
1006777
public <T extends IEntity> void deleteAsync(T entity, CallbackHandler callbackHandler) throws FMSException {

        IntuitMessage intuitMessage = prepareDelete(entity);

        //set callback handler
        intuitMessage.getRequestElements().setCallbackHandler(callbackHandler);

        //execute async interceptors
        executeAsyncInterceptors(intuitMessage);
    }
145710
@Override
	public void update(Object entity) {
		if (entity == null) {
			throw new IllegalArgumentException("'entity' must not be [" + entity + "]");
		}
		
		assertTransactional();
		List<Log> logs = transaction.get().logs();
		
		if (logs.isEmpty()) {
			throw new IllegalStateException("Log ["
					+ Log.Operation.UPDATE
					+ "] is not allowed: previous operation must be ["
					+ Log.Operation.GET + "]");
		}
		
		for (int i = logs.size() - 1; i >= 0; i--) {
			Log log = logs.get(i);
			
			if (keyValue(entity).equals(keyValue(log.entity()))) {
				if (log.operation() == Log.Operation.GET) {
					break;
				} else {
					throw new IllegalStateException("Log [" + log.operation() 
							+ "] -> [" + Log.Operation.UPDATE
							+ "] is not allowed: previous operation must be ["
							+ Log.Operation.GET + "]");
				}
			}
		}
		
		Transaction tx = transaction.get().transaction();
		datastore.put(tx, Translation.toEntities(entity));
		Log log = new Log(logs.size() + 1, Log.Operation.UPDATE, entity);
		log.state(State.UNCOMMITTED);
		logs.add(log);
	}
1095555
public function processEntity(string $entity, callable $callback = null): array
    {
        $this->dbUtils->assertTableExists($entity);

        $this->priKey = $this->dbUtils->getPrimaryKey($entity);
        $this->entityCols = $this->dbUtils->getTableCols($entity);
        $this->entity = $entity;

        $actionsOnThatEntity = $this->whatToDoWithEntity();
        $this->queries = [];

        // Prepare CSV
        if ($this->mode === 'batch') {
            $this->csv = new CSVWriter();
            $this->csv->setCsvControl('|', $this->dbHelper->getEnclosureForCSV());
        }

        // Wrap everything in a transaction
        $conn = $this->dbUtils->getConn();
        try {
            $conn->beginTransaction();

            if ($actionsOnThatEntity & self::UPDATE_TABLE) {
                $this->updateData($callback);
            }

            if ($actionsOnThatEntity & self::INSERT_TABLE) {
                $this->insertData($callback);
            }

            $conn->commit();
        } catch (\Exception $e) {
            $conn->rollBack();
            $conn->close(); // To avoid locks

            throw $e;
        }

        return $this->queries;
    }
3117
private void execCallback(boolean result, EmailBody body, String to, String title,
                              FilePart[] fileParts, Throwable error, JMail mail,
                              JMailCallback callback) {
        if (callback != null) {
            callback.call(result, body, to, title, fileParts, error, mail);
        }
    }
1083464
@SuppressWarnings("unchecked")
    public <T extends IEntity> T donotUpdateAccountOnTxns(T entity) throws FMSException {

        IntuitMessage intuitMessage = preparedonotUpdateAccountOnTxns(entity);

        //execute interceptors
        executeInterceptors(intuitMessage);

        return (T) retrieveEntity(intuitMessage);
    }
333884
public function bindEntity($entity, $fields = null, $validatable = true)
    {
        if ($this->submitted) {
            throw new BadMethodCallException("Entities cannot be assigned after FormHandler::handleRequest has been called");
        }

        $this->entities[] = array('entity' => $entity, 'fields' => $fields, 'validatable' => $validatable);

        if ($entity instanceof EntityInterface) {
            $entityData = $entity->getFormData(array_keys($this->fields), $fields);
        } else {
            $entityData = $this->entityProcessor->getFromEntity($entity, array_keys($this->fields), $fields);
        }

        $entityData = $this->transformToFormData($entityData);

        $this->data = array_replace_recursive($this->data, $entityData);
    }
1230114
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {

        final ModelNode userMap = this.userDomain;

        List<Callback> toRespondTo = new LinkedList<Callback>();

        String userName = null;
        ModelNode user = null;
        ExceptionSupplier<CredentialSource, Exception> userCredentialSourceSupplier = null;

        // A single pass may be sufficient but by using a two pass approach the Callbackhandler will not
        // fail if an unexpected order is encountered.

        // First Pass - is to double check no unsupported callbacks and to retrieve
        // information from the callbacks passing in information.
        for (Callback current : callbacks) {

            if (current instanceof AuthorizeCallback) {
                toRespondTo.add(current);
            } else if (current instanceof NameCallback) {
                NameCallback nameCallback = (NameCallback) current;
                userName = nameCallback.getDefaultName();
                if (userMap.get(USER).hasDefined(userName)) {
                    user = userMap.get(USER, userName);
                }
                userCredentialSourceSupplier = getUserCredentialSourceSupplier(userName);
            } else if (current instanceof PasswordCallback) {
                toRespondTo.add(current);
            } else if (current instanceof RealmCallback) {
                String realm = ((RealmCallback) current).getDefaultText();
                if (this.realm.equals(realm) == false) {
                    // TODO - Check if this needs a real error or of just an unexpected internal error.
                    throw DomainManagementLogger.ROOT_LOGGER.invalidRealm(realm, this.realm);
                }
            } else {
                throw new UnsupportedCallbackException(current);
            }
        }

        // Second Pass - Now iterate the Callback(s) requiring a response.
        for (Callback current : toRespondTo) {
            if (current instanceof AuthorizeCallback) {
                AuthorizeCallback acb = (AuthorizeCallback) current;
                boolean authorized = acb.getAuthenticationID().equals(acb.getAuthorizationID());
                if (authorized == false) {
                    SECURITY_LOGGER.tracef(
                            "Checking 'AuthorizeCallback', authorized=false, authenticationID=%s, authorizationID=%s.",
                            acb.getAuthenticationID(), acb.getAuthorizationID());
                }
                acb.setAuthorized(authorized);
            } else if (current instanceof PasswordCallback) {
                if (user == null) {
                    SECURITY_LOGGER.tracef("User '%s' not found.", userName);
                    throw new UserNotFoundException(userName);
                }
                char[] password =EMPTY_PASSWORD;
                if (user.hasDefined(PASSWORD)) {
                    password = user.require(PASSWORD).asString().toCharArray();
                }
                ((PasswordCallback) current).setPassword(resolvePassword(userCredentialSourceSupplier, password));
            }

        }
    }
482005
void handleRollback(SubscriptionMessage subMessage, 
                      LocalTransaction transaction)
  {
    if (tc.isEntryEnabled())
      SibTr.entry(tc, "handleRollback", new Object[] { subMessage, transaction });

    try
    {
      if (transaction != null)
      {
        try
        {
          transaction.rollback();
        }
        catch (SIException e)
        {
          // If there are any exceptions, then this is bad, log a FFDC
          FFDCFilter.processException(
            e,
            "com.ibm.ws.sib.processor.proxyhandler.NeighbourProxyListener.handleRollback",
            "1:330:1.73",
            this);
          
          SibTr.exception(tc, e);
        }
      }
    
      Transaction msTran = iProxyHandler.getMessageProcessor().resolveAndEnlistMsgStoreTransaction(transaction);
      
      switch (subMessage.getSubscriptionMessageType().toInt())
      {
        case SubscriptionMessageType.CREATE_INT :
    
          // Remove any created Proxy subscriptions
         iProxyHandler.remoteUnsubscribeEvent(iAddTopicSpaces,
                                              iAddTopics, 
                                              subMessage.getBus(), 
                                              msTran,
                                              false);
    
          break;
    
        case SubscriptionMessageType.DELETE_INT :
    
        // Create any removed Proxy subscriptions
        iProxyHandler.remoteSubscribeEvent(iDeleteTopicSpaces,
                                           iDeleteTopics,                                          
                                           subMessage.getBus(),
                                           msTran, 
                                           false);              
    
          break;
    
        case SubscriptionMessageType.RESET_INT :
    
        // Remove any created Proxy subscriptions
        iProxyHandler.remoteUnsubscribeEvent(iAddTopicSpaces,
                                             iAddTopics,                                            
                                             subMessage.getBus(), 
                                             msTran,
                                             false);
    
        // Create any removed Proxy subscriptions
        iProxyHandler.remoteSubscribeEvent(iDeleteTopicSpaces,
                                           iDeleteTopics,                                            
                                           subMessage.getBus(),
                                           msTran, 
                                           false);
                                                         
          break;
    
        default :
          // Log Message
          break;
      }
    }
    catch (SIException e)
    {
      // FFDC
      FFDCFilter.processException(
        e,
        "com.ibm.ws.sib.processor.proxyhandler.NeighbourProxyListener.handleRollback",
        "1:392:1.73",
        this);
    }
    
    if (tc.isEntryEnabled())
      SibTr.exit(tc, "handleRollback");
  }
544017
@SuppressWarnings("unchecked")
    private void addCallBackMethod(EntityMetadata metadata, Class<?> jpaAnnotation, CallbackMethod callbackMethod)
    {
        Map<Class<?>, List<? extends CallbackMethod>> callBackMethodsMap = metadata.getCallbackMethodsMap();
        List<CallbackMethod> list = (List<CallbackMethod>) callBackMethodsMap.get(jpaAnnotation);
        if (null == list)
        {
            list = new ArrayList<CallbackMethod>();
            callBackMethodsMap.put(jpaAnnotation, list);
        }
        list.add(callbackMethod);
    }
573644
synchronized void openConnection(final ModelController controller, final ActiveOperation.CompletedCallback<ModelNode> callback) throws Exception {
        boolean ok = false;
        final Connection connection = connectionManager.connect();
        try {
            channelHandler.executeRequest(new ServerRegisterRequest(), null, callback);
            // HC is the same version, so it will support sending the subject
            channelHandler.getAttachments().attach(TransactionalProtocolClient.SEND_IDENTITY, Boolean.TRUE);
            channelHandler.getAttachments().attach(TransactionalProtocolClient.SEND_IN_VM, Boolean.TRUE);
            channelHandler.addHandlerFactory(new TransactionalProtocolOperationHandler(controller, channelHandler, responseAttachmentSupport));
            ok = true;
        } finally {
            if(!ok) {
                connection.close();
            }
        }
    }
292543
public void execute(List<IntuitMessage> intuitMessages) throws FMSException {
        LOG.debug("Enter HTTPBatchClientConnectionInterceptor - batch...");
        
        RequestElements intuitRequest = getFirst(intuitMessages).getRequestElements();
        
        IntuitRetryPolicyHandler handler = getRetryHandler();
        HttpClientBuilder hcBuilder = HttpClients.custom()
                .setRetryHandler(handler)
                .setDefaultRequestConfig(setTimeout(intuitRequest.getContext()))
                .setDefaultCredentialsProvider(setProxyAuthentication())
                .setSSLSocketFactory(prepareClientSSL());
        
        entitiesManager.reset();
        HttpHost proxy = getProxy();

        if (proxy != null) {
            hcBuilder.setProxy(proxy);
        }

        CloseableHttpClient client = hcBuilder.build();
        HttpRequestBase httpRequest = prepareHttpRequest(intuitRequest);

        //Additional processing for POST requests
        if(httpRequest instanceof HttpPost) {
            for (IntuitMessage intuitMessage : intuitMessages) {
                execute(intuitMessage);
            }
            try {
                ((HttpPost) httpRequest).setEntity(entitiesManager.asSingleEntity());
            } catch (IOException ex) {
                LOG.debug("HTTPBatchClientConnectionInterceptor was unable to convert input into single HTTP entity");
                throw new FMSException("Unable to prepare http entity" + ex.getMessage() + "\n" + ex.getStackTrace());
            } finally {
                entitiesManager.reset();
            }


        }

        //Method to send request
        IntuitMessage intuitMessage = executeHttpRequest(httpRequest,client);

        //TODO review this implementation, since it is using one temporary instance to fill up response elements in original
        for (IntuitMessage originalMessage : intuitMessages) {
            ResponseElements originalResponseElements = originalMessage.getResponseElements();
            ResponseElements receivedResponseElements = intuitMessage.getResponseElements();

            originalResponseElements.setResponseContent(   receivedResponseElements.getResponseContent()   );
            originalResponseElements.setEncodingHeader(    receivedResponseElements.getEncodingHeader()    );
            originalResponseElements.setContentTypeHeader( receivedResponseElements.getContentTypeHeader() );
            originalResponseElements.setStatusLine(        receivedResponseElements.getStatusLine()        );
            originalResponseElements.setStatusCode(        receivedResponseElements.getStatusCode()        );

        }
        LOG.debug("Exit HTTPBatchClientConnectionInterceptor.");

    }
266096
public function populate($id, $recipient = null, $backupCodeIdentifier = null, $totpIdentifier = null)
    {
        if (empty($id)) {
            throw new EntityException('No messages id supplied', EntityException::NO_MESSAGE_ID_SUPPLIED);
        }
        if ($recipient === null && $backupCodeIdentifier === null && $totpIdentifier === null) {
            throw new EntityException('No recipient, backup code identifier or totp identifier supplied', EntityException::INVALID_FIELDS);
        }

        $params = [];
        if ($recipient !== null) {
            $params['recipient'] = $recipient;
        }
        if ($backupCodeIdentifier !== null) {
            $params['backupCodeIdentifier'] = $backupCodeIdentifier;
        }
        if ($totpIdentifier !== null) {
            $params['totpIdentifier'] = $totpIdentifier;
        }

        $this->sendApiCall(self::ACTION_RETRIEVE, $this->getCreateUrl() . '/' . urlencode($id) . '?' . http_build_query($params));
    }
656922
public void executeBatch(BatchOperation batchOperation) throws FMSException {

        IntuitMessage intuitMessage = prepareBatch(batchOperation);

        //execute interceptors
        executeInterceptors(intuitMessage);

        IntuitResponse intuitResponse = (IntuitResponse) intuitMessage.getResponseElements().getResponse();
        if (intuitResponse != null) {
            List<BatchItemResponse> batchItemResponses = intuitResponse.getBatchItemResponse();
            if (batchItemResponses != null && !batchItemResponses.isEmpty()) {
                int count = 0;
                Iterator<BatchItemResponse> itr = batchItemResponses.iterator();
                while (itr.hasNext()) {
                    BatchItemResponse batchItemResponse = itr.next();
                    String bId = batchItemResponse.getBId();
                    if (!StringUtils.hasText(bId)) {
                        bId = batchOperation.getBatchItemRequests().get(count).getBId();
                    }
                    if (batchItemResponse.getFault() != null) {
                        // segregate fault batch items
                        batchOperation.getFaultResult().put(bId, batchItemResponse.getFault());
                    } else if (batchItemResponse.getReport() != null) {
                        // segregate report batch items
                        batchOperation.getReportResult().put(bId, batchItemResponse.getReport());
                    } else if (batchItemResponse.getIntuitObject() != null) {
                        // segregate entity batch items
                        batchOperation.getEntityResult().put(bId, (IEntity) batchItemResponse.getIntuitObject().getValue());
                    } else if (batchItemResponse.getQueryResponse() != null) {
                        // segregate query batch items
                        QueryResult queryResult = getQueryResult(batchItemResponse.getQueryResponse());
                        batchOperation.getQueryResult().put(bId, queryResult);
                    } else if (batchItemResponse.getCDCResponse() != null) {
                        // segregate cdc query batch items
                        CDCQueryResult cdcQueryResult = getCDCQueryResult(batchItemResponse.getCDCResponse());
                        batchOperation.getCDCQueryResult().put(bId, cdcQueryResult);
                    } else {
                        LOG.warn("BatchItemResponse is not Fault, Entity, Query and Report.");
                    }
                    count++;
                }
            }
        }
    }
1132625
private <T extends IEntity> IntuitMessage prepareUpload(T entity, InputStream docContent, String boundaryId) throws FMSException {
        IntuitMessage intuitMessage = new IntuitMessage();
        RequestElements requestElements = intuitMessage.getRequestElements();

        //set the request parameters
        Map<String, String> requestParameters = requestElements.getRequestParameters();
        requestParameters.put(RequestElements.REQ_PARAM_METHOD_TYPE, MethodType.POST.toString());

        UploadRequestElements uploadRequestElements = requestElements.getUploadRequestElements();
        uploadRequestElements.setDocContent(docContent);
        uploadRequestElements.setBoundaryId( utilizeIf(boundaryId) );
        uploadRequestElements.setElementsId(generateId().substring(0, 5));

        requestElements.setAction(OperationType.UPLOAD.toString());
        requestElements.setContext(context);
        requestElements.setEntity(entity);
        requestElements.setObjectToSerialize(getSerializableObject(entity));

        return intuitMessage;
    }