Example usage for java.util List retainAll

List of usage examples for java.util List retainAll

Introduction

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

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

Retains only the elements in this list that are contained in the specified collection (optional operation).

Usage

From source file:org.opendaylight.genius.itm.impl.ItmUtils.java

private static List<BigInteger> getConflictingDpnsAlreadyConfiguredWithTz(String schemaName, String tzone,
        List<BigInteger> lstDpns, List<VtepConfigSchema> existingSchemas) {
    List<BigInteger> lstConflictingDpns = new ArrayList<>();
    for (VtepConfigSchema schema : emptyIfNull(existingSchemas)) {
        if (!StringUtils.equalsIgnoreCase(schemaName, schema.getSchemaName())
                && StringUtils.equals(schema.getTransportZoneName(), tzone)) {
            lstConflictingDpns = new ArrayList<>(getDpnIdList(schema.getDpnIds()));
            lstConflictingDpns.retainAll(lstDpns);
            if (!lstConflictingDpns.isEmpty()) {
                break;
            }//from w  w  w.j a  v  a  2s  .c o  m
        }
    }
    return lstConflictingDpns;
}

From source file:org.yes.cart.service.payment.impl.PaymentModulesManagerImpl.java

private void filterOutDisabledPaymentGateways(final List<PaymentGatewayDescriptor> paymentGatewayDescriptors,
        final String[] allowed) {

    if (allowed != null && allowed.length > 0) {

        final List<String> enabled = Arrays.asList(allowed);

        final List<PaymentGatewayDescriptor> allowedDescr = new ArrayList<PaymentGatewayDescriptor>();
        for (final PaymentGatewayDescriptor descriptor : paymentGatewayDescriptors) {
            if (enabled.contains(descriptor.getLabel())) {
                allowedDescr.add(descriptor);
            }/* w  ww . j a  v a 2 s  . c om*/
        }
        paymentGatewayDescriptors.retainAll(allowedDescr);

    } else {

        paymentGatewayDescriptors.clear();

    }
}

From source file:org.slc.sli.api.security.OauthMongoSessionManager.java

/**
 * Generates the principal's edorg-context-rights map.
 * Traverses each edOrg's upward hierachy to combine all of the rights for each context.
 *
 * @param principal - The principal/*from  w  ww.j av a  2  s .c o m*/
 *
 * @return - Generated edorg-context-rights map for principal
 */
private EdOrgContextRightsCache generateEdOrgContextRightsCache(SLIPrincipal principal) {
    EdOrgContextRightsCache edOrgContextRights = new EdOrgContextRightsCache();
    if (principal.getEdOrgRoles() != null) {
        for (String edOrg : principal.getEdOrgRoles().keySet()) {
            Entity edOrgEntity = repo.findById(EDORG_COLLECTION, edOrg);
            List<String> hierarchicalEdOrgs = new ArrayList<String>(Arrays.asList(edOrg));
            hierarchicalEdOrgs.addAll(helper.getParentEdOrgs(edOrgEntity));
            hierarchicalEdOrgs.retainAll(principal.getEdOrgRoles().keySet());
            Map<String, Collection<GrantedAuthority>> contextRights = generateContextRightsForEdOrg(principal,
                    hierarchicalEdOrgs);
            edOrgContextRights.put(edOrg, contextRights);
        }
    }

    return edOrgContextRights;
}

From source file:org.talend.designer.core.generic.utils.ComponentsUtilsTest.java

