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:org.dspace.app.dav.DAVResource.java

/**
 * Propfind crawler./*from  www .j a va 2  s . c o m*/
 * 
 * @param multistatus the multistatus
 * @param pfType the pf type
 * @param pfProps the pf props
 * @param depth the depth
 * @param typeMask the type mask
 * @param count the count
 * 
 * @return the int
 * 
 * @throws DAVStatusException the DAV status exception
 * @throws SQLException the SQL exception
 * @throws AuthorizeException the authorize exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
private int propfindCrawler(Element multistatus, int pfType, List<Element> pfProps, int depth, int typeMask,
        int count) throws DAVStatusException, SQLException, AuthorizeException, IOException {
    if ((this.type & typeMask) != 0 || this.type == TYPE_OTHER) {
        // check the count of resources visited
        ++count;
        if (propfindResourceLimit > 0 && count > propfindResourceLimit) {
            throw new DAVStatusException(HttpServletResponse.SC_CONFLICT,
                    "PROPFIND request exceeded server's limit on number of resources to query.");
        }

        String uri = hrefURL();
        log.debug("PROPFIND returning (count=" + String.valueOf(count) + ") href=" + uri);
        List<Element> notFound = new ArrayList<Element>();
        List<Element> forbidden = new ArrayList<Element>();
        Element responseElt = new Element("response", DAV.NS_DAV);
        multistatus.addContent(responseElt);

        Element href = new Element("href", DAV.NS_DAV);
        href.setText(uri);
        responseElt.addContent(href);

        // just get the names
        if (pfType == DAV.PROPFIND_PROPNAME) {
            responseElt.addContent(
                    makePropstat(copyElementList(getAllProperties()), HttpServletResponse.SC_OK, "OK"));
        } else {
            List<Element> success = new LinkedList<Element>();
            List<Element> props = (pfType == DAV.PROPFIND_ALLPROP) ? getAllProperties() : pfProps;
            ListIterator pi = props.listIterator();
            while (pi.hasNext()) {
                Element property = (Element) pi.next();
                try {
                    Element value = propfindInternal(property);
                    if (value != null) {
                        success.add(value);
                    } else {
                        notFound.add((Element) property.clone());
                    }
                } catch (DAVStatusException se) {
                    if (se.getStatus() == HttpServletResponse.SC_NOT_FOUND) {
                        notFound.add((Element) property.clone());
                    } else {
                        responseElt.addContent(
                                makePropstat((Element) property.clone(), se.getStatus(), se.getMessage()));
                    }
                } catch (AuthorizeException ae) {
                    forbidden.add((Element) property.clone());
                }
            }

            if (success.size() > 0) {
                responseElt.addContent(makePropstat(success, HttpServletResponse.SC_OK, "OK"));
            }
            if (notFound.size() > 0) {
                responseElt.addContent(makePropstat(notFound, HttpServletResponse.SC_NOT_FOUND, "Not found"));
            }
            if (forbidden.size() > 0) {
                responseElt.addContent(
                        makePropstat(forbidden, HttpServletResponse.SC_FORBIDDEN, "Not authorized."));
            }
        }
    }

    // recurse on children; filter on types first.
    // child types are all lower bits than this type, so (type - 1) is
    // bit-mask of all the possible child types. Skip recursion if
    // all child types would be masked out anyway.
    if (depth != 0 && ((this.type - 1) & typeMask) != 0) {
        DAVResource[] kids = children();
        for (DAVResource element : kids) {
            count = element.propfindCrawler(multistatus, pfType, pfProps,
                    depth == DAV.DAV_INFINITY ? depth : depth - 1, typeMask, count);
        }
    }

    return count;
}

From source file:org.apache.ofbiz.shipment.thirdparty.usps.UspsServices.java

