Search in sources :

Example 11 with UpdateResult

use of com.google.api.ads.admanager.axis.v202205.UpdateResult in project googleads-java-lib by googleads.

the class PopulateFirstPartyAudienceSegments method runExample.

/**
 * Runs the example.
 *
 * @param adManagerServices the services factory.
 * @param session the session.
 * @param audienceSegmentId the ID of the first party audience segment to populate.
 * @throws ApiException if the API request failed with one or more service errors.
 * @throws RemoteException if the API request failed due to other errors.
 */
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session, long audienceSegmentId) throws RemoteException {
    // Get the AudienceSegmentService.
    AudienceSegmentServiceInterface audienceSegmentService = adManagerServices.get(session, AudienceSegmentServiceInterface.class);
    // Create a statement to only select a specified first party audience
    // segment.
    StatementBuilder statementBuilder = new StatementBuilder().where("WHERE id = :audienceSegmentId and type = :type").orderBy("id ASC").limit(1).withBindVariableValue("audienceSegmentId", audienceSegmentId).withBindVariableValue("type", "FIRST_PARTY");
    // Default for total result set size.
    int totalResultSetSize = 0;
    do {
        // Get audience segments by statement.
        AudienceSegmentPage page = audienceSegmentService.getAudienceSegmentsByStatement(statementBuilder.toStatement());
        if (page.getResults() != null) {
            totalResultSetSize = page.getTotalResultSetSize();
            int i = page.getStartIndex();
            for (AudienceSegment audienceSegment : page.getResults()) {
                System.out.printf("%d) Audience segment with ID %d and name '%s' will be populated.%n", i++, audienceSegment.getId(), audienceSegment.getName());
            }
        }
        statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    } while (statementBuilder.getOffset() < totalResultSetSize);
    System.out.printf("Number of audience segments to be populated: %d%n", totalResultSetSize);
    if (totalResultSetSize > 0) {
        // Remove limit and offset from statement.
        statementBuilder.removeLimitAndOffset();
        // Create action.
        PopulateAudienceSegments action = new PopulateAudienceSegments();
        // Perform action.
        UpdateResult result = audienceSegmentService.performAudienceSegmentAction(action, statementBuilder.toStatement());
        if (result != null && result.getNumChanges() > 0) {
            System.out.printf("Number of audience segments populated: %d%n", result.getNumChanges());
        } else {
            System.out.println("No audience segments were populated.");
        }
    }
}
Also used : AudienceSegmentPage(com.google.api.ads.admanager.axis.v202108.AudienceSegmentPage) StatementBuilder(com.google.api.ads.admanager.axis.utils.v202108.StatementBuilder) PopulateAudienceSegments(com.google.api.ads.admanager.axis.v202108.PopulateAudienceSegments) AudienceSegment(com.google.api.ads.admanager.axis.v202108.AudienceSegment) AudienceSegmentServiceInterface(com.google.api.ads.admanager.axis.v202108.AudienceSegmentServiceInterface) UpdateResult(com.google.api.ads.admanager.axis.v202108.UpdateResult)

Example 12 with UpdateResult

use of com.google.api.ads.admanager.axis.v202205.UpdateResult in project ignite by apache.

the class DmlDistributedUpdateRun method handleResponse.

/**
 * Handle response from remote node.
 *
 * @param id Node id.
 * @param msg Response message.
 */
public void handleResponse(UUID id, GridH2DmlResponse msg) {
    synchronized (this) {
        if (!rspNodes.add(id))
            // ignore duplicated messages
            return;
        String err = msg.error();
        if (err != null) {
            fut.onDone(new IgniteCheckedException("Update failed. " + (F.isEmpty(err) ? "" : err) + "[reqId=" + msg.requestId() + ", node=" + id + "]."));
            return;
        }
        if (!F.isEmpty(msg.errorKeys())) {
            List<Object> errList = Arrays.asList(msg.errorKeys());
            if (errorKeys == null)
                errorKeys = new HashSet<>(errList);
            else
                errorKeys.addAll(errList);
        }
        updCntr += msg.updateCounter();
        if (rspNodes.size() == nodeCount)
            fut.onDone(new UpdateResult(updCntr, errorKeys == null ? null : errorKeys.toArray()));
    }
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) UpdateResult(org.apache.ignite.internal.processors.query.h2.UpdateResult) HashSet(java.util.HashSet)

