/*
(non-Javadoc)

@see com.impetus.kundera.persistence.api.Batcher#executeBatch()
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();
    }
786188
public void processEvent(QueryBatch batch) {
    if ( ! (batch.getClient() instanceof DatabaseClientImpl) ) {
      throw new IllegalStateException("DatabaseClient must be instanceof DatabaseClientImpl");
    }
    StringHandle uris = new StringHandle(String.join("\n", batch.getItems()))
      .withMimetype("text/uri-list");
    RESTServices services = ((DatabaseClientImpl) batch.getClient()).getServices();
    try {
      RequestParameters params = new RequestParameters();
      if ( transform != null ) transform.merge(params);
      params.add("result", applyResult.toString().toLowerCase());
      List<String> responseUris = new BufferedReader(
        services.postResource(null, "internal/apply-transform", null, params, uris, new ReaderHandle()).get()
      ).lines().collect(Collectors.toList());
      QueryBatchImpl processedBatch = new QueryBatchImpl()
        .withClient( batch.getClient() )
        .withItems( responseUris.toArray(new String[responseUris.size()]) )
        .withTimestamp( batch.getTimestamp() )
        .withJobBatchNumber( batch.getJobBatchNumber() )
        .withJobResultsSoFar( batch.getJobResultsSoFar() )
        .withForestBatchNumber( batch.getForestBatchNumber() )
        .withForestResultsSoFar( batch.getForestResultsSoFar() )
        .withForest( batch.getForest() )
        .withServerTimestamp( batch.getServerTimestamp() )
        .withJobTicket( batch.getJobTicket() );
      for ( QueryBatchListener listener : successListeners ) {
        try {
          listener.processEvent(processedBatch);
        } catch (Throwable t) {
          logger.error("Exception thrown by an onSuccess listener", t);
        }
      }

      List<String> skippedRequestUris = new ArrayList<>(Arrays.asList(batch.getItems()));
      skippedRequestUris.removeAll( responseUris );
      if ( skippedRequestUris.size() > 0 ) {
        QueryBatchImpl skippedBatch = processedBatch
          .withItems( skippedRequestUris.toArray(new String[0]) );
        for ( QueryBatchListener listener : skippedListeners ) {
          try {
            listener.processEvent(skippedBatch);
          } catch (Throwable t) {
            logger.error("Exception thrown by an onSkipped listener", t);
          }
        }
      }
    } 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);
        }
      }
      logger.warn("Error: {} in batch with urs ({})", t.toString(),
        Arrays.asList(batch.getItems()));
    }
  }
266887
@Override
    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
        ContentProviderResult[] result = null;

        SQLiteDatabase db = this.getHelper().getWritableDatabase();

        db.beginTransaction();
        try {
            result = super.applyBatch(operations);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
        return result;
    }
1202079
public static int[] executeBatch(Connection conn, String sql, Object[]... paramsBatch) throws SQLException {
		return executeBatch(conn, sql, new ArrayIter<Object[]>(paramsBatch));
	}
94738
@Override
	public int[] executeBatch() throws SQLException {
		Split s = prepare(batchSql);
		try {
			return stmt.executeBatch();
		} finally {
			finish(s);
		}
	}
1157240
@Override
	public int count() {
		if (batch) {
			throw new IllegalStateException(
					"Since the parameter has already been set with addBatch() method, please call batch() method.");
		}
		try {
			return agent().update(context());
		} catch (SQLException e) {
			throw new UroborosqlSQLException(e);
		}
	}
393633
private int executeBatch() {
		try {
			return Arrays.stream(agent().batch(context())).sum();
		} catch (Exception ex) {
			errorAction.accept(agent(), context(), ex);
		} finally {
			batchAction.accept(agent(), context());
		}
		return 0;
	}
883902
private void execute(Map<Key, List<TableOperation>> batches)
    {
        if (batches != null && !batches.isEmpty())
        {
            try
            {
                for (List<TableOperation> batch : batches.values())
                {
                    tableAPI.execute(batch, null);
                }
            }
            catch (DurabilityException e)
            {
                log.error("Error while executing operations in OracleNOSQL, Caused by:" + e + ".");
                throw new PersistenceException("Error while Persisting data using batch", e);
            }
            catch (TableOpExecutionException e)
            {
                log.error("Error while executing operations in OracleNOSQL, Caused by:" + e + ".");
                throw new PersistenceException("Error while Persisting data using batch", e);
            }
            catch (FaultException e)
            {
                log.error("Error while executing operations in OracleNOSQL, Caused by:" + e + ".");
                throw new PersistenceException("Error while Persisting data using batch", e);
            }
            finally
            {
                batches.clear();
            }
        }
    }
501809
@Override
    public String prepareBatchQuery(List<String> statements) {

        StringBuilder sb = new StringBuilder("BEGIN BATCH \n");

        for (String statement : statements) {
            sb.append(statement).append("\n");
        }

        sb.append(" APPLY BATCH;");

        return sb.toString();
    }
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);
			}
		}
	}
902651
@Override
    @Transactional
    public void run() {
        String storedProc = "purge_obsolete_batch_data";
        boolean result = entityManager.createStoredProcedureQuery(storedProc)
                                      .registerStoredProcedureParameter(0, Integer.class, ParameterMode.IN)
                                      .setParameter(0, 90)
                                      .execute();
        log.info("executed {} : resultset ? {}", storedProc, result);
    }
1221578
@Override
    public int executeBatch()
    {

        Map<Key, List<TableOperation>> operations = new HashMap<Key, List<TableOperation>>();
        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());
                    List<RelationHolder> relationHolders = getRelationHolders(node);
                    // KunderaCoreUtils.showQuery("Execute batch for" +
                    // metadata.getSchema() + "." + metadata.getTableName(),
                    // showQuery);
                    Row row = createRow(metadata, node.getData(), node.getEntityId(), relationHolders);

                    Table schemaTable = tableAPI.getTable(metadata.getTableName());

                    addOps(operations, schemaTable, row);
                }
                node.handlePostEvent();
            }
        }

        execute(operations);
        return nodes.size();
    }
1105774
@Override
    public void addBatch() throws SQLException
    {
        checkClosed();
        if (this.Query.isOfType(VoltSQL.TYPE_EXEC,VoltSQL.TYPE_SELECT)) {
            throw SQLError.get(SQLError.ILLEGAL_STATEMENT, this.Query.toSqlString());
        }
        this.addBatch(this.Query.getExecutableQuery(this.parameters));
        this.parameters = this.Query.getParameterArray();
    }
492434
@Override
    public void batchProcess(Map<String, List<Row>> batchData)
    {
        for (String tableName : batchData.keySet())
        {
            List<Row> actions = batchData.get(tableName);
            try
            {
                Table hTable = gethTable(tableName);
                hTable.batch(actions, new Object[actions.size()]);
            }
            catch (IOException | InterruptedException e)
            {
                logger.error("Error while batch processing on HTable: " + tableName);
                throw new PersistenceException(e);
            }

        }

    }
1005537
public <T> void queue(StorageRequest<T> req, JsonBatchCallback<T> callback) throws IOException {
    checkState(
        !requestsExecutor.isShutdown() && !requestsExecutor.isTerminated(),
        "requestsExecutor should not be terminated to queue batch requests");
    if (maxRequestsPerBatch == 1) {
      responseFutures.add(
          requestsExecutor.submit(
              () -> {
                execute(req, callback);
                return null;
              }));
    } else {
      pendingRequests.add(batch -> req.queue(batch, callback));

      flushIfPossibleAndRequired();
    }
  }
1003935
@Override
    public int[] executeBatch() throws SQLException
    {
        checkClosed();
        closeCurrentResult();
        if (batch == null || batch.size() == 0) {
            return new int[0];
        }

        int[] updateCounts = new int[batch.size()];
        // keep a running total of update counts
        int runningUpdateCount = 0;

        int i = 0;
        try {
            for (; i < batch.size(); i++) {

                setCurrentResult(
                        null,
                        (int) batch.get(i).execute(
                                sourceConnection.NativeConnection,
                                this.m_timeout,
                                sourceConnection.queryTimeOutUnit)[0].fetchRow(
                                0).getLong(0));
                updateCounts[i] = this.lastUpdateCount;
                runningUpdateCount += this.lastUpdateCount;
            }
        } catch (SQLException x) {
            updateCounts[i] = EXECUTE_FAILED;
            throw new BatchUpdateException(Arrays.copyOf(updateCounts, i + 1),
                    x);
        } finally {
            clearBatch();
        }
        // replace the update count from the last statement with the update count
        // from the last batch.
        this.lastUpdateCount = runningUpdateCount;

        return updateCounts;
    }
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);
        }
      }
    }
  }