/*
(non-Javadoc)

@see com.impetus.kundera.persistence.api.Batcher#executeBatch()
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);
        }

    }
369678
@DELETE
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/{batchId}")
    @Description("Deletes the batch having the given ID.")
    public Response deleteBatch(@Context HttpServletRequest req,
                                    @PathParam("batchId") String batchId) {
        _validateBatchId(batchId);
        PrincipalUser currentOwner = validateAndGetOwner(req, null);

        BatchMetricQuery batch = batchService.findBatchById(batchId);
        if (batch != null) {
            PrincipalUser actualOwner = userService.findUserByUsername(batch.getOwnerName());
            validateResourceAuthorization(req, actualOwner, currentOwner);
            batchService.deleteBatch(batchId);
            return Response.status(Response.Status.OK).build();
        }
        throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND);
    }
427443
protected void writeBatchEntry(StringBuilder sb, ExecutionInfo execInfo, List<QueryInfo> queryInfoList) {
        sb.append("\"batch\":");
        sb.append(execInfo.isBatch() ? "true" : "false");
        sb.append(", ");
    }
569159
protected synchronized BatchExecutor getBatchExecutor() {
    if (batchExecutor == null) {
      batchExecutor = new BatchExecutor(bigtableConnection.getSession(), hbaseAdapter);
    }
    return batchExecutor;
  }
518701
public void executeBatch() throws OJBBatchUpdateException
    {
        if (batchCon != null)
        {
            try
            {
                batchCon.executeBatch();
            }
            catch (Throwable th)
            {
                throw new OJBBatchUpdateException(th);
            }
        }
    }
1202079
public static int[] executeBatch(Connection conn, String sql, Object[]... paramsBatch) throws SQLException {
		return executeBatch(conn, sql, new ArrayIter<Object[]>(paramsBatch));
	}
1264624
@SuppressWarnings("unchecked")
    @Override
    public Future<?> runBatchAsync(Batch<T> batch, AfterExecute<T> afterExecute) {

        for (Map.Entry<Address, T> entry : batch.getMap().entrySet()) {
            Address address = entry.getKey();
            T opFromBatch = entry.getValue();

            BoxedByteArray mapKey;
            try {
                mapKey = new BoxedByteArray(address.toWriteKey(idService));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            if (commitType == CommitType.READ_COMBINE_CAS) {
                int casRetriesRemaining = casRetries;
                do {
                    Optional<byte[]> oldBytes;
                    try {
                        oldBytes = getRaw(address);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }

                    T newOp;
                    if (oldBytes.isPresent()) {
                        T oldOp = deserializer.fromBytes(oldBytes.get());
                        newOp = (T) opFromBatch.add(oldOp);
                        if (log.isDebugEnabled()) {
                            log.debug("Combined " + oldOp + " and " + opFromBatch + " into " +
                                    newOp);
                        }
                    } else {
                        newOp = opFromBatch;
                    }

                    if (oldBytes.isPresent()) {
                        // Compare and swap, if the key is still mapped to the same byte array.
                        if (map.replace(mapKey, oldBytes.get(), newOp.serialize())) {
                            if (log.isDebugEnabled()) {
                                log.debug("Successful CAS overwrite at key " +
                                        Hex.encodeHexString(mapKey.bytes) + " with " +
                                        Hex.encodeHexString(newOp.serialize()));
                            }
                            break;
                        }
                    } else {
                        // Compare and swap, if the key is still absent from the map.
                        if (map.putIfAbsent(mapKey, newOp.serialize()) == null) {
                            // null is returned when there was no existing mapping for the 
                            // given key, which is the success case.
                            if (log.isDebugEnabled()) {
                                log.debug("Successful CAS insert without existing key for key " +
                                        Hex.encodeHexString(mapKey.bytes) + " with " +
                                        Hex.encodeHexString(newOp.serialize()));
                            }
                            break;
                        }
                    }
                } while (casRetriesRemaining-- > 0);
                if (casRetriesRemaining == -1) {
                    RuntimeException e = new RuntimeException("CAS retries exhausted");
                    afterExecute.afterExecute(e);
                    throw e;
                }
            } else if (commitType == CommitType.OVERWRITE) {
                map.put(mapKey, opFromBatch.serialize());
                if (log.isDebugEnabled()) {
                    log.debug("Write of key " + Hex.encodeHexString(mapKey.bytes));
                }
            } else {
                throw new AssertionError("Unsupported commit type: " + commitType);
            }
        }
        batch.reset();
        afterExecute.afterExecute(null); // null throwable => success
        return nullFuture;
    }
499456
@Override
  public void processEvent(QueryBatch batch) {
    try {
      batch.getClient().newDocumentManager().delete( batch.getItems() );
    } catch (Throwable t) {
      for ( BatchFailureListener<Batch<String>> listener : failureListeners ) {
        try {
          listener.processFailure(batch, t);
        } catch (Throwable t2) {
          logger.error("Exception thrown by an onBatchFailure listener", t2);
        }
      }
      for ( BatchFailureListener<QueryBatch> queryBatchFailureListener : queryBatchFailureListeners ) {
        try {
          queryBatchFailureListener.processFailure(batch, t);
        } catch (Throwable t2) {
          logger.error("Exception thrown by an onFailure listener", t2);
        }
      }
    }
  }
84584
private void executeBatch(BatchStatement batchState) {
        if (batchState.size() > 0) {
            m_logger.debug("Executing synchronous batch with {} statements", batchState.size());
            m_dbservice.getSession().execute(batchState);
        }
    }
554422
@Override
	public void run(ApplicationArguments args) throws Exception {
		List<File> scriptsToRun = args.getNonOptionArgs().stream()
				.filter(s -> s.startsWith("@"))
				.map(s -> new File(s.substring(1)))
				.collect(Collectors.toList());

		boolean batchEnabled = environment.getProperty(SPRING_SHELL_SCRIPT_ENABLED, boolean.class, true);

		if (!scriptsToRun.isEmpty() && batchEnabled) {
			InteractiveShellApplicationRunner.disable(environment);
			for (File file : scriptsToRun) {
				try (Reader reader = new FileReader(file);
						FileInputProvider inputProvider = new FileInputProvider(reader, parser)) {
					shell.run(inputProvider);
				}
			}
		}
	}
84173
void executeHandlers(EventBatch<AuditEvent> batch) {
        String formattedEvent = "";
        for (AuditEvent auditEvent : batch) {
            formattedEvent = formattedEvent + configContext.getLayout().format(auditEvent) + '\n';
        }
        for (final Handler handler : configContext.getHandlers()) {
            handler.setEventBatch(batch);
            handler.setQuery(formattedEvent);
            try {
                //handler.handle();
                handler.handle(batch);
                handler.handle(formattedEvent);
            } catch (HandlerException e) {
                Log.warn("Failed to submit audit event.", e);
            }
        }
    }
569789
private void doBatchEnd(final JsonObject message) {
    if (currentBatch != null) {
      Object args = deserializer.deserialize(message);
      if (log.isDebugEnabled()) {
        log.debug(String.format("%s - Batch ended: Batch[batch=%s, args=%s]", this, currentBatch.id(), args));
      }
      currentBatch.handleEnd(args);
      currentBatch = null;
    }
  }
196473
@Override
	public void bindBatchParams(final PreparedStatement preparedStatement) throws SQLException {
		for (Map<String, Parameter> paramMap : batchParameters) {
			parameterMap = paramMap;
			bindParams(preparedStatement);
			preparedStatement.addBatch();
		}
		LOG.debug("{} items Added for batch process.", batchParameters.size());
	}
751188
@Override
	public int[] executeBatch(String sql, List<Object> list) {
		if (list.isEmpty() == true) {
			return new int[] {};
		}
		Iterator<Object> iterator = list.iterator();
		if (iterator.hasNext() == false) {
			return new int[] {};
		}
		Connection connection = null;
		PreparedStatement ps = null;
		try {
			PropertyDesc.cacheModeOn();
			connection = getConnection();
			Object object = iterator.next();

			Map<String, ParameterValue> values = new HashMap<>();
			addValues(values, object);
			sql = getSql(sql, dialect);
			ps = createPreparedStatement(connection, sql, values, ExecuteType.UPDATE, dialect, null);
			PreparedStatementUtil.addBatch(ps, sqlLogRegistry);

			while (iterator.hasNext()) {
				object = iterator.next();

				Node node = parse(sql);
				values = new HashMap<>();
				addValues(values, object);
				CommandContext ctx = new CommandContext(dialect);
				ctx.addArgs(values);
				node.accept(ctx);
				List<Object> bindVariables = ctx.getBindVariables();
				List<Integer> bindVariableTypes = ctx.getBindVariableTypes();
				bindArgs(ps, bindVariables, bindVariableTypes, ExecuteType.UPDATE, dialect);
				PreparedStatementUtil.addBatch(ps, sqlLogRegistry);
			}
			return PreparedStatementUtil.executeBatch(ps, sqlLogRegistry);
		} finally {
			PropertyDesc.cacheModeOff();
			try {
				StatementUtil.close(ps);
			} finally {
				ConnectionUtil.close(connection);
			}
		}
	}
810830
public int[] executeBatch() throws SQLException {
        final boolean isExceptionThrown = ExecutorExceptionHandler.isExceptionThrown();
        SQLExecuteCallback<int[]> callback = new SQLExecuteCallback<int[]>(getDatabaseType(), isExceptionThrown) {
            
            @Override
            protected int[] executeSQL(final RouteUnit routeUnit, final Statement statement, final ConnectionMode connectionMode) throws SQLException {
                return statement.executeBatch();
            }
        };
        List<int[]> results = executeCallback(callback);
        if (isAccumulate()) {
            return accumulate(results);
        } else {
            return results.get(0);
        }
    }
685477
function executeBatch(bulkOperation, batch, options, callback) {
  function resultHandler(err, result) {
    // Error is a driver related error not a bulk op error, terminate
    if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) {
      return handleCallback(callback, err);
    }

    // If we have and error
    if (err) err.ok = 0;
    if (err instanceof MongoWriteConcernError) {
      return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, false, err, callback);
    }
    handleCallback(
      callback,
      null,
      mergeBatchResults(false, batch, bulkOperation.s.bulkResult, err, result)
    );
  }

  bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback);
}
769938
public int executeBatch() {
        Cassandra.Client conn = null;
        Object pooledConnection = null;

        /**
         * Key -> Entity Class Value -> Map containing Row ID as Key and Mutation List as Value
         */
        Map<Class<?>, Map<ByteBuffer, Map<String, List<Mutation>>>> batchMutationMap =
            new HashMap<Class<?>, Map<ByteBuffer, Map<String, List<Mutation>>>>();

        int recordsExecuted = 0;
        boolean setCounter = true;
        String batchQuery = CQLTranslator.BATCH_QUERY;
        batchQuery = StringUtils.replace(batchQuery, CQLTranslator.STATEMENT, "");
        StringBuilder batchQueryBuilder = new StringBuilder(batchQuery);
        try {
            boolean isCql3Enabled = false;
            for (Node node : nodes) {
                if (node.isDirty()) {
                    node.handlePreEvent();
                    Object entity = node.getData();
                    Object id = node.getEntityId();
                    EntityMetadata metadata =
                        KunderaMetadataManager.getEntityMetadata(kunderaMetadata, node.getDataClass());
                    if (metadata.isCounterColumnType() && setCounter) {
                        batchQueryBuilder = new StringBuilder(StringUtils.replace(batchQueryBuilder.toString(),
                            CQLTranslator.BEGIN_BATCH, CQLTranslator.BEGIN_COUNTER_BATCH));
                        setCounter = false;
                    }
                    persistenceUnit = metadata.getPersistenceUnit();
                    isUpdate = node.isUpdate();

                    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                        .getMetamodel(metadata.getPersistenceUnit());

                    // delete can not be executed in batch

                    if (isCql3Enabled(metadata)) {
                        isCql3Enabled = true;
                        List<RelationHolder> relationHolders = getRelationHolders(node);
                        if (node.isInState(RemovedState.class)) {
                            String query;
                            query = onDeleteQuery(metadata, metadata.getTableName(), metaModel, id);
                            batchQueryBuilder.append(Constants.SPACE);
                            batchQueryBuilder.append(query);
                        } else {
                            List<String> insertQueries = getPersistQueries(metadata, entity, conn, relationHolders,
                                getTtlValues().get(metadata.getTableName()));
                            for (String query : insertQueries) {
                                batchQueryBuilder.append(Constants.SPACE);
                                batchQueryBuilder.append(query);
                            }
                        }
                    } else {
                        if (node.isInState(RemovedState.class)) {
                            delete(entity, id);
                        } else {
                            List<RelationHolder> relationHolders = getRelationHolders(node);
                            Map<ByteBuffer, Map<String, List<Mutation>>> mutationMap =
                                new HashMap<ByteBuffer, Map<String, List<Mutation>>>();
                            mutationMap = prepareMutation(metadata, entity, id, relationHolders, mutationMap);

                            recordsExecuted += mutationMap.size();
                            if (!batchMutationMap.containsKey(metadata.getEntityClazz())) {
                                batchMutationMap.put(metadata.getEntityClazz(), mutationMap);
                            } else {
                                batchMutationMap.get(metadata.getEntityClazz()).putAll(mutationMap);
                            }

                            indexNode(node, metadata);
                        }
                    }
                    node.handlePostEvent();
                }
            }

            // Write Mutation map to database

            if (!batchMutationMap.isEmpty()) {
                pooledConnection = getConnection();
                conn = (org.apache.cassandra.thrift.Cassandra.Client) getConnection(pooledConnection);

                for (Class<?> entityClass : batchMutationMap.keySet()) {
                    conn.batch_mutate(batchMutationMap.get(entityClass), consistencyLevel);
                }
            }

            if (!nodes.isEmpty() && isCql3Enabled) {
                batchQueryBuilder.append(CQLTranslator.APPLY_BATCH);
                executeCQLQuery(batchQueryBuilder.toString(), isCql3Enabled);
            }
        } catch (Exception e) {
            log.error("Error while persisting record. Caused by: .", e);
            throw new KunderaException(e);
        } finally {
            clear();
            if (pooledConnection != null) {
                releaseConnection(pooledConnection);
            }
        }

        return recordsExecuted;
    }