Example 13 with UpdateResult

use of com.google.api.ads.admanager.axis.v202205.UpdateResult in project ignite by apache.

the class DmlUtils method doInsertBatched.

/**
 * Execute INSERT statement plan.
 *
 * @param plan Plan to execute.
 * @param cursor Cursor to take inserted data from. I.e. list of batch arguments for each query.
 * @param pageSize Batch size for streaming, anything <= 0 for single page operations.
 * @return Number of items affected.
 * @throws IgniteCheckedException if failed, particularly in case of duplicate keys.
 */
private static List<UpdateResult> doInsertBatched(UpdatePlan plan, List<List<List<?>>> cursor, int pageSize) throws IgniteCheckedException {
    GridCacheContext cctx = plan.cacheContext();
    DmlBatchSender snd = new DmlBatchSender(cctx, pageSize, cursor.size());
    int rowNum = 0;
    SQLException resEx = null;
    for (List<List<?>> qryRow : cursor) {
        for (List<?> row : qryRow) {
            try {
                final IgniteBiTuple keyValPair = plan.processRow(row);
                snd.add(keyValPair.getKey(), new DmlStatementsProcessor.InsertEntryProcessor(keyValPair.getValue()), rowNum);
            } catch (Exception e) {
                String sqlState;
                int code;
                if (e instanceof IgniteSQLException) {
                    sqlState = ((IgniteSQLException) e).sqlState();
                    code = ((IgniteSQLException) e).statusCode();
                } else {
                    sqlState = SqlStateCode.INTERNAL_ERROR;
                    code = IgniteQueryErrorCode.UNKNOWN;
                }
                resEx = chainException(resEx, new SQLException(e.getMessage(), sqlState, code, e));
                snd.setFailed(rowNum);
            }
        }
        rowNum++;
    }
    try {
        snd.flush();
    } catch (Exception e) {
        resEx = chainException(resEx, new SQLException(e.getMessage(), SqlStateCode.INTERNAL_ERROR, IgniteQueryErrorCode.UNKNOWN, e));
    }
    resEx = chainException(resEx, snd.error());
    if (!F.isEmpty(snd.failedKeys())) {
        SQLException e = new SQLException("Failed to INSERT some keys because they are already in cache [keys=" + snd.failedKeys() + ']', SqlStateCode.CONSTRAINT_VIOLATION, DUPLICATE_KEY);
        resEx = chainException(resEx, e);
    }
    if (resEx != null) {
        BatchUpdateException e = new BatchUpdateException(resEx.getMessage(), resEx.getSQLState(), resEx.getErrorCode(), snd.perRowCounterAsArray(), resEx);
        throw new IgniteCheckedException(e);
    }
    int[] cntPerRow = snd.perRowCounterAsArray();
    List<UpdateResult> res = new ArrayList<>(cntPerRow.length);
    for (int i = 0; i < cntPerRow.length; i++) {
        int cnt = cntPerRow[i];
        res.add(new UpdateResult(cnt, X.EMPTY_OBJECT_ARRAY));
    }
    return res;
}
Also used : GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) SQLException(java.sql.SQLException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) ArrayList(java.util.ArrayList) BatchUpdateException(java.sql.BatchUpdateException) IgniteQueryErrorCode.createJdbcSqlException(org.apache.ignite.internal.processors.cache.query.IgniteQueryErrorCode.createJdbcSqlException) SQLException(java.sql.SQLException) TransactionDuplicateKeyException(org.apache.ignite.transactions.TransactionDuplicateKeyException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) ArrayList(java.util.ArrayList) List(java.util.List) DmlStatementsProcessor(org.apache.ignite.internal.processors.query.h2.DmlStatementsProcessor) UpdateResult(org.apache.ignite.internal.processors.query.h2.UpdateResult) BatchUpdateException(java.sql.BatchUpdateException)