@Test
public void testGetFormalPossibleValues() {
    ComponentService componentService = ComponentsUtils.getComponentService();
    ComponentProperties props = (ComponentProperties) new TestProperties("test").init(); //$NON-NLS-1$
    Form form = props.getForm(Form.MAIN);
    Element element = new FakeElement(form.getName());
    Widget testWidget = null;/*from   w  w  w  .  java 2 s .co  m*/
    Property testProperty = null;
    Collection<Widget> widgets = form.getWidgets();
    Iterator<Widget> widgetsIterator = widgets.iterator();
    while (widgetsIterator.hasNext()) {
        Widget widget = widgetsIterator.next();
        NamedThing content = widget.getContent();
        if (content instanceof Property) {
            testWidget = widget;
            testProperty = (Property) content;
            break;
        }
    }
    assertNotNull(testWidget);
    assertNotNull(testProperty);

    // Test NamedThing type
    List<NamedThing> namedThings = new ArrayList<>();
    namedThings.add(new SimpleNamedThing("p1", "Test P1"));
    namedThings.add(new SimpleNamedThing("p2", "Test P2"));
    namedThings.add(new SimpleNamedThing("p3", "Test P3"));
    testProperty.setPossibleValues(namedThings);

    GenericElementParameter param = new GenericElementParameter(element, props, form, testWidget,
            componentService);
    param.setPossibleValues(testProperty.getPossibleValues());
    List<NamedThing> possibleValues = ComponentsUtils.getFormalPossibleValues(param);
    assertEquals(3, possibleValues.size());
    namedThings.retainAll(possibleValues);
    assertEquals(3, namedThings.size());

    // Test Integer type which is not support yet
    List<Integer> ints = new ArrayList<>();
    ints.add(1);
    ints.add(2);
    ints.add(3);
    testProperty.setPossibleValues(ints);

    param = new GenericElementParameter(element, props, form, testWidget, componentService);
    param.setPossibleValues(testProperty.getPossibleValues());
    possibleValues = ComponentsUtils.getFormalPossibleValues(param);
    assertEquals(0, possibleValues.size());

    // Test StringProperty
    testWidget = null;
    StringProperty testStringProperty = null;
    widgetsIterator = widgets.iterator();
    while (widgetsIterator.hasNext()) {
        Widget widget = widgetsIterator.next();
        NamedThing content = widget.getContent();
        if (content instanceof StringProperty) {
            testWidget = widget;
            testStringProperty = (StringProperty) content;
            break;
        }
    }
    assertNotNull(testWidget);
    assertNotNull(testStringProperty);

    testStringProperty.setPossibleNamedThingValues(namedThings);
    param = new GenericElementParameter(element, props, form, testWidget, componentService);
    param.setPossibleValues(testStringProperty.getPossibleValues());
    possibleValues = ComponentsUtils.getFormalPossibleValues(param);
    assertEquals(3, possibleValues.size());
    List<String> pvNames = new ArrayList<>();
    for (NamedThing pv : possibleValues) {
        pvNames.add(pv.getName());
    }
    for (NamedThing nt : namedThings) {
        assertTrue(pvNames.contains(nt.getName()));
    }
}

From source file:org.opendaylight.netvirt.dhcpservice.DhcpExternalTunnelManager.java

/**
 * Choose a dpn among the list of elanDpns such that it has lowest count of being the designated dpn.
 * @param tunnelIp The tunnel Ip address
 * @param elanInstanceName The elan instance name
 * @param dpns The data path nodes/*  ww w.ja v  a2s  .  c  o  m*/
 * @return The designated dpn
 */
