Example usage for java.util List removeAll

List of usage examples for java.util List removeAll

Introduction

In this page you can find the example usage for java.util List removeAll.

Prototype

boolean removeAll(Collection<?> c);

Source Link

Document

Removes from this list all of its elements that are contained in the specified collection (optional operation).

Usage

From source file:dao.FilesDaoTest.java

@Test
public void testGetSubFiles2() {
    System.out.println("getSubFiles from empty Folder");
    String path = folder.toString() + fSeparator + "EmptyFolder";
    FilesDao instance = new FilesDao();

    List<URI> expResult = new ArrayList<URI>();
    expResult.removeAll(expResult);
    List<URI> result;
    try {//  ww  w . j  a  v  a 2 s.co  m
        result = instance.getSubFiles(path);
    } catch (EntryException ex) {
        result = null;
    }
    assertEquals("Some message", expResult, result);
}

From source file:io.lavagna.service.BulkOperationService.java

public List<Integer> assign(String projectShortName, List<Integer> cardIds, LabelValue value, User user) {

    List<Integer> filteredCardIds = keepCardIdsInProject(cardIds, projectShortName);
    int labelId = findBy(projectShortName, "ASSIGNED", LabelDomain.SYSTEM).getId();

    // we remove the cards that have _already_ the user assigned
    Collection<Integer> alreadyWithUserAssigned = keepCardWithMatching(filteredCardIds,
            new FilterByLabelIdAndLabelValue(labelId, value)).keySet();
    filteredCardIds.removeAll(alreadyWithUserAssigned);
    ////  w  ww . ja  v  a 2  s. c  o  m

    labelService.addLabelValueToCards(labelId, filteredCardIds, value, user, new Date());
    return filteredCardIds;
}

From source file:lodsve.core.condition.OnBeanCondition.java

private List<String> getMatchingBeans(ConditionContext context, BeanSearchSpec beans) {
    ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
    if (beans.getStrategy() == SearchStrategy.PARENTS) {
        BeanFactory parent = beanFactory.getParentBeanFactory();
        Assert.isInstanceOf(ConfigurableListableBeanFactory.class, parent,
                "Unable to use SearchStrategy.PARENTS");
        beanFactory = (ConfigurableListableBeanFactory) parent;
    }//from   w w w.  j a v a 2 s  . c  o m
    if (beanFactory == null) {
        return Collections.emptyList();
    }
    List<String> beanNames = new ArrayList<String>();
    boolean considerHierarchy = beans.getStrategy() == SearchStrategy.ALL;
    for (String type : beans.getTypes()) {
        beanNames.addAll(getBeanNamesForType(beanFactory, type, context.getClassLoader(), considerHierarchy));
    }
    for (String ignoredType : beans.getIgnoredTypes()) {
        beanNames.removeAll(
                getBeanNamesForType(beanFactory, ignoredType, context.getClassLoader(), considerHierarchy));
    }
    for (String annotation : beans.getAnnotations()) {
        beanNames.addAll(Arrays.asList(getBeanNamesForAnnotation(beanFactory, annotation,
                context.getClassLoader(), considerHierarchy)));
    }
    for (String beanName : beans.getNames()) {
        if (containsBean(beanFactory, beanName, considerHierarchy)) {
            beanNames.add(beanName);
        }
    }
    return beanNames;
}

From source file:org.saiku.web.rest.resources.BasicTagRepositoryResource.java

/**
 * Delete Query./*w w w . j  a v  a  2  s. c  o m*/
 * @param queryName - The name of the query.
 * @return A GONE Status if the query was deleted, otherwise it will return a NOT FOUND Status code.
 */