public static Map<String, Object> uspsInternationalRateInquire(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId");
    String resource = (String) context.get("configProps");
    Locale locale = (Locale) context.get("locale");

    // check for 0 weight
    BigDecimal shippableWeight = (BigDecimal) context.get("shippableWeight");
    if (shippableWeight.compareTo(BigDecimal.ZERO) == 0) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsShippableWeightMustGreaterThanZero", locale));
    }/*from  w ww  .j a  va2  s  .c o  m*/

    // get the destination country
    String destinationCountry = null;
    String shippingContactMechId = (String) context.get("shippingContactMechId");
    if (UtilValidate.isNotEmpty(shippingContactMechId)) {
        try {
            GenericValue shipToAddress = EntityQuery.use(delegator).from("PostalAddress")
                    .where("contactMechId", shippingContactMechId).queryOne();
            if (domesticCountries.contains(shipToAddress.get("countryGeoId"))) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsRateInternationCannotBeUsedForUsDestinations", locale));
            }
            if (shipToAddress != null && UtilValidate.isNotEmpty(shipToAddress.getString("countryGeoId"))) {
                GenericValue countryGeo = shipToAddress.getRelatedOne("CountryGeo", false);
                // TODO: Test against all country geoNames against what USPS expects
                destinationCountry = countryGeo.getString("geoName");
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (UtilValidate.isEmpty(destinationCountry)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineDestinationCountry", locale));
    }

    // get the service code
    String serviceCode = null;
    try {
        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod")
                .where("shipmentMethodTypeId", (String) context.get("shipmentMethodTypeId"), "partyId",
                        (String) context.get("carrierPartyId"), "roleTypeId",
                        (String) context.get("carrierRoleTypeId"))
                .queryOne();
        if (carrierShipmentMethod != null) {
            serviceCode = carrierShipmentMethod.getString("carrierServiceCode");
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    if (UtilValidate.isEmpty(serviceCode)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineServiceCode", locale));
    }

    BigDecimal maxWeight = new BigDecimal("70");
    String maxWeightStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "maxEstimateWeight",
            resource, "shipment.usps.max.estimate.weight", "70");
    try {
        maxWeight = new BigDecimal(maxWeightStr);
    } catch (NumberFormatException e) {
        Debug.logWarning(
                "Error parsing max estimate weight string [" + maxWeightStr + "], using default instead",
                module);
        maxWeight = new BigDecimal("70");
    }

    List<Map<String, Object>> shippableItemInfo = UtilGenerics.checkList(context.get("shippableItemInfo"));
    List<Map<String, BigDecimal>> packages = ShipmentWorker.getPackageSplit(dctx, shippableItemInfo, maxWeight);
    boolean isOnePackage = packages.size() == 1; // use shippableWeight if there's only one package

    // create the request document
    Document requestDocument = createUspsRequestDocument("IntlRateRequest", false, delegator,
            shipmentGatewayConfigId, resource);

    // TODO: Up to 25 packages can be included per request - handle more than 25
    for (ListIterator<Map<String, BigDecimal>> li = packages.listIterator(); li.hasNext();) {
        Map<String, BigDecimal> packageMap = li.next();

        Element packageElement = UtilXml.addChildElement(requestDocument.getDocumentElement(), "Package",
                requestDocument);
        packageElement.setAttribute("ID", String.valueOf(li.nextIndex() - 1)); // use zero-based index (see examples)

        BigDecimal packageWeight = isOnePackage ? shippableWeight
                : ShipmentWorker.calcPackageWeight(dctx, packageMap, shippableItemInfo, BigDecimal.ZERO);
        if (packageWeight.compareTo(BigDecimal.ZERO) == 0) {
            continue;
        }
        Integer[] weightPoundsOunces = convertPoundsToPoundsOunces(packageWeight);
        // for Parcel post, the weight must be at least 1 lb
        if ("PARCEL".equals(serviceCode.toUpperCase()) && (weightPoundsOunces[0] < 1)) {
            weightPoundsOunces[0] = 1;
            weightPoundsOunces[1] = 0;
        }
        UtilXml.addChildElementValue(packageElement, "Pounds", weightPoundsOunces[0].toString(),
                requestDocument);
        UtilXml.addChildElementValue(packageElement, "Ounces", weightPoundsOunces[1].toString(),
                requestDocument);

        UtilXml.addChildElementValue(packageElement, "Machinable", "False", requestDocument);
        UtilXml.addChildElementValue(packageElement, "MailType", "Package", requestDocument);

        // TODO: Add package value so that an insurance fee can be returned

        UtilXml.addChildElementValue(packageElement, "Country", destinationCountry, requestDocument);
    }

    // send the request
    Document responseDocument = null;
    try {
        responseDocument = sendUspsRequest("IntlRate", requestDocument, delegator, shipmentGatewayConfigId,
                resource, locale);
    } catch (UspsRequestException e) {
        Debug.logInfo(e, module);
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateInternationalSendingError",
                        UtilMisc.toMap("errorString", e.getMessage()), locale));
    }

    if (responseDocument == null) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale));
    }

    List<? extends Element> packageElements = UtilXml.childElementList(responseDocument.getDocumentElement(),
            "Package");
    if (UtilValidate.isEmpty(packageElements)) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale));
    }

    BigDecimal estimateAmount = BigDecimal.ZERO;
    for (Element packageElement : packageElements) {
        Element errorElement = UtilXml.firstChildElement(packageElement, "Error");
        if (errorElement != null) {
            String errorDescription = UtilXml.childElementValue(errorElement, "Description");
            Debug.logInfo("USPS International Rate Calculation returned a package error: " + errorDescription,
                    module);
            return ServiceUtil.returnError(
                    UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale));
        }
        List<? extends Element> serviceElements = UtilXml.childElementList(packageElement, "Service");
        for (Element serviceElement : serviceElements) {
            String respServiceCode = serviceElement.getAttribute("ID");
            if (!serviceCode.equalsIgnoreCase(respServiceCode)) {
                continue;
            }
            try {
                BigDecimal packageAmount = new BigDecimal(UtilXml.childElementValue(serviceElement, "Postage"));
                estimateAmount = estimateAmount.add(packageAmount);
            } catch (NumberFormatException e) {
                Debug.logInfo("USPS International Rate Calculation returned an unparsable postage amount: "
                        + UtilXml.childElementValue(serviceElement, "Postage"), module);
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale));
            }
        }
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("shippingEstimateAmount", estimateAmount);
    return result;
}