private BigInteger chooseDpn(IpAddress tunnelIp, String elanInstanceName, List<BigInteger> dpns) {
    BigInteger designatedDpnId = DhcpMConstants.INVALID_DPID;
    if (dpns != null && dpns.size() != 0) {
        List<BigInteger> candidateDpns = DhcpServiceUtils.getDpnsForElan(elanInstanceName, broker);
        candidateDpns.retainAll(dpns);
        LOG.trace("Choosing new dpn for tunnelIp {}, elanInstanceName {}, among elanDpns {}", tunnelIp,
                elanInstanceName, candidateDpns);
        boolean elanDpnAvailableFlag = true;
        if (candidateDpns == null || candidateDpns.isEmpty()) {
            candidateDpns = dpns;
            elanDpnAvailableFlag = false;
        }
        int size = 0;
        L2GatewayDevice device = getDeviceFromTunnelIp(elanInstanceName, tunnelIp);
        if (device == null) {
            LOG.trace("Could not find any device for elanInstanceName {} and tunnelIp {}", elanInstanceName,
                    tunnelIp);
            handleUnableToDesignateDpn(tunnelIp, elanInstanceName);
            return designatedDpnId;
        }
        for (BigInteger dpn : candidateDpns) {
            String hwvtepNodeId = device.getHwvtepNodeId();
            if (!elanDpnAvailableFlag) {
                if (!isTunnelConfigured(dpn, hwvtepNodeId)) {
                    LOG.trace("Tunnel is not configured on dpn {} to TOR {}", dpn, hwvtepNodeId);
                    continue;
                }
            } else if (!isTunnelUp(hwvtepNodeId, dpn)) {
                LOG.trace("Tunnel is not up between dpn {} and TOR {}", dpn, hwvtepNodeId);
                continue;
            }
            Set<Pair<IpAddress, String>> tunnelIpElanNameSet = designatedDpnsToTunnelIpElanNameCache.get(dpn);
            if (tunnelIpElanNameSet == null) {
                designatedDpnId = dpn;
                break;
            }
            if (size == 0 || tunnelIpElanNameSet.size() < size) {
                size = tunnelIpElanNameSet.size();
                designatedDpnId = dpn;
            }
        }
        writeDesignatedSwitchForExternalTunnel(designatedDpnId, tunnelIp, elanInstanceName);
        return designatedDpnId;
    }
    handleUnableToDesignateDpn(tunnelIp, elanInstanceName);
    return designatedDpnId;
}

From source file:org.mindswap.pellet.taxonomy.Taxonomy.java

/**
 * Given a list of concepts, find all the Least Common Ancestors (LCA). Note that a taxonomy
 * is DAG not a tree so we do not have a unique LCA but a set of LCA. The function might
 * return a singleton list that contains TOP if there are no lower level nodes that
 * satisfy the LCA condition.//from  w  w  w .j a  v  a2s  .co  m
 * 
 * @param names
 * @return
 */
public List computeLCA(ATermList list) {
    // TODO this function can probably be improved 

    // get the first concept
    ATermAppl c = (ATermAppl) list.getFirst();

    // add all its ancestor as possible LCA candidates
    List ancestors = new ArrayList(getSupers(c, true, true));

    for (; !list.isEmpty(); list = list.getNext()) {
        c = (ATermAppl) list.getFirst();

        // take the intersection of possible candidates to get rid of uncommon ancestors
        ancestors.retainAll(getSupers(c, true, true));

        // we hit TOP so no need to continue
        if (ancestors.size() == 1) {
            ATermUtils.assertTrue(ancestors.contains(ATermUtils.TOP));
            return ancestors;
        }
    }

    // we have all common ancestors now remove the ones that have descendants in the list
    for (int j = 0; j < ancestors.size(); j++) {
        c = (ATermAppl) ancestors.get(j);
        ancestors.removeAll(getSupers(c, true, true));
    }

    return ancestors;
}

From source file:org.apache.hyracks.algebricks.core.algebra.operators.physical.AbstractPreclusteredGroupByPOperator.java