@DELETE
@Produces({ "application/json" })
@Path("/{cubeIdentifier}/{tagName}")
public Status deleteTag(@PathParam("cubeIdentifier") String cubeIdentifier,
        @PathParam("tagName") String tagName) {
    try {
        if (repo != null) {
            List<SaikuTag> tags = getSavedTags(cubeIdentifier);
            List<SaikuTag> remove = new ArrayList<SaikuTag>();
            for (SaikuTag tag : tags) {
                if (tag.getName().equals(tagName)) {
                    remove.add(tag);
                }
            }
            tags.removeAll(remove);
            ObjectMapper om = new ObjectMapper();
            om.setVisibilityChecker(om.getVisibilityChecker().withFieldVisibility(Visibility.ANY));

            String uri = repo.getName().getPath();
            if (!uri.endsWith("" + File.separatorChar)) {
                uri += File.separatorChar;
            }
            if (!cubeIdentifier.endsWith(".tag")) {
                cubeIdentifier += ".tag";
            }

            File tagFile = new File(uri + URLDecoder.decode(cubeIdentifier, "UTF-8"));
            if (tagFile.exists()) {
                tagFile.delete();
            } else {
                tagFile.createNewFile();
            }
            om.writeValue(tagFile, tags);
            return (Status.GONE);

        }
        throw new Exception("Cannot delete tag :" + tagName);
    } catch (Exception e) {
        log.error("Cannot delete tag (" + tagName + ")", e);
        return (Status.NOT_FOUND);
    }
}

From source file:com.linkedin.pinot.controller.helix.core.rebalance.ReplicaGroupRebalanceSegmentStrategy.java

/**
 * Compute the new replica group mapping based on the new configurations
 * @param tableConfig a talbe config/* ww w.j ava  2s .c o m*/
 * @param partitionAssignmentGenerator partition assignment generator
 * @return new replica group partition assignment
 */