From source file:org.apache.fop.layoutmgr.inline.LineLayoutManager.java

private void processUpdates(Paragraph par, List updateList) {
    // create iterator for the updateList
    ListIterator updateListIterator = updateList.listIterator();
    Update currUpdate;/* ww  w. j  ava2s.  c om*/
    int elementsAdded = 0;

    while (updateListIterator.hasNext()) {
        // ask the LMs to apply the changes and return
        // the new KnuthElements to replace the old ones
        currUpdate = (Update) updateListIterator.next();
        int fromIndex = currUpdate.firstIndex;
        int toIndex;
        if (updateListIterator.hasNext()) {
            Update nextUpdate = (Update) updateListIterator.next();
            toIndex = nextUpdate.firstIndex;
            updateListIterator.previous();
        } else {
            // maybe this is not always correct!
            toIndex = par.size() - par.ignoreAtEnd - elementsAdded;
        }

        // applyChanges() returns true if the LM modifies its data,
        // so it must return new KnuthElements to replace the old ones
        if (currUpdate.inlineLM.applyChanges(par.subList(fromIndex + elementsAdded, toIndex + elementsAdded))) {
            // insert the new KnuthElements
            List newElements = currUpdate.inlineLM.getChangedKnuthElements(
                    par.subList(fromIndex + elementsAdded, toIndex + elementsAdded),
                    /*flaggedPenalty,*/ effectiveAlignment);
            // remove the old elements
            par.subList(fromIndex + elementsAdded, toIndex + elementsAdded).clear();
            // insert the new elements
            par.addAll(fromIndex + elementsAdded, newElements);
            elementsAdded += newElements.size() - (toIndex - fromIndex);
        }
    }
    updateList.clear();
}

From source file:gov.nih.nci.ncicb.cadsr.contexttree.service.impl.CDEBrowserTreeServiceImpl.java

/**
 * @returns a Context holder that contains a contect object and context we node
 *//*w  w  w. j  ava 2s .co m*/
public List getContextNodeHolders(TreeFunctions treeFunctions, TreeIdGenerator idGen, String excludeList)
        throws Exception {
    ContextDAO dao = daoFactory.getContextDAO();

    List contexts = dao.getAllContexts(excludeList);
    ListIterator it = contexts.listIterator();
    List holders = new ArrayList();

    while (it.hasNext()) {
        Context context = (Context) it.next();

        ContextHolder holder = new ContextHolderTransferObject();
        holder.setContext(context);
        holder.setNode(getContextNode(idGen.getNewId(), context, treeFunctions));
        holders.add(holder);
    }

    return holders;
}

From source file:org.easyrec.service.web.nodomain.impl.ShopRecommenderServiceImpl.java

