/*
(non-Javadoc)

@see com.impetus.kundera.persistence.api.Batcher#executeBatch()
426666
@Override
    public int executeBatch()
    {
        BulkRequestBuilder bulkRequest = txClient.prepareBulk().setRefresh(isRefreshIndexes());

        try
        {
            for (Node node : nodes)
            {
                if (node.isDirty())
                {
                    node.handlePreEvent();
                    Object entity = node.getData();
                    Object id = node.getEntityId();
                    EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                            node.getDataClass());

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

                    EntityType entityType = metaModel.entity(metadata.getEntityClazz());

                    String key = getKeyAsString(id, metadata, metaModel);

                    if (node.isInState(RemovedState.class))
                    {
                        // create a delete request.

                        DeleteRequest request = new DeleteRequest(metadata.getSchema().toLowerCase(),
                                metadata.getTableName(), key);
                        bulkRequest.add(request);

                    }
                    else if (node.isUpdate())
                    {
                        Map<String, Object> values = new HashMap<String, Object>();
                        List<RelationHolder> relationHolders = getRelationHolders(node);

                        addSource(entity, values, entityType);

                        addRelations(relationHolders, values);

                        UpdateRequest request = new UpdateRequest(metadata.getSchema().toLowerCase(),
                                metadata.getTableName(), key).doc(values);
                        bulkRequest.add(request);
                    }
                    else
                    {
                        // create an insert request.
                        Map<String, Object> values = new HashMap<String, Object>();
                        List<RelationHolder> relationHolders = getRelationHolders(node);

                        addSource(entity, values, entityType);

                        addRelations(relationHolders, values);

                        IndexRequest request = new IndexRequest(metadata.getSchema().toLowerCase(),
                                metadata.getTableName(), key).source(values);
                        bulkRequest.add(request);

                    }

                }
            }

            BulkResponse response = null;
            if (nodes != null && !nodes.isEmpty())
            {
                // bulkRequest.setRefresh(true);
                response = bulkRequest.execute().actionGet();
            }
            return response != null ? response.getItems().length : 0;
        }
        finally
        {
            clear();
        }

    }
1275148
@Override
  public MutationResult execute() {
    if (pendingMutations == null || pendingMutations.isEmpty()) {
      return new MutationResultImpl(true, 0, null);
    }
    final BatchMutation<K> mutations = pendingMutations.makeCopy();
    pendingMutations = null;
    return new MutationResultImpl(keyspace.doExecuteOperation(new Operation<Void>(OperationType.WRITE) {
      @Override
      public Void execute(Cassandra.Client cassandra) throws Exception {
        cassandra.batch_mutate(mutations.getMutationMap(),
          ThriftConverter.consistencyLevel(consistencyLevelPolicy.get(operationType)));
        return null;
      }
    }));

  }
1144022
void doBatchStart(String batch, Object args) {
    checkOpen();
    JsonObject message = createMessage(args)
        .putString("batch", batch)
        .putString("action", "startBatch");
    if (open && !paused) {
      if (log.isDebugEnabled()) {
        log.debug(String.format("%s - Batch start: Batch[batch=%s]", this, batch));
      }
      eventBus.send(inAddress, message);
    }
    checkFull();
  }
925509
@Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                AsyncBatchedMetricQuery query = batchService.executeNextQuery(5000);
                if (query != null) {
                    LOGGER.info("Finished processing " + query.getExpression() + " of batch " + query.getBatchId());
                }
                Thread.sleep(POLL_INTERVAL_MS);
            } catch (InterruptedException ex) {
                LOGGER.info("Execution was interrupted.");
                Thread.currentThread().interrupt();
                break;
            } catch (Throwable ex) {
                LOGGER.warn("Exception in MetricProcessor: {}", ex.toString());
            }
        }
    }
877816
public void executeBatchIfNecessary() throws OJBBatchUpdateException
    {
        if (batchCon != null)
        {
            try
            {
                batchCon.executeBatchIfNecessary();
            }
            catch (Throwable th)
            {
                throw new OJBBatchUpdateException(th);
            }
        }
    }
238734
private void onFlushBatch(Map<String, BulkWriteOperation> bulkWriteOperationMap)
    {
        if (!bulkWriteOperationMap.isEmpty())
        {
            for (BulkWriteOperation builder : bulkWriteOperationMap.values())
            {
                try
                {
                    builder.execute(getWriteConcern());
                }
                catch (BulkWriteException bwex)
                {
                    log.error("Batch insertion is not performed due to error in write command. Caused By: ", bwex);
                    throw new KunderaException(
                            "Batch insertion is not performed due to error in write command. Caused By: ", bwex);
                }
                catch (MongoException mex)
                {
                    log.error("Batch insertion is not performed. Caused By: ", mex);
                    throw new KunderaException("Batch insertion is not performed. Caused By: ", mex);
                }
            }
        }
    }
526661
private void afterBatch(BatchBackend backend) {
		IndexedTypeSet targetedTypes = searchFactoryImplementor.getIndexedTypesPolymorphic( rootIndexedTypes );
		if ( this.optimizeAtEnd ) {
			backend.optimize( targetedTypes );
		}
		backend.flush( targetedTypes );
	}
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);
    }
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;
	}
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));
	}
209271
public int[] executeBatch(String... sqls) throws SQLException {
		Connection conn = null;
		try {
			conn = this.getConnection();
			return SqlExecutor.executeBatch(conn, sqls);
		} catch (SQLException e) {
			throw e;
		} finally {
			this.closeConnection(conn);
		}
	}
623226
@Override
  public void processEvent(QueryBatch batch) {
    try {
      PlanBuilder.Plan exportPlan = exportFunction.apply(batch);
      for (RowRecord record : rowManager.resultRows(exportPlan)) {
        for (Consumer<RowRecord> listener : opticExportListeners) {
          try {
            listener.accept(record);
          } catch (Throwable t) {
            logger.error("Exception thrown by an onRowRecordReady listener ", t);
          }
        }
      }
    } catch (Throwable t) {
      for (BatchFailureListener<Batch<String>> listener : opticFailureListeners) {
        try {
          listener.processFailure(batch, t);
        } catch (Throwable t2) {
          logger.error("Exception thrown by an onBatchFailure listener", t2);
        }
      }
    }
  }
979518
@Override
    public String evaluateBatch(List<String> request) throws PEPException {
        if (request == null) {
            throw new NullPointerException("evaluateBatch(request=null)");
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Resolving request batch ({} requests)", request.size());
        }

        String response = null;
        try {
            response = this.client.evaluateBatch(request.toArray(STRING_TYPE));
        } catch (Exception e) {
            logger.error("Error evaluating request.", e);
            throw new PEPException("Error evaluating request", e);
        }

        return response;
    }
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;
    }
367061
@Override
  public void addBatch(String sql) throws SQLException {
    checkClosed();

    if (batchStatements == null) {
      batchStatements = new ArrayList<Query>();
      batchParameters = new ArrayList<ParameterList>();
    }

    // Simple statements should not replace ?, ? with $1, $2
    boolean shouldUseParameterized = false;
    CachedQuery cachedQuery = connection.createQuery(sql, replaceProcessingEnabled, shouldUseParameterized);
    batchStatements.add(cachedQuery.query);
    batchParameters.add(null);
  }
554829
@Override
  public long[] executeLargeBatch() throws SQLException {
    checkClose();
    int size;
    if (batchQueries == null || (size = batchQueries.size()) == 0) {
      return new long[0];
    }

    lock.lock();
    try {
      internalBatchExecution(size);
      return results.getCmdInformation().getLargeUpdateCounts();

    } catch (SQLException initialSqlEx) {
      throw executeBatchExceptionEpilogue(initialSqlEx, size);
    } finally {
      executeBatchEpilogue();
      lock.unlock();
    }
  }