private ReplicaGroupPartitionAssignment computeNewReplicaGroupMapping(TableConfig tableConfig,
        ReplicaGroupPartitionAssignmentGenerator partitionAssignmentGenerator) throws InvalidConfigException {
    ReplicaGroupStrategyConfig replicaGroupConfig = tableConfig.getValidationConfig()
            .getReplicaGroupStrategyConfig();

    // If no replica group config is available in table config, we cannot perform the rebalance algorithm
    if (replicaGroupConfig == null) {
        throw new InvalidConfigException("This table is not using replica group segment assignment");
    }

    // Currently, only table level replica group rebalance is supported
    if (replicaGroupConfig.getPartitionColumn() != null) {
        throw new InvalidConfigException("Partition level replica group rebalance is not supported");
    }

    // Fetch the information required for computing new replica group partition assignment
    int targetNumInstancesPerPartition = replicaGroupConfig.getNumInstancesPerPartition();
    int targetNumReplicaGroup = tableConfig.getValidationConfig().getReplicationNumber();

    OfflineTagConfig offlineTagConfig = new OfflineTagConfig(tableConfig);
    List<String> serverInstances = _helixAdmin.getInstancesInClusterWithTag(_helixClusterName,
            offlineTagConfig.getOfflineServerTag());

    // Perform the basic validation
    if (targetNumReplicaGroup <= 0 || targetNumInstancesPerPartition <= 0
            || targetNumReplicaGroup * targetNumInstancesPerPartition > serverInstances.size()) {
        throw new InvalidConfigException("Invalid input config (numReplicaGroup: " + targetNumReplicaGroup
                + ", " + "numInstancesPerPartition: " + targetNumInstancesPerPartition + ", numServers: "
                + serverInstances.size() + ")");
    }

    // Check that the partition assignment exists
    String tableNameWithType = tableConfig.getTableName();
    ReplicaGroupPartitionAssignment oldReplicaGroupPartitionAssignment = partitionAssignmentGenerator
            .getReplicaGroupPartitionAssignment(tableNameWithType);
    if (oldReplicaGroupPartitionAssignment == null) {
        throw new InvalidConfigException(
                "Replica group partition assignment does not exist for " + tableNameWithType);
    }

    // Fetch the previous replica group configurations
    List<String> oldServerInstances = oldReplicaGroupPartitionAssignment.getAllInstances();
    int oldNumReplicaGroup = oldReplicaGroupPartitionAssignment.getNumReplicaGroups();
    int oldNumInstancesPerPartition = oldServerInstances.size() / oldNumReplicaGroup;

    // Compute added and removed servers
    List<String> addedServers = new ArrayList<>(serverInstances);
    addedServers.removeAll(oldServerInstances);
    List<String> removedServers = new ArrayList<>(oldServerInstances);
    removedServers.removeAll(serverInstances);

    // Create the new replica group partition assignment
    ReplicaGroupPartitionAssignment newReplicaGroupPartitionAssignment = new ReplicaGroupPartitionAssignment(
            oldReplicaGroupPartitionAssignment.getTableName());

    // In case of replacement, create the removed to added server mapping
    Map<String, String> oldToNewServerMapping = new HashMap<>();
    if (addedServers.size() == removedServers.size()) {
        for (int i = 0; i < addedServers.size(); i++) {
            oldToNewServerMapping.put(removedServers.get(i), addedServers.get(i));
        }
    }

    // Compute rebalance type
    ReplicaGroupRebalanceType rebalanceType = computeRebalanceType(oldNumInstancesPerPartition,
            oldNumReplicaGroup, targetNumReplicaGroup, targetNumInstancesPerPartition, addedServers,
            removedServers);
    LOGGER.info("Replica group rebalance type: " + rebalanceType);

    // For now, we don't support the rebalance for partition level replica group so "numPartitions" will always be 1.
    for (int partitionId = 0; partitionId < oldReplicaGroupPartitionAssignment
            .getNumPartitions(); partitionId++) {
        int currentNewReplicaGroupId = 0;
        for (int groupId = 0; groupId < oldNumReplicaGroup; groupId++) {
            List<String> oldReplicaGroup = oldReplicaGroupPartitionAssignment
                    .getInstancesfromReplicaGroup(partitionId, groupId);
            List<String> newReplicaGroup = new ArrayList<>();
            boolean removeGroup = false;

            // Based on the rebalance type, compute the new replica group partition assignment accordingly
            switch (rebalanceType) {
            case REPLACE:
                // Swap the removed server with the added one.
                for (String oldServer : oldReplicaGroup) {
                    if (!oldToNewServerMapping.containsKey(oldServer)) {
                        newReplicaGroup.add(oldServer);
                    } else {
                        newReplicaGroup.add(oldToNewServerMapping.get(oldServer));
                    }
                }
                break;
            case ADD_SERVER:
                newReplicaGroup.addAll(oldReplicaGroup);
                // Assign new servers to the replica group
                for (int serverIndex = 0; serverIndex < addedServers.size(); serverIndex++) {
                    if (serverIndex % targetNumReplicaGroup == groupId) {
                        newReplicaGroup.add(addedServers.get(serverIndex));
                    }
                }
                break;
            case REMOVE_SERVER:
                // Only add the servers that are not in the removed list
                newReplicaGroup.addAll(oldReplicaGroup);
                newReplicaGroup.removeAll(removedServers);
                break;
            case ADD_REPLICA_GROUP:
                // Add all servers for original replica groups and add new replica groups later
                newReplicaGroup.addAll(oldReplicaGroup);
                break;
            case REMOVE_REPLICA_GROUP:
                newReplicaGroup.addAll(oldReplicaGroup);
                // mark the group if this is the replica group that needs to be removed
                if (removedServers.containsAll(oldReplicaGroup)) {
                    removeGroup = true;
                }
                break;
            default:
                String errorMessage = "Not supported replica group rebalance operation. Need to check server tags and replica group config to"
                        + " make sure only one maintenance step is asked. ( oldNumInstancesPerPatition: "
                        + oldNumInstancesPerPartition + ", targetNumInstancesPerPartition: "
                        + targetNumInstancesPerPartition + ", oldNumReplicaGroup: " + oldNumReplicaGroup
                        + ", targetNumReplicaGroup: " + targetNumReplicaGroup + ", numAddedServers: "
                        + addedServers.size() + ", numRemovedServers: " + removedServers.size() + " )";
                LOGGER.info(errorMessage);
                throw new InvalidConfigException(errorMessage);
            }
            if (!removeGroup) {
                LOGGER.info("Setting new replica group ( partitionId: " + partitionId + ", replicaGroupId: "
                        + groupId + ", server list: " + StringUtils.join(",", newReplicaGroup));
                newReplicaGroupPartitionAssignment.setInstancesToReplicaGroup(partitionId,
                        currentNewReplicaGroupId++, newReplicaGroup);
            }
        }

        // Adding new replica groups if needed
        int index = 0;
        for (int newGroupId = currentNewReplicaGroupId; newGroupId < targetNumReplicaGroup; newGroupId++) {
            List<String> newReplicaGroup = new ArrayList<>();
            while (newReplicaGroup.size() < targetNumInstancesPerPartition) {
                newReplicaGroup.add(addedServers.get(index));
                index++;
            }
            newReplicaGroupPartitionAssignment.setInstancesToReplicaGroup(partitionId, newGroupId,
                    newReplicaGroup);
        }
    }

    return newReplicaGroupPartitionAssignment;
}