@SuppressWarnings({ "unchecked" })
@IOLog/*from w w w . ja v  a  2 s . c o m*/
@Profiled
@Override
public List<Item> mostRatedItems(Integer tenantId, String itemType, Integer cluster, Integer numberOfResults,
        Integer offset, String timeRange, TimeConstraintVO constraint, Session session) {
    List<Item> items;
    offset = CollectionUtils.getSafeOffset(offset);
    RemoteTenant remoteTenant = remoteTenantDAO.get(tenantId);

    if (logger.isDebugEnabled()) {

        logger.debug("<MOST_RATED@" + remoteTenant.getStringId() + "> " + " requesting most rated Items");
    }

    if (timeRange == null) {
        timeRange = "ALL";
    } // default timeRange
    String cacheKey = tenantId + WS.ACTION_MOST_RATED + itemType + cluster + timeRange;
    Element e = cache.get(cacheKey);
    if ((e != null) && (!e.isExpired())) {
        items = itemService.filterDeactivatedItems((List<Item>) e.getValue());
        return CollectionUtils.getSafeSubList(items, offset, numberOfResults);
    }
    if (constraint == null)
        constraint = new TimeConstraintVO();
    adjustConstraint(constraint, TimeRange.getEnumFromString(timeRange));

    Monitor monCore = MonitorFactory.start(JAMON_REST_MOST_RATED_CORE);

    List<RankedItemVO<Integer, String>> rankedItems = domainActionService.mostRatedItems(tenantId, itemType,
            cluster, WS.MAX_NUMBER_OF_RANKING_RESULTS, constraint, Boolean.TRUE);

    // filter invisible items
    Set<String> invisibleItemTypes = typeMappingService.getItemTypes(tenantId, false);

    if (invisibleItemTypes.size() > 0) {
        ListIterator<RankedItemVO<Integer, String>> iterator = rankedItems.listIterator();

        while (iterator.hasNext()) {
            RankedItemVO<Integer, String> rankedItemVO = iterator.next();

            if (invisibleItemTypes.contains(rankedItemVO.getItem().getType()))
                iterator.remove();
        }
    }

    monCore.stop();

    items = idMappingService.mapRankedItems(rankedItems, remoteTenant, session,
            WS.MAX_NUMBER_OF_RANKING_RESULTS, 0);

    cache.put(new Element(cacheKey, items));
    return CollectionUtils.getSafeSubList(items, offset, numberOfResults);
}

From source file:org.easyrec.service.web.nodomain.impl.ShopRecommenderServiceImpl.java

@SuppressWarnings({ "unchecked" })
@IOLog//w ww.j  a  va 2 s .  co m
@Profiled
@Override
public List<Item> mostBoughtItems(Integer tenantId, String itemType, Integer cluster, Integer numberOfResults,
        Integer offset, String timeRange, TimeConstraintVO constraint, Session session) {
    List<Item> items;
    offset = CollectionUtils.getSafeOffset(offset);
    RemoteTenant remoteTenant = remoteTenantDAO.get(tenantId);

    if (logger.isDebugEnabled()) {

        logger.debug("<MOST_BOUGHT@" + remoteTenant.getStringId() + "> " + " requesting most bought Items");
    }

    if (timeRange == null) {
        timeRange = "ALL";
    } // default timeRange
    String cacheKey = tenantId + WS.ACTION_MOST_BOUGHT + itemType + cluster + timeRange;
    Element e = cache.get(cacheKey);
    if ((e != null) && (!e.isExpired())) {
        items = itemService.filterDeactivatedItems((List<Item>) e.getValue());
        return CollectionUtils.getSafeSubList(items, offset, numberOfResults);
    }
    if (constraint == null)
        constraint = new TimeConstraintVO();
    adjustConstraint(constraint, TimeRange.getEnumFromString(timeRange));

    Monitor monCore = MonitorFactory.start(JAMON_REST_MOST_BOUGHT_CORE);

    List<RankedItemVO<Integer, String>> rankedItems = domainActionService.mostBoughtItems(tenantId, itemType,
            cluster, WS.MAX_NUMBER_OF_RANKING_RESULTS, constraint, Boolean.TRUE);

    // filter invisible items
    Set<String> invisibleItemTypes = typeMappingService.getItemTypes(tenantId, false);

    if (invisibleItemTypes.size() > 0) {
        ListIterator<RankedItemVO<Integer, String>> iterator = rankedItems.listIterator();

        while (iterator.hasNext()) {
            RankedItemVO<Integer, String> rankedItemVO = iterator.next();

            if (invisibleItemTypes.contains(rankedItemVO.getItem().getType()))
                iterator.remove();
        }
    }

    monCore.stop();

    items = idMappingService.mapRankedItems(rankedItems, remoteTenant, session,
            WS.MAX_NUMBER_OF_RANKING_RESULTS, 0);

    cache.put(new Element(cacheKey, items));
    return CollectionUtils.getSafeSubList(items, offset, numberOfResults);
}

From source file:org.easyrec.service.web.nodomain.impl.ShopRecommenderServiceImpl.java