@Override
public PhysicalRequirements getRequiredPropertiesForChildren(ILogicalOperator op,
        IPhysicalPropertiesVector reqdByParent, IOptimizationContext context) {
    GroupByOperator gby = (GroupByOperator) op;
    StructuralPropertiesVector[] pv = new StructuralPropertiesVector[1];
    if (gby.isGroupAll() && gby.isGlobal()) {
        if (op.getExecutionMode() == ExecutionMode.UNPARTITIONED) {
            pv[0] = new StructuralPropertiesVector(IPartitioningProperty.UNPARTITIONED, null);
            return new PhysicalRequirements(pv, IPartitioningRequirementsCoordinator.NO_COORDINATION);
        } else {//from   ww  w.  j  av  a  2 s . c  o m
            return emptyUnaryRequirements();
        }
    }

    List<ILocalStructuralProperty> localProps = new ArrayList<>();
    Set<LogicalVariable> gbvars = new ListSet<>(columnList);
    LocalGroupingProperty groupProp = new LocalGroupingProperty(gbvars, new ArrayList<>(columnList));

    boolean goon = true;
    for (ILogicalPlan p : gby.getNestedPlans()) {
        // try to propagate secondary order requirements from nested
        // groupings
        for (Mutable<ILogicalOperator> r : p.getRoots()) {
            AbstractLogicalOperator op1 = (AbstractLogicalOperator) r.getValue();
            if (op1.getOperatorTag() == LogicalOperatorTag.AGGREGATE) {
                AbstractLogicalOperator op2 = (AbstractLogicalOperator) op1.getInputs().get(0).getValue();
                IPhysicalOperator pop2 = op2.getPhysicalOperator();
                if (pop2 instanceof AbstractPreclusteredGroupByPOperator) {
                    List<LogicalVariable> gbyColumns = ((AbstractPreclusteredGroupByPOperator) pop2)
                            .getGbyColumns();
                    List<LogicalVariable> sndOrder = new ArrayList<>();
                    sndOrder.addAll(gbyColumns);
                    Set<LogicalVariable> freeVars = new HashSet<>();
                    try {
                        OperatorPropertiesUtil.getFreeVariablesInSelfOrDesc(op2, freeVars);
                    } catch (AlgebricksException e) {
                        throw new IllegalStateException(e);
                    }
                    // Only considers group key variables defined out-side the outer-most group-by operator.
                    sndOrder.retainAll(freeVars);
                    groupProp.getColumnSet().addAll(sndOrder);
                    groupProp.getPreferredOrderEnforcer().addAll(sndOrder);
                    goon = false;
                    break;
                }
            }
        }
        if (!goon) {
            break;
        }
    }

    localProps.add(groupProp);

    if (reqdByParent != null) {
        // propagate parent requirements
        List<ILocalStructuralProperty> lpPar = reqdByParent.getLocalProperties();
        if (lpPar != null) {
            boolean allOk = true;
            List<ILocalStructuralProperty> props = new ArrayList<>(lpPar.size());
            for (ILocalStructuralProperty prop : lpPar) {
                if (prop.getPropertyType() != PropertyType.LOCAL_ORDER_PROPERTY) {
                    allOk = false;
                    break;
                }
                LocalOrderProperty lop = (LocalOrderProperty) prop;
                List<OrderColumn> orderColumns = new ArrayList<>();
                List<OrderColumn> ords = lop.getOrderColumns();
                for (OrderColumn ord : ords) {
                    Pair<LogicalVariable, Mutable<ILogicalExpression>> p = getGbyPairByRhsVar(gby,
                            ord.getColumn());
                    if (p == null) {
                        p = getDecorPairByRhsVar(gby, ord.getColumn());
                        if (p == null) {
                            allOk = false;
                            break;
                        }
                    }
                    ILogicalExpression e = p.second.getValue();
                    if (e.getExpressionTag() != LogicalExpressionTag.VARIABLE) {
                        throw new IllegalStateException(
                                "Right hand side of group-by assignment should have been normalized to a variable reference.");
                    }
                    LogicalVariable v = ((VariableReferenceExpression) e).getVariableReference();
                    orderColumns.add(new OrderColumn(v, ord.getOrder()));
                }
                props.add(new LocalOrderProperty(orderColumns));
            }
            List<FunctionalDependency> fdList = new ArrayList<>();
            for (Pair<LogicalVariable, Mutable<ILogicalExpression>> decorPair : gby.getDecorList()) {
                List<LogicalVariable> hd = gby.getGbyVarList();
                List<LogicalVariable> tl = new ArrayList<>();
                tl.add(((VariableReferenceExpression) decorPair.second.getValue()).getVariableReference());
                fdList.add(new FunctionalDependency(hd, tl));
            }
            if (allOk && PropertiesUtil.matchLocalProperties(localProps, props, new HashMap<>(), fdList)) {
                localProps = props;
            }
        }
    }

    IPartitioningProperty pp = null;
    AbstractLogicalOperator aop = (AbstractLogicalOperator) op;
    if (aop.getExecutionMode() == ExecutionMode.PARTITIONED) {
        pp = new UnorderedPartitionedProperty(new ListSet<>(columnList), context.getComputationNodeDomain());
    }
    pv[0] = new StructuralPropertiesVector(pp, localProps);
    return new PhysicalRequirements(pv, IPartitioningRequirementsCoordinator.NO_COORDINATION);
}