From source file:com.grayfox.server.dao.jdbc.UserJdbcDao.java

@Override
public void update(User user) {
    getJdbcTemplate().update(getQuery("User.update"), user.getFoursquareId(), user.getName(),
            user.getLastName(), user.getPhotoUrl());
    if (user.getCredential() != null) {
        getJdbcTemplate().update(getQuery("Credential.delete"), user.getFoursquareId());
        getJdbcTemplate().update(getQuery("User.createHasRelationship"), user.getFoursquareId(),
                user.getCredential().getAccessToken());
    }/*  www. ja  v a  2  s .co m*/
    if (user.getFriends() != null) {
        List<String> oldFriendsIds = fetchFriendsIds(user.getFoursquareId());
        List<String> intersection = user.getFriends().stream()
                .filter(friend -> oldFriendsIds.contains(friend.getFoursquareId())).map(User::getFoursquareId)
                .collect(Collectors.toList());
        List<User> newFriends = user.getFriends().stream()
                .filter(friend -> !intersection.contains(friend.getFoursquareId()))
                .collect(Collectors.toList());
        oldFriendsIds.removeAll(intersection);
        oldFriendsIds.forEach(friendFoursquareId -> getJdbcTemplate().update(
                getQuery("User.deleteFriendsRelationship"), user.getFoursquareId(), friendFoursquareId));
        newFriends.forEach(friend -> {
            if (!exists(friend.getFoursquareId())) {
                getJdbcTemplate().update(getQuery("User.create"), friend.getName(), friend.getLastName(),
                        friend.getPhotoUrl(), friend.getFoursquareId());
                getJdbcTemplate().update(getQuery("User.createFriendsRelationship"), user.getFoursquareId(),
                        friend.getFoursquareId());
                if (friend.getLikes() != null)
                    friend.getLikes()
                            .forEach(like -> saveLike(friend.getFoursquareId(), like.getFoursquareId()));
                friend.setId(findIdByFoursquareId(friend.getFoursquareId()));
            } else
                getJdbcTemplate().update(getQuery("User.createFriendsRelationship"), user.getFoursquareId(),
                        friend.getFoursquareId());
        });
    }
    if (user.getLikes() != null) {
        List<String> oldLikesIds = fetchLikesIds(user.getFoursquareId());
        List<String> intersection = user.getLikes().stream()
                .filter(like -> oldLikesIds.contains(like.getFoursquareId())).map(Category::getFoursquareId)
                .collect(Collectors.toList());
        List<Category> newLikes = user.getLikes().stream()
                .filter(like -> !intersection.contains(like.getFoursquareId())).collect(Collectors.toList());
        oldLikesIds.removeAll(intersection);
        oldLikesIds.forEach(likeFoursquareId -> getJdbcTemplate()
                .update(getQuery("User.deleteLikesRelationship"), user.getFoursquareId(), likeFoursquareId));
        newLikes.forEach(like -> saveLike(user.getFoursquareId(), like.getFoursquareId()));
    }
}