@SuppressWarnings({ "unchecked" })
@IOLog/*from   w  ww  .j ava  2s .  c om*/
@Profiled
@Override
public List<Item> mostViewedItems(Integer tenantId, String itemType, Integer cluster, Integer numberOfResults,
        Integer offset, String timeRange, TimeConstraintVO constraint, Session session) {
    List<Item> items;
    offset = CollectionUtils.getSafeOffset(offset);
    RemoteTenant remoteTenant = remoteTenantDAO.get(tenantId);

    if (logger.isDebugEnabled()) {

        logger.debug("<MOST_VIEWED@" + remoteTenant.getStringId() + "> " + " requesting most viewed Items");
    }

    if (timeRange == null) {
        timeRange = "ALL";
    } // default timeRange
    String cacheKey = tenantId + WS.ACTION_MOST_VIEWED + itemType + cluster + timeRange;
    Element e = cache.get(cacheKey);
    if ((e != null) && (!e.isExpired())) {
        logger.debug("most viewed - cache hit");
        items = itemService.filterDeactivatedItems((List<Item>) e.getValue());
        return CollectionUtils.getSafeSubList(items, offset, numberOfResults);
    }
    if (constraint == null)
        constraint = new TimeConstraintVO();
    adjustConstraint(constraint, TimeRange.getEnumFromString(timeRange));

    logger.debug("most viewed - cache miss - fetching new data from db");
    Monitor monCore = MonitorFactory.start(JAMON_REST_MOST_VIEWED_CORE);
    List<RankedItemVO<Integer, String>> rankedItems = domainActionService.mostViewedItems(tenantId, itemType,
            cluster, WS.MAX_NUMBER_OF_RANKING_RESULTS, constraint, Boolean.TRUE);

    // filter invisible items
    Set<String> invisibleItemTypes = typeMappingService.getItemTypes(tenantId, false);

    if (invisibleItemTypes.size() > 0) {
        ListIterator<RankedItemVO<Integer, String>> iterator = rankedItems.listIterator();

        while (iterator.hasNext()) {
            RankedItemVO<Integer, String> rankedItemVO = iterator.next();

            if (invisibleItemTypes.contains(rankedItemVO.getItem().getType()))
                iterator.remove();
        }
    }

    monCore.stop();

    items = idMappingService.mapRankedItems(rankedItems, remoteTenant, session,
            WS.MAX_NUMBER_OF_RANKING_RESULTS, 0);

    cache.put(new Element(cacheKey, items));
    return CollectionUtils.getSafeSubList(items, offset, numberOfResults);
}

From source file:org.easyrec.service.web.nodomain.impl.ShopRecommenderServiceImpl.java

@SuppressWarnings({ "unchecked" })
@IOLog/*w w  w .j a  v  a 2  s. c o  m*/
@Profiled
@Override
public List<Item> worstRatedItems(Integer tenantId, String userId, String itemType, Integer numberOfResults,
        Integer offset, String timeRange, TimeConstraintVO constraint, Session session) {
    List<Item> items;
    offset = CollectionUtils.getSafeOffset(offset);
    RemoteTenant remoteTenant = remoteTenantDAO.get(tenantId);

    if (logger.isDebugEnabled()) {

        logger.debug("<WORST_RATED@" + remoteTenant.getStringId() + "> " + " requesting worst rated Items");
    }

    if (timeRange == null) {
        timeRange = "ALL";
    } // default timeRange
    if (userId == null) {
        Element e = cache.get(tenantId + WS.ACTION_WORST_RATED + itemType + timeRange);
        if ((e != null) && (!e.isExpired())) {
            items = itemService.filterDeactivatedItems((List<Item>) e.getValue());
            return CollectionUtils.getSafeSubList(items, offset, numberOfResults);
        }
        if (constraint == null)
            constraint = new TimeConstraintVO();
        adjustConstraint(constraint, TimeRange.getEnumFromString(timeRange));
    }

    Monitor monCore = MonitorFactory.start(JAMON_REST_WORST_RATED_CORE);

    List<RatingVO<Integer, String>> ratedItems = domainActionService.badItemRatings(tenantId,
            idMappingDAO.lookup(userId), null, itemType, WS.MAX_NUMBER_OF_RANKING_RESULTS, constraint);

    // filter invisible items
    Set<String> invisibleItemTypes = typeMappingService.getItemTypes(tenantId, false);

    if (invisibleItemTypes.size() > 0) {
        ListIterator<RatingVO<Integer, String>> iterator = ratedItems.listIterator();

        while (iterator.hasNext()) {
            RatingVO<Integer, String> ratingVO = iterator.next();

            if (invisibleItemTypes.contains(ratingVO.getItem().getType()))
                iterator.remove();
        }
    }

    monCore.stop();

    items = idMappingService.mapRatedItems(ratedItems, remoteTenant, session, WS.MAX_NUMBER_OF_RANKING_RESULTS,
            0);

    if ((userId == null))
        cache.put(new Element(tenantId + WS.ACTION_WORST_RATED + itemType + timeRange, items));
    return CollectionUtils.getSafeSubList(items, offset, numberOfResults);
}