Example 14 with UpdateResult

use of com.google.api.ads.admanager.axis.v202205.UpdateResult in project ignite by apache.

the class DmlUtils method doUpdate.

/**
 * Perform UPDATE operation on top of results of SELECT.
 * @param cursor SELECT results.
 * @param pageSize Batch size for streaming, anything <= 0 for single page operations.
 * @return Pair [cursor corresponding to results of UPDATE (contains number of items affected); keys whose values
 *     had been modified concurrently (arguments for a re-run)].
 */
private static UpdateResult doUpdate(UpdatePlan plan, Iterable<List<?>> cursor, int pageSize) throws IgniteCheckedException {
    GridCacheContext cctx = plan.cacheContext();
    DmlBatchSender sender = new DmlBatchSender(cctx, pageSize, 1);
    for (List<?> row : cursor) {
        T3<Object, Object, Object> row0 = plan.processRowForUpdate(row);
        Object key = row0.get1();
        Object oldVal = row0.get2();
        Object newVal = row0.get3();
        sender.add(key, new DmlStatementsProcessor.ModifyingEntryProcessor(oldVal, new DmlStatementsProcessor.EntryValueUpdater(newVal)), 0);
    }
    sender.flush();
    SQLException resEx = sender.error();
    if (resEx != null) {
        if (!F.isEmpty(sender.failedKeys())) {
            // Don't go for a re-run if processing of some keys yielded exceptions and report keys that
            // had been modified concurrently right away.
            String msg = "Failed to UPDATE some keys because they had been modified concurrently " + "[keys=" + sender.failedKeys() + ']';
            SQLException dupEx = createJdbcSqlException(msg, IgniteQueryErrorCode.CONCURRENT_UPDATE);
            dupEx.setNextException(resEx);
            resEx = dupEx;
        }
        throw new IgniteSQLException(resEx);
    }
    return new UpdateResult(sender.updateCount(), sender.failedKeys().toArray(), cursor instanceof QueryCursorImpl ? ((QueryCursorImpl) cursor).partitionResult() : null);
}
Also used : GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) SQLException(java.sql.SQLException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) QueryCursorImpl(org.apache.ignite.internal.processors.cache.QueryCursorImpl) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) DmlStatementsProcessor(org.apache.ignite.internal.processors.query.h2.DmlStatementsProcessor) UpdateResult(org.apache.ignite.internal.processors.query.h2.UpdateResult)

Example 15 with UpdateResult

use of com.google.api.ads.admanager.axis.v202205.UpdateResult in project googleads-java-lib by googleads.

the class DeleteUserTeamAssociations method runExample.