From source file:eu.europeana.api2.v2.model.json.view.FullView.java

private List stripEmptyStrings(List swissCheese) {
    swissCheese.removeAll(Arrays.asList("", null));
    return swissCheese;
}

From source file:com.tasktop.c2c.server.internal.tasks.domain.conversion.TaskDomain.java

private void updateDependencies(Task task, List<Dependency> dependencies, List<Dependency> newDependencies) {
    int sizehint = Math.max(newDependencies.size(), dependencies.size());
    if (sizehint == 0) {
        return;/* w  w w  . j a v a2s  . c o  m*/
    }
    Date deltaTs = new Date();

    List<Dependency> removed = new ArrayList<Dependency>(sizehint);
    removed.addAll(dependencies);
    removed.removeAll(newDependencies);
    List<Dependency> added = new ArrayList<Dependency>(sizehint);
    added.addAll(newDependencies);
    added.removeAll(dependencies);

    if (removed.isEmpty() && added.isEmpty()) {
        return;
    }

    for (Dependency dependency : removed) {
        dependency.getBugsByBlocked().setDeltaTs(deltaTs);
        dependency.getBugsByDependson().setDeltaTs(deltaTs);
    }

    for (Dependency dependency : added) {
        dependency.getBugsByBlocked().setDeltaTs(deltaTs);
        dependency.getBugsByDependson().setDeltaTs(deltaTs);
    }
    dependencies.clear();
    dependencies.addAll(newDependencies);
}

From source file:it.cnr.istc.iloc.gui.StateVariableVisualizer.java

