Example usage for java.util List listIterator

List of usage examples for java.util List listIterator

Introduction

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

Prototype

ListIterator<E> listIterator();

Source Link

Document

Returns a list iterator over the elements in this list (in proper sequence).

Usage

From source file:com.redhat.rhn.manager.system.SystemManager.java

/**
 * List duplicate systems by hostname//from w  ww .j a va2  s  .  com
 * @param user the user doing the search
 * @param inactiveHours the number of hours a system hasn't checked in
 *          to consider it inactive
 * @return List of DuplicateSystemBucket objects
 */
public static List<DuplicateSystemGrouping> listDuplicatesByHostname(User user, Long inactiveHours) {
    List<DuplicateSystemGrouping> duplicateSystems = listDuplicates(user, "duplicate_system_ids_hostname",
            new ArrayList<String>(), inactiveHours);
    ListIterator<DuplicateSystemGrouping> litr = duplicateSystems.listIterator();
    while (litr.hasNext()) {
        DuplicateSystemGrouping element = litr.next();
        element.setKey(IDN.toUnicode(element.getKey()));
    }
    return duplicateSystems;
}

From source file:com.ut.healthelink.controller.adminProcessingActivity.java

/**
 * The 'donotprocessAllTransactions' function will update all transactions based on the passed in organziation id and message type id to DO NOT PROCESS.
 *///from   w w  w.j av  a2  s .c o  m