From source file:org.opencms.i18n.CmsLocaleGroupService.java

/**
 * Helper method for getting the possible locales for a resource.<p>
 *
 * @param cms the CMS context//  ww  w  . ja v  a  2  s. com
 * @param currentResource the resource
 *
 * @return the possible locales for a resource
 */
public static List<Locale> getPossibleLocales(CmsObject cms, CmsResource currentResource) {

    CmsSite site = OpenCms.getSiteManager().getSiteForRootPath(currentResource.getRootPath());
    List<Locale> secondaryLocales = Lists.newArrayList();
    Locale mainLocale = null;
    if (site != null) {
        List<Locale> siteLocales = site.getSecondaryTranslationLocales();
        mainLocale = site.getMainTranslationLocale(null);
        if ((siteLocales == null) || siteLocales.isEmpty()) {
            siteLocales = OpenCms.getLocaleManager().getAvailableLocales();
            if (mainLocale == null) {
                mainLocale = siteLocales.get(0);
            }
        }
        secondaryLocales.addAll(siteLocales);
    }

    try {
        CmsProperty secondaryLocaleProp = cms.readPropertyObject(currentResource,
                CmsPropertyDefinition.PROPERTY_SECONDARY_LOCALES, true);
        String propValue = secondaryLocaleProp.getValue();
        if (!CmsStringUtil.isEmptyOrWhitespaceOnly(propValue)) {
            List<Locale> restrictionLocales = Lists.newArrayList();
            String[] tokens = propValue.trim().split(" *, *"); //$NON-NLS-1$
            for (String token : tokens) {
                OpenCms.getLocaleManager();
                Locale localeForToken = CmsLocaleManager.getLocale(token);
                restrictionLocales.add(localeForToken);
            }
            if (!restrictionLocales.isEmpty()) {
                secondaryLocales.retainAll(restrictionLocales);
            }
        }
    } catch (CmsException e) {
        LOG.error(e.getLocalizedMessage(), e);
    }
    List<Locale> result = new ArrayList<Locale>();
    result.add(mainLocale);
    for (Locale secondaryLocale : secondaryLocales) {
        if (!result.contains(secondaryLocale)) {
            result.add(secondaryLocale);
        }
    }
    return result;
}

From source file:org.geppetto.simulation.manager.ExperimentRunThread.java

/**
 * @param experiment//from  w  w w. ja  v a  2 s .  c  o  m
 * @throws GeppettoInitializationException
 */
