/*
Map<String,Object> executeEvent(Transaction trans, Map<String,Object> args) throws PersistenceException {
return executeEvent(trans, args, null);
}
160020
Map<String,Object> executeEvent(Transaction trans, Map<String,Object> args, StringBuilder statementHolder) throws PersistenceException {
        logger.debug("enter - execute(Transaction, Map)");
        state = "EXECUTING";
        try {
            if( logger.isDebugEnabled() ) {
                logger.debug("Getting connection from transaction: " + trans.getTransactionId());
            }
            connection = trans.getConnection();
            data = args;
            try {
                String sql = loadStatement(connection, args);
                Map<String,Object> res;
                
                if( logger.isDebugEnabled() ) {
                    logger.debug("Preparing: " + sql);
                }
                if( statementHolder != null ) {
                    statementHolder.append(sql);
                }
                statement = connection.prepareStatement(sql);
                try {
                    logger.debug("And executing the prepared statement.");
                
                    res = run(trans, args);
                }
                finally {
                    try { statement.close(); statement = null; }
                    catch( Throwable ignore ) { }
                }
                if( logger.isDebugEnabled() ) {
                    logger.debug("RESULTS: " + res);
                }
                if( res ==  null ) {
                    return null;
                }
                else if( res instanceof HashMap ) {
                    return (HashMap<String,Object>)res;
                }
                else {
                    HashMap<String,Object> tmp = new HashMap<String,Object>();
                    
                    tmp.putAll(res);
                    return tmp;
                }
            }
            catch( SQLException e ) {
                logger.debug("Error executing event: " + e.getMessage(), e);
                throw new PersistenceException(e.getMessage());
            }
        }
        finally {
            state = "IDLE";
            logger.debug("exit - execute(Transaction, Map)");
        }
    }
1089084
public void generateMethodExecuteTransaction(String daoFactory) {
		// create interface
		String transationExecutorName = "Transaction";
		// @formatter:off
		ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(className(AbstractExecutable.class),
				className(daoFactory));
		classBuilder.addType(TypeSpec.interfaceBuilder(transationExecutorName).addModifiers(Modifier.PUBLIC)
				.addSuperinterface(parameterizedTypeName).addJavadoc("Rapresents transational operation.\n")
				.addMethod(MethodSpec.methodBuilder("onExecute").addParameter(className(daoFactory), "daoFactory")
						.addJavadoc(
								"Execute transation. Method need to return {@link TransactionResult#COMMIT} to commit results\nor {@link TransactionResult#ROLLBACK} to rollback.")
						.addJavadoc("\nIf exception is thrown, a rollback will be done.")
						.addJavadoc("\n\n@param daoFactory\n@return\n@throws Throwable\n")
						.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT).returns(TransactionResult.class).build())
				.build());
		// @formatter:on

		{
			MethodSpec.Builder executeMethod = MethodSpec.methodBuilder("execute").addModifiers(Modifier.PUBLIC)
					.returns(Boolean.TYPE).addParameter(className(transationExecutorName), "transaction");
			// generate javadoc
			executeMethod.addJavadoc(
					"<p>Executes a transaction. This method <strong>is thread safe</strong> to avoid concurrent problems. The "
							+ "drawback is only one transaction at time can be executed. The database will be open in write mode. This method uses default error listener to intercept errors.</p>\n");
			executeMethod.addJavadoc("\n");
			executeMethod.addJavadoc("@param transaction\n\ttransaction to execute\n");
			executeMethod.addJavadoc("@return <code>true</code> if transaction successful finished\n");

			executeMethod.addStatement("return execute(transaction, onErrorListener)");

			classBuilder.addMethod(executeMethod.build());
		}

		{
			MethodSpec.Builder executeMethod = MethodSpec.methodBuilder("execute").addModifiers(Modifier.PUBLIC)
					.addParameter(className(transationExecutorName), "transaction").returns(Boolean.TYPE)
					.addParameter(className(OnErrorListener.class), "onErrorListener");

			executeMethod.addStatement("boolean needToOpened=!this.isOpenInWriteMode()");
			executeMethod.addStatement("boolean success=false");
			executeMethod.addCode("@SuppressWarnings(\"resource\")\n");
			executeMethod.addStatement("$T connection=needToOpened ? openWritableDatabase() : database()",
					SQLiteDatabase.class);

			// support for live data
			executeMethod.addStatement("$L currentDaoFactory=_daoFactorySingleThread.bindToThread()",
					DATA_SOURCE_SINGLE_THREAD_NAME);
			executeMethod.addStatement("currentDaoFactory.onSessionOpened()");

			executeMethod.beginControlFlow("try");
			executeMethod.addCode("connection.beginTransaction();\n");

			executeMethod.beginControlFlow(
					"if (transaction!=null && $T.$L == transaction.onExecute(currentDaoFactory))",
					TransactionResult.class, TransactionResult.COMMIT);
			executeMethod.addStatement("connection.setTransactionSuccessful()");

			// support for live data
			executeMethod.addStatement("success=true");

			executeMethod.endControlFlow();
			executeMethod.nextControlFlow("catch($T e)", Throwable.class);

			executeMethod.addStatement("$T.error(e.getMessage())", Logger.class);
			executeMethod.addStatement("e.printStackTrace()");
			executeMethod.addStatement("if (onErrorListener!=null) onErrorListener.onError(e)");

			executeMethod.nextControlFlow("finally");
			executeMethod.beginControlFlow("try");
			executeMethod.addStatement("connection.endTransaction()");
			executeMethod.nextControlFlow("catch ($T e)", Throwable.class);
			executeMethod.addStatement("$T.warn(\"error closing transaction %s\", e.getMessage())", Logger.class);
			executeMethod.endControlFlow();
			executeMethod.addCode("if (needToOpened) { close(); }\n");
			// support for live data
			executeMethod.addCode(
					"if (success) { currentDaoFactory.onSessionClosed(); } else { currentDaoFactory.onSessionClear(); }\n");
			executeMethod.endControlFlow();
			executeMethod.addStatement("return success");

			// generate javadoc
			executeMethod.addJavadoc(
					"<p>Executes a transaction. This method <strong>is thread safe</strong> to avoid concurrent problems. The "
							+ "drawback is only one transaction at time can be executed. The database will be open in write mode.</p>\n");
			executeMethod.addJavadoc("\n");
			executeMethod.addJavadoc("@param transaction\n\ttransaction to execute\n");
			executeMethod.addJavadoc("@param onErrorListener\n\terror listener\n");
			executeMethod.addJavadoc("@return <code>true</code> if transaction successful finished\n");

			classBuilder.addMethod(executeMethod.build());
		}

	}
914145
private LoggingEvent convertToEvent(Map fieldMap, String[] exception) {
    if (fieldMap == null) {
      return null;
    }

    //a logger must exist at a minimum for the event to be processed
    if (!fieldMap.containsKey(LOGGER)) {
      fieldMap.put(LOGGER, "Unknown");
    }
    if (exception == null) {
      exception = emptyException;
    }

    Logger logger = null;
    long timeStamp = 0L;
    String level = null;
    String threadName = null;
    Object message = null;
    String ndc = null;
    String className = null;
    String methodName = null;
    String eventFileName = null;
    String lineNumber = null;
    Hashtable properties = new Hashtable();

    logger = Logger.getLogger((String) fieldMap.remove(LOGGER));

    if ((dateFormat != null) && fieldMap.containsKey(TIMESTAMP)) {
      try {
        timeStamp = dateFormat.parse((String) fieldMap.remove(TIMESTAMP))
            .getTime();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    //use current time if timestamp not parseable
    if (timeStamp == 0L) {
      timeStamp = System.currentTimeMillis();
    }

    message = fieldMap.remove(MESSAGE);
    if (message == null) {
      message = "";
    }

    level = (String) fieldMap.remove(LEVEL);
    Level levelImpl;
    if (level == null) {
        levelImpl = Level.DEBUG;
    } else {
        //first try to resolve against custom level definition map, then fall back to regular levels
        levelImpl = (Level) customLevelDefinitionMap.get(level);
        if (levelImpl == null) {
            levelImpl = Level.toLevel(level.trim());
            if (!level.equals(levelImpl.toString())) {
                //check custom level map
                if (levelImpl == null) {
                    levelImpl = Level.DEBUG;
                    getLogger().debug("found unexpected level: " + level + ", logger: " + logger.getName() + ", msg: " + message);
                    //make sure the text that couldn't match a level is added to the message
                    message = level + " " + message;
                }
            }
        }
    }

    threadName = (String) fieldMap.remove(THREAD);

    ndc = (String) fieldMap.remove(NDC);

    className = (String) fieldMap.remove(CLASS);

    methodName = (String) fieldMap.remove(METHOD);

    eventFileName = (String) fieldMap.remove(FILE);

    lineNumber = (String) fieldMap.remove(LINE);

    properties.put(Constants.HOSTNAME_KEY, host);
    properties.put(Constants.APPLICATION_KEY, path);
    properties.put(Constants.RECEIVER_NAME_KEY, getName());

    //all remaining entries in fieldmap are properties
    properties.putAll(fieldMap);

    LocationInfo info = null;

    if ((eventFileName != null) || (className != null) || (methodName != null)
        || (lineNumber != null)) {
      info = new LocationInfo(eventFileName, className, methodName, lineNumber);
    } else {
      info = LocationInfo.NA_LOCATION_INFO;
    }

    LoggingEvent event = new LoggingEvent(null,
            logger, timeStamp, levelImpl, message,
            threadName,
            new ThrowableInformation(exception),
            ndc,
            info,
            properties);

    return event;
  }
567091
@Transactional(propagation = Propagation.MANDATORY)
  public PreparedStatement executeSqlFromScript(String script)
  {
    return executeSqlFromScript(script, null);
  }
515245
public void processTransactionTerminated(final TransactionTerminatedEvent transactionTerminatedEvent) {
		Transaction eventTransaction = null;
		if(transactionTerminatedEvent.isServerTransaction()) {
			eventTransaction = transactionTerminatedEvent.getServerTransaction();
		} else {
			eventTransaction = transactionTerminatedEvent.getClientTransaction();
		}
		final Transaction transaction = eventTransaction;
		if(logger.isDebugEnabled()) {
			logger.info("transaction " + transaction + " terminated => " + transaction.getRequest());
		}

		final TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData();
		final String branchId = transaction.getBranchId();
		if(tad != null && tad.getSipServletMessage() != null) {
			// https://github.com/RestComm/sip-servlets/issues/107 guard against NPEon concurrent cleanup
			final SipServletMessageImpl sipServletMessageImpl = tad.getSipServletMessage();
			final MobicentsSipSessionKey sipSessionKey = sipServletMessageImpl.getSipSessionKey();
			final MobicentsSipSession sipSession = sipServletMessageImpl.getSipSession();
			getAsynchronousExecutor().execute(new Runnable() {
				public void run() {
					try {
						if(logger.isDebugEnabled()) {
							logger.info("transaction " + transaction + " terminated => " + sipServletMessageImpl);
						}

						MobicentsB2BUAHelper b2buaHelperImpl = null;
						if(sipSession != null) {
							b2buaHelperImpl = sipSession.getB2buaHelper();
						}
						if(sipSessionKey == null) {
							if(logger.isDebugEnabled()) {
								logger.debug("no sip session were returned for this key " + sipServletMessageImpl.getSipSessionKey() + " and message " + sipServletMessageImpl);
							}
						}
						ProxyBranchImpl proxyBranch = tad.getProxyBranch();
						if(proxyBranch != null) {
							proxyBranch.removeTransaction(branchId);
						}

						// Issue 1333 : B2buaHelper.getPendingMessages(linkedSession, UAMode.UAC) returns empty list
						// don't remove the transaction on terminated state for INVITE Tx because it won't be possible
						// to create the ACK on second leg for B2BUA apps
						if(sipSession != null) {
							boolean removeTx = true;
							if(b2buaHelperImpl != null && (transaction == null || transaction instanceof ClientTransaction)
									&& Request.INVITE.equals(sipServletMessageImpl.getMethod())) {
								removeTx = false;
							}
							SipContext sipContext = findSipApplication(sipSessionKey.getApplicationName());
							//the context can be null if the server is being shutdown
							if(sipContext != null) {
								MobicentsSipApplicationSession sipApplicationSession = sipSession.getSipApplicationSession();
								try {
									sipContext.enterSipApp(sipApplicationSession, sipSession, false, true);

									if(removeTx) {
										if(b2buaHelperImpl != null && tad.getSipServletMessage() instanceof SipServletRequestImpl) {
											b2buaHelperImpl.unlinkRequestInternal((SipServletRequestImpl)tad.getSipServletMessage(), false);
										}
										sipSession.removeOngoingTransaction(transaction);
										// Issue 1468 : to handle forking, we shouldn't cleanup the app data since it is needed for the forked responses
										boolean nullifyAppData = true;
										if(((SipStackImpl)((SipProvider)transactionTerminatedEvent.getSource()).getSipStack()).getMaxForkTime() > 0 && Request.INVITE.equals(sipServletMessageImpl.getMethod())) {
											nullifyAppData = false;
										}
										if(nullifyAppData) {
											tad.cleanUp();
											if(b2buaHelperImpl == null && tad.getSipServletMessage() instanceof SipServletRequestImpl) {
												sipSession.cleanDialogInformation(false);
											}
											transaction.setApplicationData(null);
										}
									} else {
										if(logger.isDebugEnabled()) {
											logger.debug("Transaction " + transaction + " not removed from session " + sipSessionKey + " because the B2BUA might still need it to create the ACK");
										}
									}
								} finally {
									sipContext.exitSipApp(sipApplicationSession, sipSession);
								}
							}

							// If it is a client transaction, do not kill the proxy session http://code.google.com/p/mobicents/issues/detail?id=1024
							tryToInvalidateSession(sipSessionKey, transactionTerminatedEvent.isServerTransaction());

						}
					} catch (Exception e) {
						logger.error("Problem handling transaction termination", e);
					}
				}
			});
		} else {
			if(logger.isDebugEnabled()) {
				logger.debug("TransactionApplicationData not available on the following request " + transaction.getRequest());
			}
			if(tad != null) {
				tad.cleanUp();
			}
			transaction.setApplicationData(null);
		}

	}
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");
    }
1188553
@SuppressWarnings({"WMI", "unchecked"})
    public DBObject callLifecycleMethods(final Class<? extends Annotation> event, final Object entity, final DBObject dbObj,
                                         final Mapper mapper) {
        final List<ClassMethodPair> methodPairs = getLifecycleMethods((Class<Annotation>) event);
        DBObject retDbObj = dbObj;
        try {
            Object tempObj;
            if (methodPairs != null) {
                final HashMap<Class<?>, Object> toCall = new HashMap<Class<?>, Object>((int) (methodPairs.size() * 1.3));
                for (final ClassMethodPair cm : methodPairs) {
                    toCall.put(cm.clazz, null);
                }
                for (final Class<?> c : toCall.keySet()) {
                    if (c != null) {
                        toCall.put(c, getOrCreateInstance(c, mapper));
                    }
                }

                for (final ClassMethodPair cm : methodPairs) {
                    final Method method = cm.method;
                    final Object inst = toCall.get(cm.clazz);
                    method.setAccessible(true);

                    if (LOG.isDebugEnabled()) {
                        LOG.debug(format("Calling lifecycle method(@%s %s) on %s", event.getSimpleName(), method, inst));
                    }

                    if (inst == null) {
                        if (method.getParameterTypes().length == 0) {
                            tempObj = method.invoke(entity);
                        } else {
                            tempObj = method.invoke(entity, retDbObj);
                        }
                    } else if (method.getParameterTypes().length == 0) {
                        tempObj = method.invoke(inst);
                    } else if (method.getParameterTypes().length == 1) {
                        tempObj = method.invoke(inst, entity);
                    } else {
                        tempObj = method.invoke(inst, entity, retDbObj);
                    }

                    if (tempObj != null) {
                        retDbObj = (DBObject) tempObj;
                    }
                }
            }

            callGlobalInterceptors(event, entity, dbObj, mapper);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }

        return retDbObj;
    }
157198
@Override
    public void onManagerEvent(ManagerEvent event)
    {

        // if this turns out to be slow, we could consider caching the reflection lookup

        try
        {

            Method method = this.getClass().getDeclaredMethod("handleEvent", new Class[]{event.getClass()});
            if (method != null)
            {
                method.invoke(this, event);
                return;
            }
        }
        catch (Exception e)
        {
            logger.error(e, e);
        }

        logger.error("The event " + event.getClass()
                + " couldn't be mapped to a method in AbstractManagerEventListener.java, someone should add it!");

    }
518821
public int executeUpdateSQL(
        String sqlStatement,
        ClassDescriptor cld,
        ValueContainer[] values1,
        ValueContainer[] values2)
        throws PersistenceBrokerException
    {
        if (logger.isDebugEnabled())
            logger.debug("executeUpdateSQL: " + sqlStatement);

        int result;
        int index;
        PreparedStatement stmt = null;
        final StatementManagerIF sm = broker.serviceStatementManager();
        try
        {
            stmt = sm.getPreparedStatement(cld, sqlStatement,
                    Query.NOT_SCROLLABLE, StatementManagerIF.FETCH_SIZE_NOT_APPLICABLE, isStoredProcedure(sqlStatement));
            index = sm.bindValues(stmt, values1, 1);
            sm.bindValues(stmt, values2, index);
            result = stmt.executeUpdate();
        }
        catch (PersistenceBrokerException e)
        {
            logger.error("PersistenceBrokerException during the execution of the Update SQL query: " + e.getMessage(), e);
            throw e;
        }
        catch (SQLException e)
        {
            ValueContainer[] tmp = addValues(values1, values2);
            throw ExceptionHelper.generateException(e, sqlStatement, cld, tmp, logger, null);
        }
        finally
        {
            sm.closeResources(stmt, null);
        }
        return result;
    }
258353
@Override
	public AuditEvent transformToEvent(AnnotationAuditEvent annotationEvent) {
		AuditEvent event = null;

		if (annotationEvent.getClazz().isAnnotationPresent(Audit.class)
				&& !annotationEvent.getMethod().isAnnotationPresent(IgnoreAudit.class)) {
			event = new AuditEvent();
			Audit audit = annotationEvent.getClazz().getAnnotation(Audit.class);

			// Extract fields
			event.setFields(getFields(annotationEvent.getMethod(), annotationEvent.getArgs()));

			// Extract Actor
			String annotationAction = audit.action();
			if (ACTION.equals(annotationAction)) {
				event.setAction(annotationEvent.getMethod().getName());
			} else {
				event.setAction(annotationAction);
			}

			// Extract repository
			event.setRepository(audit.repository());

			event.setActor(annotationEvent.getActor());
			event.setOrigin(annotationEvent.getOrigin());
		} else if (!annotationEvent.getClazz().isAnnotationPresent(Audit.class)
				&& annotationEvent.getMethod().isAnnotationPresent(Audit.class)) {
			event = new AuditEvent();
			Audit audit = annotationEvent.getMethod().getAnnotation(Audit.class);

			// Extract fields
			event.setFields(getFields(annotationEvent.getMethod(), annotationEvent.getArgs()));

			// Extract Actor
			String annotationAction = audit.action();
			if (ACTION.equals(annotationAction)) {
				event.setAction(annotationEvent.getMethod().getName());
			} else {
				event.setAction(annotationAction);
			}

			// Extract repository
			event.setRepository(audit.repository());

			event.setActor(annotationEvent.getActor());
			event.setOrigin(annotationEvent.getOrigin());
		}

		return event;
	}
495382
@Override
    public int executeBatch()
    {
        List<JsonObject> objectsToPersist = new ArrayList<JsonObject>();
        HttpResponse response = null;
        String databaseName = null;
        boolean isbulk = false;
        try
        {
            for (Node node : nodes)
            {
                if (node.isDirty())
                {
                    node.handlePreEvent();
                    // delete can not be executed in batch
                    if (node.isInState(RemovedState.class))
                    {
                        delete(node.getData(), node.getEntityId());
                    }
                    else
                    {
                        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                                node.getDataClass());
                        databaseName = metadata.getSchema();
                        JsonObject asJsonObject = CouchDBObjectMapper.getJsonOfEntity(metadata, node.getData(),
                                node.getEntityId(), getRelationHolders(node), kunderaMetadata);
                        objectsToPersist.add(asJsonObject);
                        isbulk = true;
                    }
                    node.handlePostEvent();
                }
            }

            if (isbulk)
            {
                try
                {
                    URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                            CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase()
                                    + CouchDBConstants.URL_SEPARATOR + "_bulk_docs", null, null);

                    HttpPost post = new HttpPost(uri);
                    String object = String.format("{%s%s}", "\"all_or_nothing\": true,",
                            "\"docs\": " + gson.toJson(objectsToPersist));
                    StringEntity entity = new StringEntity(object, "UTF-8");
                    entity.setContentType("application/json");
                    post.setEntity(entity);
                    response = httpClient.execute(httpHost, post, CouchDBUtils.getContext(httpHost));
                }
                catch (Exception e)
                {
                    log.error("Error while executing batch, caused by {}. ", e);
                    throw new KunderaException("Error while executing batch. caused by :" + e);
                }
            }
        }
        catch (OperationNotSupportedException e)
        {
            throw new KunderaException(e.getMessage());
        }
        finally
        {
            CouchDBUtils.closeContent(response);
        }

        return nodes.size();
    }
918865
@Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
    {
        if (constructed)
        {

            String methodName = method.getName();
            int params = args.length;

            if (params == 0)
            {
                if (isUninitialized() && method.equals(getIdentifierMethod))
                {
                    return getIdentifier();
                }

                else if ("getKunderaLazyInitializer".equals(methodName))
                {
                    return this;
                }
            }

            Object target = getImplementation();

            String[] strArr = entityName.split("#");
            String fieldName = strArr[1];

            if (owner != null)
            {
                EntityMetadata m = KunderaMetadataManager.getEntityMetadata(persistenceDelegator.getKunderaMetadata(),
                        owner.getClass());
                Relation r = m.getRelation(fieldName);
                if (r != null)
                {
                    PropertyAccessorHelper.set(owner, r.getProperty(), target);
                }
                if (r.getBiDirectionalField() != null && method.getReturnType().equals(m.getEntityClazz()))
                {
                    PropertyAccessorHelper.set(target, r.getBiDirectionalField(), owner);
                }

            }

            try
            {
                final Object returnValue;
                if (method.isAccessible())
                {
                    if (!method.getDeclaringClass().isInstance(target))
                    {
                        throw new ClassCastException(target.getClass().getName());
                    }
                    returnValue = method.invoke(target, args);
                }
                else
                {
                    if (!method.isAccessible())
                    {
                        method.setAccessible(true);
                    }
                    returnValue = method.invoke(target, args);
                }
                return ((returnValue == target) ? proxy : returnValue);
            }
            catch (InvocationTargetException ite)
            {
                throw new LazyInitializationException(ite);
            }
        }
        else
        {
            // while constructor is running
            throw new LazyInitializationException("unexpected case hit, method=" + method.getName());
        }

    }
197943
@Override
    public int executeBatch()
    {
        Map<String, List<Row>> batchData = new HashMap<String, List<Row>>();
        try
        {
            for (Node node : nodes)
            {
                if (node.isDirty())
                {
                    Row action = null;
                    node.handlePreEvent();
                    Object rowKey = node.getEntityId();
                    Object entity = node.getData();
                    EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, node.getDataClass());
                    String tableName = HBaseUtils.getHTableName(m.getSchema(), m.getTableName());
                    if (node.isInState(RemovedState.class))
                    {
                        action = handler.prepareDelete(rowKey);
                    }
                    else
                    {
                        HBaseRow hbaseRow = ((HBaseDataHandler) handler).createHbaseRow(m, entity, rowKey, null);
                        action = handler.preparePut(hbaseRow);
                    }
                    node.handlePostEvent();
                    if (!batchData.containsKey(tableName))
                    {
                        batchData.put(tableName, new ArrayList<Row>());
                    }
                    batchData.get(tableName).add(action);
                }
            }

            if (!batchData.isEmpty())
            {
                ((HBaseDataHandler) handler).batchProcess(batchData);
            }
            return batchData.size();
        }
        catch (IOException ioex)
        {
            log.error("Error while executing batch insert/update, Caused by: .", ioex);
            throw new KunderaException(ioex);
        }

    }
886275
public void executeInsert(ClassDescriptor cld, Object obj) throws PersistenceBrokerException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("executeInsert: " + obj);
        }
        final StatementManagerIF sm = broker.serviceStatementManager();
        PreparedStatement stmt = null;
        try
        {
            stmt = sm.getInsertStatement(cld);
            if (stmt == null)
            {
                logger.error("getInsertStatement returned a null statement");
                throw new PersistenceBrokerException("getInsertStatement returned a null statement");
            }
            // before bind values perform autoincrement sequence columns
            assignAutoincrementSequences(cld, obj);
            sm.bindInsert(stmt, cld, obj);
            if (logger.isDebugEnabled())
                logger.debug("executeInsert: " + stmt);
            stmt.executeUpdate();
            // after insert read and assign identity columns
            assignAutoincrementIdentityColumns(cld, obj);

            // Harvest any return values.
            harvestReturnValues(cld.getInsertProcedure(), obj, stmt);
        }
        catch (PersistenceBrokerException e)
        {
            logger.error("PersistenceBrokerException during the execution of the insert: " + e.getMessage(), e);
            throw e;
        }
        catch(SequenceManagerException e)
        {
            throw new PersistenceBrokerException("Error while try to assign identity value", e);
        }
        catch (SQLException e)
        {
            final String sql = broker.serviceSqlGenerator().getPreparedInsertStatement(cld).getStatement();
            throw ExceptionHelper.generateException(e, sql, cld, logger, obj);
        }
        finally
        {
            sm.closeResources(stmt, null);
        }
    }
1024664
public void processLocalTransactionCommittedEvent(Object handle) throws ResourceException {
        // A application level local transaction has been committed.

        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();

        if (isTraceOn) 
        {
            if (tc.isEntryEnabled()) 
                Tr.entry(this, tc, "processLocalTransactionCommittedEvent", handle);

            if (tc.isDebugEnabled()) 
            { 
                String cId = null;
                try {
                    cId = mcf.getCorrelator(this); 
                } catch (SQLException x) {
                    // will just log the exception here and ignore it since its in trace
                    Tr.debug(this, tc, "got an exception trying to get the correlator in commit, exception is: ", x);
                }

                if (cId != null) {
                    StringBuffer stbuf = new StringBuffer(200);
                    stbuf.append("Correlator: DB2, ID: ");
                    stbuf.append(cId);
                    if (xares != null) {
                        stbuf.append(" Transaction : ");
                        stbuf.append(xares);
                    }
                    stbuf.append(" COMMIT");
                    Tr.debug(this, tc, stbuf.toString());
                }
            } 
        }

        ResourceException re = stateMgr.isValid(WSStateManager.LT_COMMIT);
        if (re == null) {
            // If no work was done during the transaction, the autoCommit value may still be
            // on.  In this case, just no-op, since some drivers like ConnectJDBC 3.1 don't
            // allow commit/rollback when autoCommit is on.  

            if (!currentAutoCommit)
                try { // autoCommit is off
                    sqlConn.commit();
                } catch (SQLException se) {
                    FFDCFilter.processException(se, "com.ibm.ws.rsadapter.spi.WSRdbManagedConnectionImpl.processLocalTransactionCommittedEvent", "554", this);
                    throw AdapterUtil.translateSQLException(se, this, true, getClass());
                }

            //Set the state only after the commit has succeeded.  Else, we change the
            // state but it has not yet been committed. - a real mess

            // Already validated the state so just set it. 
            stateMgr.transtate = WSStateManager.NO_TRANSACTION_ACTIVE;
        } else {
            throw re;
        }

        // Fill in the ConnectionEvent only if needed. 
        connEvent.recycle(ConnectionEvent.LOCAL_TRANSACTION_COMMITTED, null, handle);

        if (isTraceOn && tc.isEventEnabled())
            Tr.event(this, tc, 
                     "Firing LOCAL TRANSACTION COMMITTED event for: " + handle,
                     this);

        // loop through the listeners
        for (int i = 0; i < numListeners; i++) {
            // send Local Transaction Committed event to the current listener
            ivEventListeners[i].localTransactionCommitted(connEvent); 
        }

        // Reset the indicator so lazy enlistment will be signaled if we end up in a
        // Global Transaction. 
        wasLazilyEnlistedInGlobalTran = false;

        // Replace ConnectionEvent caching with a single reusable instance per
        // ManagedConnection. 

        if (isTraceOn && tc.isEntryEnabled()) 
        {
            Tr.exit(this, tc, "processLocalTransactionCommittedEvent");
        }
    }
459143
public EventBus emitSync(ActEvent event, Object... args) {
        return _emitWithOnceBus(eventContextSync(event, args));
    }
373457
@Override
  public OperationHandle executeStatement(SessionHandle sessionHandle, String statement,
      Map<String, String> confOverlay)
          throws HiveSQLException {
    OperationHandle opHandle = sessionManager.getSession(sessionHandle)
        .executeStatement(statement, confOverlay);
    LOG.debug(sessionHandle + ": executeStatement()");
    return opHandle;
  }