/**
 * Runs the example.
 *
 * @param adManagerServices the services factory.
 * @param session the session.
 * @param userId the ID of the user to delete user team associations for.
 * @throws ApiException if the API request failed with one or more service errors.
 * @throws RemoteException if the API request failed due to other errors.
 */
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session, long userId) throws RemoteException {
    // Get the UserTeamAssociationService.
    UserTeamAssociationServiceInterface userTeamAssociationService = adManagerServices.get(session, UserTeamAssociationServiceInterface.class);
    // Create a statement to get all user team associations for a user.
    StatementBuilder statementBuilder = new StatementBuilder().where("WHERE userId = :userId ").orderBy("userId ASC, teamid ASC").limit(StatementBuilder.SUGGESTED_PAGE_LIMIT).withBindVariableValue("userId", userId);
    // Default for total result set size.
    int totalResultSetSize = 0;
    do {
        // Get user team associations by statement.
        UserTeamAssociationPage page = userTeamAssociationService.getUserTeamAssociationsByStatement(statementBuilder.toStatement());
        if (page.getResults() != null) {
            totalResultSetSize = page.getTotalResultSetSize();
            int i = page.getStartIndex();
            for (UserTeamAssociation userTeamAssociation : page.getResults()) {
                System.out.printf("%d) User team association with user ID %d and " + "team ID %d will be deleted.%n", i++, userTeamAssociation.getUserId(), userTeamAssociation.getTeamId());
            }
        }
        statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    } while (statementBuilder.getOffset() < totalResultSetSize);
    System.out.printf("Number of user team associations to be deleted: %d%n", totalResultSetSize);
    if (totalResultSetSize > 0) {
        // Remove limit and offset from statement.
        statementBuilder.removeLimitAndOffset();
        // Create action.
        com.google.api.ads.admanager.axis.v202205.DeleteUserTeamAssociations action = new com.google.api.ads.admanager.axis.v202205.DeleteUserTeamAssociations();
        // Perform action.
        UpdateResult result = userTeamAssociationService.performUserTeamAssociationAction(action, statementBuilder.toStatement());
        if (result != null && result.getNumChanges() > 0) {
            System.out.printf("Number of user team associations deleted: %d%n", result.getNumChanges());
        } else {
            System.out.println("No user team associations were deleted.");
        }
    }
}
Also used : UserTeamAssociationServiceInterface(com.google.api.ads.admanager.axis.v202205.UserTeamAssociationServiceInterface) UserTeamAssociation(com.google.api.ads.admanager.axis.v202205.UserTeamAssociation) StatementBuilder(com.google.api.ads.admanager.axis.utils.v202205.StatementBuilder) UserTeamAssociationPage(com.google.api.ads.admanager.axis.v202205.UserTeamAssociationPage) UpdateResult(com.google.api.ads.admanager.axis.v202205.UpdateResult)

Aggregations

StatementBuilder (com.google.api.ads.admanager.axis.utils.v202108.StatementBuilder)18 StatementBuilder (com.google.api.ads.admanager.axis.utils.v202111.StatementBuilder)18 StatementBuilder (com.google.api.ads.admanager.axis.utils.v202202.StatementBuilder)18 StatementBuilder (com.google.api.ads.admanager.axis.utils.v202205.StatementBuilder)18 UpdateResult (com.google.api.ads.admanager.axis.v202108.UpdateResult)18 UpdateResult (com.google.api.ads.admanager.axis.v202111.UpdateResult)18 UpdateResult (com.google.api.ads.admanager.axis.v202202.UpdateResult)18 UpdateResult (com.google.api.ads.admanager.axis.v202205.UpdateResult)18 UpdateResult (org.apache.ignite.internal.processors.query.h2.UpdateResult)11 SQLException (java.sql.SQLException)8 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)7 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)6 DmlStatementsProcessor (org.apache.ignite.internal.processors.query.h2.DmlStatementsProcessor)6 GridCacheContext (org.apache.ignite.internal.processors.cache.GridCacheContext)3 QueryCursorImpl (org.apache.ignite.internal.processors.cache.QueryCursorImpl)3 LineItemCreativeAssociationServiceInterface (com.google.api.ads.admanager.axis.v202108.LineItemCreativeAssociationServiceInterface)2 CustomTargetingServiceInterface (com.google.api.ads.admanager.axis.v202202.CustomTargetingServiceInterface)2 CustomTargetingServiceInterface (com.google.api.ads.admanager.axis.v202205.CustomTargetingServiceInterface)2 LineItemCreativeAssociationServiceInterface (com.google.api.ads.admanager.axis.v202205.LineItemCreativeAssociationServiceInterface)2 BatchUpdateException (java.sql.BatchUpdateException)2