private void init(IExperiment experiment) throws GeppettoInitializationException {
    try {
        GeppettoModelAccess modelAccess = new GeppettoModelAccess(runtimeProject.getGeppettoModel());
        List<? extends IAspectConfiguration> aspectConfigs = experiment.getAspectConfigurations();
        for (IAspectConfiguration aspectConfig : aspectConfigs) {
            ISimulatorConfiguration simConfig = aspectConfig.getSimulatorConfiguration();
            String simulatorId = simConfig.getSimulatorId();
            String instancePath = aspectConfig.getInstance();
            Pointer pointer = PointerUtility.getPointer(runtimeProject.getGeppettoModel(), instancePath);

            // We are taking the domain model for the last element of the pointer
            DomainModel model = PointerUtility.getType(pointer).getDomainModel();

            if (simConfig.getConversionServiceId() != null && !simConfig.getConversionServiceId().isEmpty()) {
                AConversion conversionService = (AConversion) ServiceCreator
                        .getNewServiceInstance(simConfig.getConversionServiceId());
                conversionService.setScope(Scope.RUN);
                conversionService.setProjectId(experiment.getParentProject().getId());
                conversionServices.put(instancePath, conversionService);
            }
            ASimulator simulator = (ASimulator) ServiceCreator.getNewServiceInstance(simulatorId);
            simulator.setProjectId(experiment.getParentProject().getId());
            simulatorServices.put(instancePath, simulator);
            simulatorRuntimes.put(instancePath, new SimulatorRuntime());

            // get conversion service
            IConversion conversionService = null;
            if (simConfig.getConversionServiceId() != null && !simConfig.getConversionServiceId().isEmpty()) {
                conversionService = this.conversionServices.get(simConfig.getConversionServiceId());
            }
            IModelInterpreter modelService = runtimeProject.getModelInterpreter(pointer);

            // TODO: Extract formats from model interpreters from within here somehow
            List<ModelFormat> inputFormats = ServicesRegistry.getModelInterpreterServiceFormats(modelService);
            List<ModelFormat> outputFormats = ServicesRegistry.getSimulatorServiceFormats(simulator);
            if (inputFormats == null || inputFormats.isEmpty()) {
                throw new GeppettoInitializationException(
                        "No supported formats for the model interpreter " + modelService.getName());
            }
            if (outputFormats == null || outputFormats.isEmpty()) {
                throw new GeppettoInitializationException(
                        "No supported formats for the simulator " + simulator.getName());
            }
            DomainModel iConvertedModel = null;

            if (conversionService != null) {
                // Read conversion supported model formats
                List<ModelFormat> supportedInputFormats = conversionService.getSupportedInputs();
                // FIXME: We can pass the model and the input format so it brings back a filtered list of outputs format
                List<ModelFormat> supportedOutputFormats = conversionService.getSupportedOutputs();

                // Check if real model formats and conversion supported model formats match
                supportedInputFormats.retainAll(inputFormats);
                supportedOutputFormats.retainAll(outputFormats);

                // Try to convert until a input-output format combination works
                for (ModelFormat inputFormat : supportedInputFormats) {
                    if (iConvertedModel == null) {
                        for (ModelFormat outputFormat : supportedOutputFormats) {
                            try {

                                iConvertedModel = conversionService.convert(model, outputFormat, aspectConfig,
                                        modelAccess);
                                break;
                            } catch (ConversionException e) {
                                throw new GeppettoInitializationException(e);
                            }
                        }
                    }
                }
            } else {
                // Check format returned by the model interpreter matches with the one accepted by the simulator
                if (Collections.disjoint(inputFormats, outputFormats) && inputFormats != null
                        && outputFormats != null) {
                    Map<ConversionServiceKey, List<IConversion>> conversionServices = ServicesRegistry
                            .getConversionService(inputFormats, outputFormats);

                    for (Map.Entry<ConversionServiceKey, List<IConversion>> entry : conversionServices
                            .entrySet()) {
                        if (iConvertedModel == null) {
                            // FIXME: Assuming we will only have one conversion service
                            ConversionServiceKey conversionServiceKey = entry.getKey();
                            for (ModelFormat supportedModelFormat : entry.getValue().get(0)
                                    .getSupportedOutputs(model)) {
                                // Verify supported outputs for this model
                                if (supportedModelFormat.equals(conversionServiceKey.getOutputModelFormat())) {
                                    ((AConversion) entry.getValue().get(0)).setScope(Scope.RUN);
                                    ((AConversion) entry.getValue().get(0))
                                            .setProjectId(experiment.getParentProject().getId());
                                    iConvertedModel = entry.getValue().get(0).convert(model,
                                            conversionServiceKey.getOutputModelFormat(), aspectConfig,
                                            modelAccess);
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            // code to initialize simulator
            if (simulator != null) {

                long start = System.currentTimeMillis();
                ExperimentState experimentState = runtimeProject.getRuntimeExperiment(experiment)
                        .getExperimentState();
                if (iConvertedModel == null) {
                    simulator.initialize(model, aspectConfig, experimentState, this, modelAccess);
                } else {
                    simulator.initialize(iConvertedModel, aspectConfig, experimentState, this, modelAccess);
                }
                long end = System.currentTimeMillis();
                logger.info("Finished initializing simulator, took " + (end - start) + " ms ");
            } else {
                throw new GeppettoInitializationException(
                        "A simulator for " + instancePath + " already exists, something did not get cleared");
            }

        }
    } catch (Exception e) {
        throw new GeppettoInitializationException(e);
    }
}

From source file:org.opencastproject.workflow.handler.RepublishWorkflowOperationHandler.java

/**
 * Creates a clone of the mediapackage and removes those elements that do not match the flavor and tags filter
 * criteria./*w ww  .ja  v  a  2  s  . com*/
 * 
 * @param mediaPackage
 *          the media package
 * @param flavors
 *          the flavors
 * @param tags
 *          the tags
 * @return the filtered media package
 */
protected MediaPackage filterMediaPackage(MediaPackage mediaPackage, Set<MediaPackageElementFlavor> flavors,
        List<String> tags) throws MediaPackageException {
    MediaPackage filteredMediaPackage = (MediaPackage) mediaPackage.clone();

    // The list of elements to keep
    List<MediaPackageElement> keep = new ArrayList<MediaPackageElement>();

    // Filter by flavor
    if (flavors.size() > 0) {
        logger.debug("Filtering elements based on flavors");
        for (MediaPackageElementFlavor flavor : flavors) {
            keep.addAll(Arrays.asList(mediaPackage.getElementsByFlavor(flavor)));
        }
    }

    // Keep those elements that have been identified in the tags
    if (tags.size() > 0) {
        logger.debug("Filtering elements based on tags");
        if (keep.size() > 0) {
            keep.retainAll(Arrays.asList(mediaPackage.getElementsByTags(tags)));
        } else {
            keep.addAll(Arrays.asList(mediaPackage.getElementsByTags(tags)));
        }
    }

    // If no filter has been supplied, take all elements
    if (flavors.size() == 0 && tags.size() == 0)
        keep.addAll(Arrays.asList(mediaPackage.getElements()));

    // Fix references and flavors
    for (MediaPackageElement element : filteredMediaPackage.getElements()) {

        if (!keep.contains(element)) {
            logger.info("Removing {} '{}' from mediapackage '{}'",
                    new String[] { element.getElementType().toString().toLowerCase(), element.getIdentifier(),
                            filteredMediaPackage.getIdentifier().toString() });
            filteredMediaPackage.remove(element);
            continue;
        }

        // Is the element referencing anything?
        MediaPackageReference reference = element.getReference();
        if (reference != null) {
            Map<String, String> referenceProperties = reference.getProperties();
            MediaPackageElement referencedElement = filteredMediaPackage.getElementByReference(reference);

            // if we are distributing the referenced element, everything is fine. Otherwise...
            if (referencedElement != null && !keep.contains(referencedElement.getIdentifier())) {

                // Follow the references until we find a flavor
                MediaPackageElement parent = null;
                while ((parent = mediaPackage.getElementByReference(reference)) != null) {
                    if (parent.getFlavor() != null && element.getFlavor() == null) {
                        element.setFlavor(parent.getFlavor());
                    }
                    if (parent.getReference() == null)
                        break;
                    reference = parent.getReference();
                }

                // Done. Let's cut the path but keep references to the mediapackage itself
                if (reference != null && reference.getType().equals(MediaPackageReference.TYPE_MEDIAPACKAGE))
                    element.setReference(reference);
                else if (reference != null && (referenceProperties == null || referenceProperties.size() == 0))
                    element.clearReference();
                else {
                    // Ok, there is more to that reference than just pointing at an element. Let's keep the original,
                    // you never know.
                    referencedElement.setURI(null);
                    referencedElement.setChecksum(null);
                }
            }
        }
    }

    return filteredMediaPackage;
}