From source file:org.easyrec.service.web.nodomain.impl.ShopRecommenderServiceImpl.java

@SuppressWarnings({ "unchecked" })
@IOLog/*from w  w  w .j a  v  a2s.  c o m*/
@Profiled
@Override
public List<Item> bestRatedItems(Integer tenantId, String userId, String itemType, Integer numberOfResults,
        Integer offset, String timeRange, TimeConstraintVO constraint, Session session) {
    List<Item> items;
    offset = CollectionUtils.getSafeOffset(offset);
    RemoteTenant remoteTenant = remoteTenantDAO.get(tenantId);

    if (logger.isDebugEnabled()) {

        logger.debug("<BEST_RATED@" + remoteTenant.getStringId() + "> " + " requesting best rated Items");
    }

    if (timeRange == null) {
        timeRange = "ALL";
    } // default timeRange
    if (userId == null) {
        Element e = cache.get(tenantId + WS.ACTION_BEST_RATED + itemType + timeRange);
        if ((e != null) && (!e.isExpired())) {
            items = itemService.filterDeactivatedItems((List<Item>) e.getValue());
            return CollectionUtils.getSafeSubList(items, offset, numberOfResults);
        }
        if (constraint == null)
            constraint = new TimeConstraintVO();
        adjustConstraint(constraint, TimeRange.getEnumFromString(timeRange));
    }

    Monitor monCore = MonitorFactory.start(JAMON_REST_BEST_RATED_CORE);

    List<RatingVO<Integer, String>> ratedItems = domainActionService.goodItemRatings(tenantId,
            idMappingDAO.lookup(userId), null, itemType, WS.MAX_NUMBER_OF_RANKING_RESULTS, constraint);

    // filter invisible items
    Set<String> invisibleItemTypes = typeMappingService.getItemTypes(tenantId, false);

    if (invisibleItemTypes.size() > 0) {
        ListIterator<RatingVO<Integer, String>> iterator = ratedItems.listIterator();

        while (iterator.hasNext()) {
            RatingVO<Integer, String> ratingVO = iterator.next();

            if (invisibleItemTypes.contains(ratingVO.getItem().getType()))
                iterator.remove();
        }
    }

    monCore.stop();

    items = idMappingService.mapRatedItems(ratedItems, remoteTenant, session, WS.MAX_NUMBER_OF_RANKING_RESULTS,
            0);

    if ((userId == null))
        cache.put(new Element(tenantId + WS.ACTION_BEST_RATED + itemType + timeRange, items));
    return CollectionUtils.getSafeSubList(items, offset, numberOfResults);
}

From source file:com.netflix.config.ConcurrentCompositeConfiguration.java

/**
 * Get a List of objects associated with the given configuration key.
 * If the key doesn't map to an existing object, the default value
 * is returned.//from   w w  w.ja  va 2  s.  c o  m
 *
 * @param key The configuration key.
 * @param defaultValue The default value.
 * @return The associated List of value.
 * 
 */
@Override
public List getList(String key, List defaultValue) {
    List<Object> list = new ArrayList<Object>();

    // add all elements from the first configuration containing the requested key
    Iterator<AbstractConfiguration> it = configList.iterator();
    if (overrideProperties.containsKey(key)) {
        appendListProperty(list, overrideProperties, key);
    }
    while (it.hasNext() && list.isEmpty()) {
        Configuration config = it.next();
        if ((config != containerConfiguration || containerConfigurationChanged) && config.containsKey(key)) {
            appendListProperty(list, config, key);
        }
    }

    // add all elements from the in memory configuration
    if (list.isEmpty()) {
        appendListProperty(list, containerConfiguration, key);
    }

    if (list.isEmpty()) {
        return defaultValue;
    }

    ListIterator<Object> lit = list.listIterator();
    while (lit.hasNext()) {
        lit.set(interpolate(lit.next()));
    }

    return list;
}