@RequestMapping(value = "/donotprocessAllTransactions", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody boolean donotprocessAllTransactions(
        @RequestParam(value = "orgId", required = true) Integer orgId,
        @RequestParam(value = "messageTypeId", required = false) Integer messageTypeId) throws Exception {

    if (messageTypeId == null || "".equals(messageTypeId)) {
        messageTypeId = 0;
    }

    /* Need to get all transactions for the passed in org and message type id (IF PASSED IN) */
    List transactions = transactionOutManager.getAllransactionsToProcessByMessageType(orgId, messageTypeId);

    for (ListIterator iter = transactions.listIterator(); iter.hasNext();) {
        Object[] row = (Object[]) iter.next();
        transactionOutManager
                .doNotProcessTransaction(Integer.valueOf(Integer.parseInt(String.valueOf(row[0]))));

    }

    return true;
}

From source file:com.ut.healthelink.controller.adminProcessingActivity.java

/**
 * The 'processAllTransactions' function will process all transactions based on the passed in organziation id and message type id.
 *//*w  w w .j a va 2 s .c om*/
@RequestMapping(value = "/processAllTransactions", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody boolean processAllTransactions(
        @RequestParam(value = "orgId", required = true) Integer orgId,
        @RequestParam(value = "messageTypeId", required = false) Integer messageTypeId) throws Exception {

    if (messageTypeId == null || "".equals(messageTypeId)) {
        messageTypeId = 0;
    }

    /* Need to get all transactions for the passed in org and message type id (IF PASSED IN) */
    List transactions = transactionOutManager.getAllransactionsToProcessByMessageType(orgId, messageTypeId);

    for (ListIterator iter = transactions.listIterator(); iter.hasNext();) {

        Object[] row = (Object[]) iter.next();

        transactionTarget transaction = transactionOutManager
                .getTransactionDetails(Integer.valueOf(Integer.parseInt(String.valueOf(row[0]))));

        int batchId = transactionOutManager.processManualTransaction(transaction);

    }

    return true;
}

From source file:org.broadleafcommerce.openadmin.server.service.AdminEntityServiceImpl.java

@Override
public PersistenceResponse addSubCollectionEntity(EntityForm entityForm, ClassMetadata mainMetadata,
        Property field, Entity parentEntity, List<SectionCrumb> sectionCrumbs)
        throws ServiceException, ClassNotFoundException {
    // Assemble the properties from the entity form
    List<Property> properties = new ArrayList<Property>();
    for (Entry<String, Field> entry : entityForm.getFields().entrySet()) {
        Property p = new Property();
        p.setName(entry.getKey());//  w w w.ja  v a  2  s .c  o  m
        p.setValue(entry.getValue().getValue());
        properties.add(p);
    }

    FieldMetadata md = field.getMetadata();

    PersistencePackageRequest ppr = PersistencePackageRequest.fromMetadata(md, sectionCrumbs)
            .withEntity(new Entity());

    if (md instanceof BasicCollectionMetadata) {
        BasicCollectionMetadata fmd = (BasicCollectionMetadata) md;
        ppr.getEntity().setType(new String[] { entityForm.getEntityType() });

        // If we're looking up an entity instead of trying to create one on the fly, let's make sure 
        // that we're not changing the target entity at all and only creating the association to the id
        if (fmd.getAddMethodType().equals(AddMethodType.LOOKUP)
                || fmd.getAddMethodType().equals(AddMethodType.LOOKUP_FOR_UPDATE)) {
            List<String> fieldsToRemove = new ArrayList<String>();

            String idProp = getIdProperty(mainMetadata);
            for (String key : entityForm.getFields().keySet()) {
                if (!idProp.equals(key)) {
                    fieldsToRemove.add(key);
                }
            }

            for (String key : fieldsToRemove) {
                ListIterator<Property> li = properties.listIterator();
                while (li.hasNext()) {
                    if (li.next().getName().equals(key)) {
                        li.remove();
                    }
                }
            }

            ppr.setValidateUnsubmittedProperties(false);
        }

        if (fmd.getAddMethodType().equals(AddMethodType.LOOKUP_FOR_UPDATE)) {
            ppr.setUpdateLookupType(true);
        }

        Property fp = new Property();
        fp.setName(ppr.getForeignKey().getManyToField());
        fp.setValue(getContextSpecificRelationshipId(mainMetadata, parentEntity, field.getName()));
        properties.add(fp);
    } else if (md instanceof AdornedTargetCollectionMetadata) {
        ppr.getEntity().setType(new String[] { ppr.getAdornedList().getAdornedTargetEntityClassname() });

        String[] maintainedFields = ((AdornedTargetCollectionMetadata) md).getMaintainedAdornedTargetFields();
        if (maintainedFields == null || maintainedFields.length == 0) {
            ppr.setValidateUnsubmittedProperties(false);
        }
    } else if (md instanceof MapMetadata) {
        ppr.getEntity().setType(new String[] { entityForm.getEntityType() });

        Property p = new Property();
        p.setName("symbolicId");
        p.setValue(getContextSpecificRelationshipId(mainMetadata, parentEntity, field.getName()));
        properties.add(p);
    } else {
        throw new IllegalArgumentException(
                String.format("The specified field [%s] for class [%s] was" + " not a collection field.",
                        field.getName(), mainMetadata.getCeilingType()));
    }

    ppr.setCeilingEntityClassname(ppr.getEntity().getType()[0]);
    String sectionField = field.getName();
    if (sectionField.contains(".")) {
        sectionField = sectionField.substring(0, sectionField.lastIndexOf("."));
    }
    ppr.setSectionEntityField(sectionField);

    Property parentNameProp = parentEntity.getPMap().get(AdminMainEntity.MAIN_ENTITY_NAME_PROPERTY);
    if (parentNameProp != null) {
        ppr.setRequestingEntityName(parentNameProp.getValue());
    }

    Property[] propArr = new Property[properties.size()];
    properties.toArray(propArr);
    ppr.getEntity().setProperties(propArr);

    return add(ppr);
}

From source file:org.apache.gobblin.salesforce.SalesforceExtractor.java

/**
 * Get Record set using salesforce specific API(Bulk API)
 * @param entity/tablename/*from  ww  w  .ja va  2  s . c  om*/
 * @param predicateList of all predicate conditions
   * @return iterator with batch of records
 */
private List<BatchIdAndResultId> getQueryResultIds(String entity, List<Predicate> predicateList)
        throws Exception {
    if (!bulkApiLogin()) {
        throw new IllegalArgumentException("Invalid Login");
    }

    try {
        boolean usingPkChunking = false;

        // Set bulk job attributes
        this.bulkJob.setObject(entity);
        this.bulkJob.setOperation(OperationEnum.query);
        this.bulkJob.setConcurrencyMode(ConcurrencyMode.Parallel);

        // use pk chunking if pk chunking is configured and the expected record count is larger than the pk chunking size
        if (this.pkChunking && getExpectedRecordCount() > this.pkChunkingSize) {
            log.info("Enabling pk chunking with size {}", this.pkChunkingSize);
            this.bulkConnection.addHeader("Sforce-Enable-PKChunking", "chunkSize=" + this.pkChunkingSize);
            usingPkChunking = true;
        }

        // Result type as CSV
        this.bulkJob.setContentType(ContentType.CSV);

        this.bulkJob = this.bulkConnection.createJob(this.bulkJob);
        this.bulkJob = this.bulkConnection.getJobStatus(this.bulkJob.getId());

        // Construct query with the predicates
        String query = this.updatedQuery;
        if (!isNullPredicate(predicateList)) {
            String limitString = getLimitFromInputQuery(query);
            query = query.replace(limitString, "");

            Iterator<Predicate> i = predicateList.listIterator();
            while (i.hasNext()) {
                Predicate predicate = i.next();
                query = SqlQueryUtils.addPredicate(query, predicate.getCondition());
            }

            query = query + limitString;
        }

        log.info("QUERY:" + query);
        ByteArrayInputStream bout = new ByteArrayInputStream(
                query.getBytes(ConfigurationKeys.DEFAULT_CHARSET_ENCODING));

        BatchInfo bulkBatchInfo = this.bulkConnection.createBatchFromStream(this.bulkJob, bout);

        long expectedSizePerBatch = usingPkChunking ? this.pkChunkingSize : this.getExpectedRecordCount();

        int retryInterval = Math.min(MAX_RETRY_INTERVAL_SECS,
                30 + (int) Math.ceil((float) expectedSizePerBatch / 10000) * 2);
        log.info("Salesforce bulk api retry interval in seconds:" + retryInterval);

        // Get batch info with complete resultset (info id - refers to the resultset id corresponding to entire resultset)
        bulkBatchInfo = this.bulkConnection.getBatchInfo(this.bulkJob.getId(), bulkBatchInfo.getId());

        // wait for completion, failure, or formation of PK chunking batches
        while ((bulkBatchInfo.getState() != BatchStateEnum.Completed)
                && (bulkBatchInfo.getState() != BatchStateEnum.Failed)
                && (!usingPkChunking || bulkBatchInfo.getState() != BatchStateEnum.NotProcessed)) {
            Thread.sleep(retryInterval * 1000);
            bulkBatchInfo = this.bulkConnection.getBatchInfo(this.bulkJob.getId(), bulkBatchInfo.getId());
            log.debug("Bulk Api Batch Info:" + bulkBatchInfo);
            log.info("Waiting for bulk resultSetIds");
        }

        // Wait for pk chunking batches
        BatchInfoList batchInfoList = this.bulkConnection.getBatchInfoList(this.bulkJob.getId());

        if (usingPkChunking && bulkBatchInfo.getState() == BatchStateEnum.NotProcessed) {
            bulkBatchInfo = waitForPkBatches(batchInfoList, retryInterval);
        }

        if (bulkBatchInfo.getState() == BatchStateEnum.Failed) {
            log.error("Bulk batch failed: " + bulkBatchInfo.toString());
            throw new RuntimeException("Failed to get bulk batch info for jobId " + bulkBatchInfo.getJobId()
                    + " error - " + bulkBatchInfo.getStateMessage());
        }

        // Get resultset ids of all the batches from the batch info list
        List<BatchIdAndResultId> batchIdAndResultIdList = Lists.newArrayList();

        for (BatchInfo bi : batchInfoList.getBatchInfo()) {
            QueryResultList list = this.bulkConnection.getQueryResultList(this.bulkJob.getId(), bi.getId());

            for (String result : list.getResult()) {
                batchIdAndResultIdList.add(new BatchIdAndResultId(bi.getId(), result));
            }
        }

        log.info("QueryResultList: " + batchIdAndResultIdList);

        return batchIdAndResultIdList;

    } catch (RuntimeException | AsyncApiException | InterruptedException e) {
        throw new RuntimeException(
                "Failed to get query result ids from salesforce using bulk api; error - " + e.getMessage(), e);
    }
}

From source file:com.ut.healthelink.controller.adminProcessingActivity.java

/**
 * The '/pending' GET request will retrieve a list of pendind transactions grouped by organization.
 *
 * @return The list of pending transactions to be processed
 *
 * @throws Exception//from   w w w.  jav  a  2  s.c om
 */
@RequestMapping(value = "/pending", method = RequestMethod.GET)
public ModelAndView showWaitingMessages(HttpSession session) throws Exception {

    ModelAndView mav = new ModelAndView();
    mav.setViewName("/administrator/processing-activity/pending");

    /* Get system inbound summary */
    systemSummary summaryDetails = transactionOutManager.generateSystemWaitingSummary();
    mav.addObject("summaryDetails", summaryDetails);

    /* Get all waiting transactions */
    try {
        /* Need to get a list of all uploaded batches */
        List batchTransactions = transactionOutManager.getTransactionsToProcess();

        List<pendingDeliveryTargets> transactionList = new ArrayList<pendingDeliveryTargets>();

        if (!batchTransactions.isEmpty()) {
            for (ListIterator iter = batchTransactions.listIterator(); iter.hasNext();) {

                Object[] row = (Object[]) iter.next();

                /* Get the target Org */
                Organization tgtOrgDetails = organizationmanager
                        .getOrganizationById(Integer.valueOf(Integer.parseInt(String.valueOf(row[0]))));

                pendingDeliveryTargets targetDetails = new pendingDeliveryTargets();
                targetDetails.setOrgId(tgtOrgDetails.getId());
                targetDetails.setTotalPending(Integer.valueOf(Integer.parseInt(String.valueOf(row[1]))));

                String OrgDetails = new StringBuilder().append(tgtOrgDetails.getOrgName()).append("<br />")
                        .append(tgtOrgDetails.getAddress()).append(" ").append(tgtOrgDetails.getAddress2())
                        .append("<br />").append(tgtOrgDetails.getCity()).append(" ")
                        .append(tgtOrgDetails.getState()).append(",").append(tgtOrgDetails.getPostalCode())
                        .toString();

                targetDetails.setOrgDetails(OrgDetails);

                transactionList.add(targetDetails);
            }
        }

        mav.addObject("transactions", transactionList);

    } catch (Exception e) {
        throw new Exception(
                "(Admin) Error occurred viewing the all pending transactions. Error: " + e.getMessage(), e);
    }

    return mav;

}

From source file:com.ut.healthelink.controller.adminProcessingActivity.java

/**
 * The '/pending/{orgId}' GET method will return all pending output transactions based on the the passed in organization Id. The will return pending transactions grouped by message types for the passed in organziation
 *
 *
 *//*ww  w  . ja  va2 s .c o m*/
@RequestMapping(value = "/pending/messageTypes", method = RequestMethod.POST)
public ModelAndView viewOrgPendingMessages(@RequestParam(value = "orgId", required = true) int orgId)
        throws Exception {

    ModelAndView mav = new ModelAndView();
    mav.setViewName("/administrator/processing-activity/pendingByMessageType");

    mav.addObject("orgId", orgId);

    /* Get all waiting transactions */
    try {
        /* Need to get a list of all uploaded batches */
        Integer totaltransactions = 0;
        List batchTransactions = transactionOutManager.getTransactionsToProcessByMessageType(orgId);

        List<pendingDeliveryTargets> transactionList = new ArrayList<pendingDeliveryTargets>();

        if (!batchTransactions.isEmpty()) {
            for (ListIterator iter = batchTransactions.listIterator(); iter.hasNext();) {

                Object[] row = (Object[]) iter.next();

                /* Get the target Org */
                Organization tgtOrgDetails = organizationmanager
                        .getOrganizationById(Integer.valueOf(Integer.parseInt(String.valueOf(row[0]))));

                pendingDeliveryTargets targetDetails = new pendingDeliveryTargets();
                targetDetails.setOrgId(tgtOrgDetails.getId());
                targetDetails.setTotalPending(Integer.valueOf(Integer.parseInt(String.valueOf(row[3]))));

                String OrgDetails = new StringBuilder().append(tgtOrgDetails.getOrgName()).append("<br />")
                        .append(tgtOrgDetails.getAddress()).append(" ").append(tgtOrgDetails.getAddress2())
                        .append("<br />").append(tgtOrgDetails.getCity()).append(" ")
                        .append(tgtOrgDetails.getState()).append(",").append(tgtOrgDetails.getPostalCode())
                        .toString();

                targetDetails.setOrgDetails(OrgDetails);

                targetDetails.setMessageType(String.valueOf(row[1]));
                targetDetails.setMessageTypeId(Integer.valueOf(Integer.parseInt(String.valueOf(row[2]))));

                transactionList.add(targetDetails);
            }

            mav.addObject("transactions", transactionList);
        }

    } catch (Exception e) {
        throw new Exception(
                "(Admin) Error occurred viewing the all pending transactions. Error: " + e.getMessage(), e);
    }

    return mav;

}

From source file:com.ichi2.libanki.Sched.java

private List<DeckDueTreeNode> _groupChildrenMain(List<DeckDueTreeNode> grps) {
    List<DeckDueTreeNode> tree = new ArrayList<DeckDueTreeNode>();
    // group and recurse
    ListIterator<DeckDueTreeNode> it = grps.listIterator();
    while (it.hasNext()) {
        DeckDueTreeNode node = it.next();
        String head = node.names[0];
        // Compose the "tail" node list. The tail is a list of all the nodes that proceed
        // the current one that contain the same name[0]. I.e., they are subdecks that stem
        // from this node. This is our version of python's itertools.groupby.
        List<DeckDueTreeNode> tail = new ArrayList<DeckDueTreeNode>();
        tail.add(node);//from www . j  a v a 2  s.com
        while (it.hasNext()) {
            DeckDueTreeNode next = it.next();
            if (head.equals(next.names[0])) {
                // Same head - add to tail of current head.
                tail.add(next);
            } else {
                // We've iterated past this head, so step back in order to use this node as the
                // head in the next iteration of the outer loop.
                it.previous();
                break;
            }
        }
        Long did = null;
        int rev = 0;
        int _new = 0;
        int lrn = 0;
        List<DeckDueTreeNode> children = new ArrayList<DeckDueTreeNode>();
        for (DeckDueTreeNode c : tail) {
            if (c.names.length == 1) {
                // current node
                did = c.did;
                rev += c.revCount;
                lrn += c.lrnCount;
                _new += c.newCount;
            } else {
                // set new string to tail
                String[] newTail = new String[c.names.length - 1];
                System.arraycopy(c.names, 1, newTail, 0, c.names.length - 1);
                c.names = newTail;
                children.add(c);
            }
        }
        children = _groupChildrenMain(children);
        // tally up children counts
        for (DeckDueTreeNode ch : children) {
            rev += ch.revCount;
            lrn += ch.lrnCount;
            _new += ch.newCount;
        }
        // limit the counts to the deck's limits
        JSONObject conf = mCol.getDecks().confForDid(did);
        JSONObject deck = mCol.getDecks().get(did);
        try {
            if (conf.getInt("dyn") == 0) {
                rev = Math.max(0, Math.min(rev,
                        conf.getJSONObject("rev").getInt("perDay") - deck.getJSONArray("revToday").getInt(1)));
                _new = Math.max(0, Math.min(_new,
                        conf.getJSONObject("new").getInt("perDay") - deck.getJSONArray("newToday").getInt(1)));
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        tree.add(new DeckDueTreeNode(head, did, rev, lrn, _new, children));
    }
    return tree;
}

From source file:de.tudarmstadt.ukp.csniper.webapp.evaluation.EvaluationRepository.java

/**
 * Persist the given results. If they already exist in the database, replace the result in the
 * list with the result from the database. Transient data (e.g. match offsets) is preserved.
 *///from  w w  w .j av  a2 s  . c  o m
@Transactional
public void writeEvaluationResults(List<EvaluationResult> aResults) {
    long start = System.currentTimeMillis();

    Set<String> users = new HashSet<String>();
    for (EvaluationResult r : aResults) {
        users.add(r.getUserId());
    }

    for (String user : users) {
        // Build index on in-memory results
        log.info("Building index on in-memory results (" + aResults.size() + " results)");
        List<Long> itemIds = new ArrayList<Long>(aResults.size());
        for (EvaluationResult r : aResults) {
            if (user.equals(r.getUserId())) {
                itemIds.add(r.getItem().getId());
            }
        }

        // Build index on persisted results
        TypedQuery<EvaluationResult> query = entityManager.createQuery(
                "FROM EvaluationResult WHERE userId = :userId AND item_id in (:itemIds)",
                EvaluationResult.class);
        query.setParameter("userId", user);
        LongKeyOpenHashMap pResults = new LongKeyOpenHashMap(aResults.size());
        if (itemIds.size() > 0) {
            // Big Performance problem with setParameterList()
            // https://hibernate.onjira.com/browse/HHH-766
            int chunkSize = 500;
            log.info("Fetching in-database results in "
                    + ((aResults.size() / chunkSize) + (aResults.size() % chunkSize == 0 ? 0 : 1)) + " chunks");
            for (int i = 0; i < itemIds.size(); i += chunkSize) {
                query.setParameter("itemIds", itemIds.subList(i, Math.min(i + chunkSize, itemIds.size())));
                List<EvaluationResult> pr = query.getResultList();
                for (EvaluationResult r : pr) {
                    pResults.put(r.getItem().getId(), r);
                }
            }
        }

        // Merge information from the database
        log.info("Merging");
        for (ListIterator<EvaluationResult> li = aResults.listIterator(); li.hasNext();) {
            EvaluationResult mResult = li.next();

            // only replace for current user
            if (!mResult.getUserId().equals(user)) {
                continue;
            }

            EvaluationResult pResult = (EvaluationResult) pResults.get(mResult.getItem().getId());
            if (pResult != null) {
                // if result already exists, use that instead of persisting the new
                pResult.getItem().copyTransientData(mResult.getItem());
                li.set(pResult);
            } else if (mResult.getId() != 0) {
                li.set(entityManager.merge(mResult));
            } else {
                // if results does not exist, persist it
                entityManager.persist(mResult);
            }
        }
    }

    log.info("writeEvaluationResults for " + aResults.size() + " items completed in "
            + (System.currentTimeMillis() - start) + " ms");
}

From source file:io.apiman.manager.api.es.EsStorage.java

/**
 * @see io.apiman.manager.api.core.IStorage#reorderPolicies(io.apiman.manager.api.beans.policies.PolicyType, java.lang.String, java.lang.String, java.lang.String, java.util.List)
 *///from  ww w.j ava  2 s .c o m
@Override
public void reorderPolicies(PolicyType type, String organizationId, String entityId, String entityVersion,
        List<Long> newOrder) throws StorageException {
    String docType = getPoliciesDocType(type);
    String pid = id(organizationId, entityId, entityVersion);
    Map<String, Object> source = getEntity(docType, pid);
    if (source == null) {
        return;
    }
    PoliciesBean policiesBean = EsMarshalling.unmarshallPolicies(source);
    List<PolicyBean> policies = policiesBean.getPolicies();
    List<PolicyBean> reordered = new ArrayList<>(policies.size());
    for (Long policyId : newOrder) {
        ListIterator<PolicyBean> iterator = policies.listIterator();
        while (iterator.hasNext()) {
            PolicyBean policyBean = iterator.next();
            if (policyBean.getId().equals(policyId)) {
                iterator.remove();
                reordered.add(policyBean);
                break;
            }
        }
    }
    // Make sure we don't stealth-delete any policies.  Put anything
    // remaining at the end of the list.
    for (PolicyBean policyBean : policies) {
        reordered.add(policyBean);
    }
    policiesBean.setPolicies(reordered);
    updateEntity(docType, pid, EsMarshalling.marshall(policiesBean));
}