@Override
public Collection<XYPlot> getPlots(Type type) {
    Collection<IItem> instances = type.getInstances();
    Collection<XYPlot> plots = new ArrayList<>(instances.size());
    Map<IItem, Collection<Atom>> sv_atoms = new IdentityHashMap<>(instances.size());
    for (IItem i : type.getInstances()) {
        sv_atoms.put(i, new ArrayList<>());
    }//from   w  w  w  . j a v  a  2 s.  c  o  m
    for (Atom atom : ((StateVariable) type).getDefinedPredicates().stream()
            .flatMap(p -> p.getInstances().stream()).map(a -> (Atom) a)
            .filter(a -> a.state.evaluate().isSingleton() && a.state.evaluate().contains(AtomState.Active))
            .collect(Collectors.toList())) {
        for (IItem i : ((IEnumItem) atom.get(SCOPE)).getEnumVar().evaluate().getAllowedValues()) {
            if (sv_atoms.containsKey(i)) {
                sv_atoms.get(i).add(atom);
            }
        }
    }

    for (IItem sv : instances) {
        Collection<Atom> atoms = sv_atoms.get(sv);
        // For each pulse the atoms starting at that pulse
        Map<Double, Collection<Atom>> starting_atoms = new HashMap<>(atoms.size());
        // For each pulse the atoms ending at that pulse
        Map<Double, Collection<Atom>> ending_atoms = new HashMap<>(atoms.size());

        // The pulses of the timeline
        Set<Double> c_pulses = new HashSet<>(atoms.size() * 2);

        for (Atom atom : atoms) {
            double start = sv.getCore().evaluate(((IArithItem) atom.get("start")).getArithVar());
            double end = sv.getCore().evaluate(((IArithItem) atom.get("end")).getArithVar());

            if (!starting_atoms.containsKey(start)) {
                starting_atoms.put(start, new ArrayList<>());
            }
            starting_atoms.get(start).add(atom);

            if (!ending_atoms.containsKey(end)) {
                ending_atoms.put(end, new ArrayList<>());
            }
            ending_atoms.get(end).add(atom);

            c_pulses.add(start);
            c_pulses.add(end);
        }

        // we sort current pulses..
        Double[] c_pulses_array = c_pulses.toArray(new Double[c_pulses.size()]);
        Arrays.sort(c_pulses_array);

        XYIntervalSeriesCollection collection = new XYIntervalSeriesCollection();

        ValueXYIntervalSeries undefined = new ValueXYIntervalSeries("Undefined");
        ValueXYIntervalSeries sv_values = new ValueXYIntervalSeries("Values");
        ValueXYIntervalSeries conflicts = new ValueXYIntervalSeries("Conflicts");

        List<Atom> overlapping_atoms = new ArrayList<>();
        for (int i = 0; i < c_pulses_array.length - 1; i++) {
            if (starting_atoms.containsKey(c_pulses_array[i])) {
                overlapping_atoms.addAll(starting_atoms.get(c_pulses_array[i]));
            }
            if (ending_atoms.containsKey(c_pulses_array[i])) {
                overlapping_atoms.removeAll(ending_atoms.get(c_pulses_array[i]));
            }
            switch (overlapping_atoms.size()) {
            case 0:
                undefined.add(c_pulses_array[i], c_pulses_array[i], c_pulses_array[i + 1], 0, 0, 1,
                        new Atom[0]);
                break;
            case 1:
                sv_values.add(c_pulses_array[i], c_pulses_array[i], c_pulses_array[i + 1], 0, 0, 1,
                        overlapping_atoms.toArray(new Atom[overlapping_atoms.size()]));
                break;
            default:
                conflicts.add(c_pulses_array[i], c_pulses_array[i], c_pulses_array[i + 1], 0, 0, 1,
                        overlapping_atoms.toArray(new Atom[overlapping_atoms.size()]));
                break;
            }
        }

        collection.addSeries(undefined);
        collection.addSeries(sv_values);
        collection.addSeries(conflicts);

        XYBarRenderer renderer = new XYBarRenderer();
        renderer.setSeriesPaint(0, Color.lightGray);
        renderer.setSeriesPaint(1, new Color(100, 250, 100));
        renderer.setSeriesPaint(2, Color.pink);
        renderer.setBarPainter(new ReverseGradientXYBarPainter());
        renderer.setDrawBarOutline(true);
        renderer.setShadowXOffset(2);
        renderer.setShadowYOffset(2);
        renderer.setUseYInterval(true);

        renderer.setBaseItemLabelsVisible(true);
        renderer.setBaseItemLabelPaint(Color.black);
        Font font = new Font("SansSerif", Font.PLAIN, 9);
        renderer.setBaseItemLabelFont(font);
        XYItemLabelGenerator generator = (XYDataset dataset, int series,
                int item) -> toString(((ValueXYIntervalDataItem) ((XYIntervalSeriesCollection) dataset)
                        .getSeries(series).getDataItem(item)).atoms);
        ItemLabelPosition itLabPos = new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER);
        renderer.setBasePositiveItemLabelPosition(itLabPos);
        for (int i = 0; i < collection.getSeriesCount(); i++) {
            renderer.setSeriesItemLabelGenerator(i, generator);
            renderer.setSeriesItemLabelsVisible(i, true);
            renderer.setSeriesItemLabelPaint(i, Color.black);
            renderer.setSeriesItemLabelFont(i, font);
            renderer.setSeriesPositiveItemLabelPosition(i, itLabPos);
            renderer.setSeriesToolTipGenerator(i,
                    (XYDataset dataset, int series, int item) -> toString(
                            ((ValueXYIntervalDataItem) ((XYIntervalSeriesCollection) dataset).getSeries(series)
                                    .getDataItem(item)).atoms));
        }

        XYPlot plot = new XYPlot(collection, null, new NumberAxis(""), renderer);
        plot.getRangeAxis().setVisible(false);
        plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

        plots.add(plot);
    }

    return plots;
}

From source file:com.osafe.events.CheckOutEvents.java

public static String autoCaptureAuthPayments(HttpServletRequest request, HttpServletResponse response) {
    // warning there can only be ONE payment preference for this to work
    // you cannot accept multiple payment type when using an external gateway
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
    String orderId = (String) request.getAttribute("orderId");
    ShoppingCart cart = ShoppingCartEvents.getCartObject(request);
    String result = "success";

    //LS: Note: This service is automatically called from controller_ecommerce (autoCpaturePayments) checkout flow.
    //If a client wants to only 'approve' orders and not capture when order is placed update parameter CHECKOUT_CC_CAPTURE_FLAG=FALSE.
    String autoCapture = Util.getProductStoreParm(request, "CHECKOUT_CC_CAPTURE_FLAG");
    if (UtilValidate.isNotEmpty(autoCapture) && "FALSE".equals(autoCapture.toUpperCase())) {
        OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId);
        return result;

    }//from www. j  a  va 2s. c  om

    try {
        /*
         * A bit of a hack here to get the admin user since to capture payments and complete the order requires a user who has
         * the proper security permissions
         */
        GenericValue sysLogin = delegator.findByPrimaryKeyCache("UserLogin",
                UtilMisc.toMap("userLoginId", "admin"));

        List<GenericValue> lOrderPaymentPreference = delegator.findByAnd("OrderPaymentPreference",
                UtilMisc.toMap("orderId", orderId, "statusId", "PAYMENT_AUTHORIZED"));
        if (UtilValidate.isNotEmpty(lOrderPaymentPreference)) {
            /*
             * This will complete the order generate invoice and capture any payments.
             * OrderChangeHelper.completeOrder(dispatcher, sysLogin, orderId);
             */

            /*
             * To only capture payments and leave the order in approved status. Remove the complete order call,
             */
            //Get the amount to capture
            BigDecimal amountToCapture = BigDecimal.ZERO;
            for (GenericValue orderPaymentPreference : lOrderPaymentPreference) {
                amountToCapture = amountToCapture.add(orderPaymentPreference.getBigDecimal("maxAmount"))
                        .setScale(scale, rounding);
            }

            Map<String, Object> serviceContext = UtilMisc.toMap("userLogin", sysLogin, "orderId", orderId,
                    "captureAmount", amountToCapture);
            String captureResp = "";
            try {
                Map callResult = dispatcher.runSync("captureOrderPayments", serviceContext);
                if (ModelService.RESPOND_ERROR.equals(callResult.get(ModelService.RESPONSE_MESSAGE))) {
                    captureResp = "ERROR";
                } else {
                    captureResp = (String) callResult.get("processResult");
                }
                ServiceUtil.getMessages(request, callResult, null);
            } catch (Exception e) {
                captureResp = "ERROR";
                Debug.logError(e, module);
            }
            if (captureResp.equals("FAILED") || captureResp.equals("ERROR")) {
                OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId);
                // Remove all payment method from cart except GIFT_CARD
                List pmi = cart.getPaymentMethodIds();
                List giftCards = cart.getGiftCards();
                List giftCardPmi = new LinkedList();
                if (UtilValidate.isNotEmpty(giftCards)) {
                    Iterator i = giftCards.iterator();
                    while (i.hasNext()) {
                        GenericValue gc = (GenericValue) i.next();
                        giftCardPmi.add(gc.getString("paymentMethodId"));
                    }
                    pmi.removeAll(giftCardPmi);
                }
                cart.clearPaymentMethodsById(pmi);
                // Set order id as null in cart because order has been canceled
                cart.setOrderId(null);
                return "error";
            }
        } else {
            //If no payments were authorized, there are no payments to capture; approve the order.
            OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId);

        }

    } catch (Exception e) {
        Debug.logError(e, module);
    }

    return result;
}