Example usage for com.google.common.collect Multimap containsKey

List of usage examples for com.google.common.collect Multimap containsKey

Introduction

In this page you can find the example usage for com.google.common.collect Multimap containsKey.

Prototype

boolean containsKey(@Nullable Object key);

Source Link

Document

Returns true if this multimap contains at least one key-value pair with the key key .

Usage

From source file:com.google.devtools.build.lib.skyframe.SkyframeExecutor.java

/**
 * Returns a map from {@link Dependency} inputs to the {@link ConfiguredTarget}s corresponding
 * to those dependencies./*  w w  w  .  j a  v a2  s  .c  om*/
 *
 * <p>For use for legacy support and tests calling through {@code BuildView} only.
 *
 * <p>If a requested configured target is in error, the corresponding value is omitted from the
 * returned list.
 */
@ThreadSafety.ThreadSafe
public ImmutableMultimap<Dependency, ConfiguredTarget> getConfiguredTargetMap(EventHandler eventHandler,
        BuildConfiguration originalConfig, Iterable<Dependency> keys, boolean useOriginalConfig) {
    checkActive();

    Multimap<Dependency, BuildConfiguration> configs;
    if (originalConfig != null) {

        if (useOriginalConfig) {
            // This flag is used because of some unfortunate complexity in the configuration machinery:
            // Most callers of this method pass a <Label, Configuration> pair to directly create a
            // ConfiguredTarget from, but happen to use the Dependency data structure to pass that
            // info (even though the data has nothing to do with dependencies). If this configuration
            // includes a split transition, a dynamic configuration created from it will *not*
            // include that transition (because dynamic configurations don't embed transitions to
            // other configurations. In that case, we need to preserve the original configuration.
            // TODO(bazel-team); make this unnecessary once split transition logic is properly ported
            // out of configurations.
            configs = ArrayListMultimap.<Dependency, BuildConfiguration>create();
            configs.put(Iterables.getOnlyElement(keys), originalConfig);
        } else {
            configs = getConfigurations(eventHandler, originalConfig.getOptions(), keys);
        }
    } else {
        configs = ArrayListMultimap.<Dependency, BuildConfiguration>create();
        for (Dependency key : keys) {
            configs.put(key, null);
        }
    }

    final List<SkyKey> skyKeys = new ArrayList<>();
    for (Dependency key : keys) {
        if (!configs.containsKey(key)) {
            // If we couldn't compute a configuration for this target, the target was in error (e.g.
            // it couldn't be loaded). Exclude it from the results.
            continue;
        }
        for (BuildConfiguration depConfig : configs.get(key)) {
            skyKeys.add(ConfiguredTargetValue.key(key.getLabel(), depConfig));
            for (AspectDescriptor aspectDescriptor : key.getAspects()) {
                skyKeys.add(ActionLookupValue.key(
                        AspectValue.createAspectKey(key.getLabel(), depConfig, aspectDescriptor, depConfig)));
            }
        }
    }

    EvaluationResult<SkyValue> result = evaluateSkyKeys(eventHandler, skyKeys);
    for (Map.Entry<SkyKey, ErrorInfo> entry : result.errorMap().entrySet()) {
        reportCycles(eventHandler, entry.getValue().getCycleInfo(), entry.getKey());
    }

    ImmutableMultimap.Builder<Dependency, ConfiguredTarget> cts = ImmutableMultimap
            .<Dependency, ConfiguredTarget>builder();

    DependentNodeLoop: for (Dependency key : keys) {
        if (!configs.containsKey(key)) {
            // If we couldn't compute a configuration for this target, the target was in error (e.g.
            // it couldn't be loaded). Exclude it from the results.
            continue;
        }
        for (BuildConfiguration depConfig : configs.get(key)) {
            SkyKey configuredTargetKey = ConfiguredTargetValue.key(key.getLabel(), depConfig);
            if (result.get(configuredTargetKey) == null) {
                continue;
            }

            ConfiguredTarget configuredTarget = ((ConfiguredTargetValue) result.get(configuredTargetKey))
                    .getConfiguredTarget();
            List<ConfiguredAspect> configuredAspects = new ArrayList<>();

            for (AspectDescriptor aspectDescriptor : key.getAspects()) {
                SkyKey aspectKey = ActionLookupValue.key(
                        AspectValue.createAspectKey(key.getLabel(), depConfig, aspectDescriptor, depConfig));
                if (result.get(aspectKey) == null) {
                    continue DependentNodeLoop;
                }

                configuredAspects.add(((AspectValue) result.get(aspectKey)).getConfiguredAspect());
            }

            try {
                cts.put(key, MergedConfiguredTarget.of(configuredTarget, configuredAspects));
            } catch (DuplicateException e) {
                throw new IllegalStateException(
                        String.format("Error creating %s", configuredTarget.getTarget().getLabel()), e);
            }
        }
    }

    return cts.build();
}

From source file:it.osm.gtfs.input.OSMParser.java

public static List<Stop> readOSMStops(String fileName)
        throws ParserConfigurationException, SAXException, IOException {
    List<Stop> result = new ArrayList<Stop>();
    Multimap<String, Stop> refBuses = HashMultimap.create();
    Multimap<String, Stop> refRails = HashMultimap.create();

    File file = new File(fileName);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();

    NodeList nodeLst = doc.getElementsByTagName("node");

    for (int s = 0; s < nodeLst.getLength(); s++) {
        Node fstNode = nodeLst.item(s);
        Stop st = new Stop(null, null,
                Double.valueOf(fstNode.getAttributes().getNamedItem("lat").getNodeValue()),
                Double.valueOf(fstNode.getAttributes().getNamedItem("lon").getNodeValue()), null);
        st.originalXMLNode = fstNode;//from ww  w .  j  av a2s .c om
        NodeList att = fstNode.getChildNodes();
        for (int t = 0; t < att.getLength(); t++) {
            Node attNode = att.item(t);
            if (attNode.getAttributes() != null) {
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("ref"))
                    st.setCode(attNode.getAttributes().getNamedItem("v").getNodeValue());
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("name"))
                    st.setName(attNode.getAttributes().getNamedItem("v").getNodeValue());
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("gtfs_id"))
                    st.setGtfsId(attNode.getAttributes().getNamedItem("v").getNodeValue());
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("highway")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("bus_stop"))
                    st.setIsRailway(false);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("railway")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("tram_stop"))
                    st.setIsRailway(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("railway")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("station"))
                    st.setIsRailway(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("public_transport")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("stop_position")
                        && st.isRailway() == null)
                    st.setIsStopPosition(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("train")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("yes"))
                    st.setIsRailway(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("tram")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("yes"))
                    st.setIsRailway(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("bus")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("yes"))
                    st.setIsRailway(false);
            }
        }

        if (st.isRailway() == null)
            if (st.isStopPosition())
                continue; //ignore unsupported stop positions (like ferries)
            else
                throw new IllegalArgumentException("Unknow node type for node: " + st.getOSMId()
                        + ". We support only highway=bus_stop, public_transport=stop_position, railway=tram_stop and railway=station");

        //Check duplicate ref in osm
        if (st.getCode() != null) {
            if (st.isStopPosition() == null || st.isStopPosition() == false) {
                if (st.isRailway()) {
                    if (refRails.containsKey(st.getCode())) {
                        for (Stop existingStop : refRails.get(st.getCode())) {
                            if (OSMDistanceUtils.distVincenty(st.getLat(), st.getLon(), existingStop.getLat(),
                                    existingStop.getLon()) < 500)
                                System.err.println("Warning: The ref " + st.getCode()
                                        + " is used in more than one node within 500m this may lead to bad import."
                                        + " (nodes ids:" + st.getOSMId() + "," + existingStop.getOSMId() + ")");
                        }
                    }

                    refRails.put(st.getCode(), st);
                } else {
                    if (refBuses.containsKey(st.getCode())) {
                        for (Stop existingStop : refBuses.get(st.getCode())) {
                            if (OSMDistanceUtils.distVincenty(st.getLat(), st.getLon(), existingStop.getLat(),
                                    existingStop.getLon()) < 500)
                                System.err.println("Warning: The ref " + st.getCode()
                                        + " is used in more than one node within 500m this may lead to bad import."
                                        + " (nodes ids:" + st.getOSMId() + "," + existingStop.getOSMId() + ")");
                        }
                    }
                    refBuses.put(st.getCode(), st);
                }
            }
        }
        result.add(st);
    }

    return result;
}

From source file:org.openmicroscopy.shoola.agents.measurement.view.MeasurementViewerComponent.java

/**
 * Implemented as specified by the {@link MeasurementViewer} interface.
 * @see MeasurementViewer#tagSelectedFigures()
 *//*from  w w w .j a  v  a  2 s  . c o  m*/
public void tagSelectedFigures(List<AnnotationData> tags) {
    Collection<Figure> figures = view.getSelectedFiguresFromTables();
    if (CollectionUtils.isEmpty(figures)) {
        return;
    }
    List<ROIShape> shapes = new ArrayList<ROIShape>();
    Iterator<Figure> kk = figures.iterator();
    ROIFigure fig;
    while (kk.hasNext()) {
        fig = (ROIFigure) kk.next();
        shapes.add(fig.getROIShape());
    }
    if (CollectionUtils.isEmpty(shapes))
        return;

    Multimap<Long, AnnotationData> m = ArrayListMultimap.create();
    Iterator<AnnotationData> j = tags.iterator();
    AnnotationData an;
    while (j.hasNext()) {
        an = j.next();
        m.put(an.getId(), an);
    }
    Iterator<ROIShape> i = shapes.iterator();
    ROIShape shape;
    StructuredDataResults data;
    List<DataObject> objects = new ArrayList<DataObject>();
    ShapeData d;
    Map<Long, AnnotationData> mo = new HashMap<Long, AnnotationData>();
    while (i.hasNext()) {
        shape = i.next();
        d = shape.getData();
        if (d != null && d.getId() > 0) {
            objects.add(d);
            data = (StructuredDataResults) shape.getFigure().getAttribute(AnnotationKeys.TAG);
            if (data != null && CollectionUtils.isNotEmpty(data.getTags())) {
                Collection<TagAnnotationData> t = data.getTags();
                Iterator<TagAnnotationData> tt = t.iterator();
                while (tt.hasNext()) {
                    TagAnnotationData tag = tt.next();
                    if (!mo.containsKey(tag.getId())) {
                        mo.put(tag.getId(), tag);
                    }
                }
            }
        }
    }
    if (objects.isEmpty()) {
        UserNotifier un = MeasurementAgent.getRegistry().getUserNotifier();
        un.notifyInfo("ROI Annotations", "You must save the ROI before annotating it.");
        return;
    }

    //Now we prepare the list of annotations to add or remove
    List<AnnotationData> toAdd = new ArrayList<AnnotationData>();
    List<Object> toRemove = new ArrayList<Object>();
    if (CollectionUtils.isNotEmpty(m.get(-1L))) {
        toAdd.addAll(m.removeAll(-1L));
    }
    Iterator<Entry<Long, AnnotationData>> k = m.entries().iterator();
    Entry<Long, AnnotationData> e;
    while (k.hasNext()) {
        e = k.next();
        Long id = e.getKey();
        if (!mo.containsKey(id)) {
            toAdd.add(e.getValue());
        }
    }
    k = mo.entrySet().iterator();
    while (k.hasNext()) {
        e = k.next();
        Long id = e.getKey();
        if (!m.containsKey(id)) {
            toRemove.add(e.getValue());
        }
    }
    model.fireAnnotationSaving(objects, toAdd, toRemove);
}

From source file:org.jclouds.rest.internal.RestAnnotationProcessor.java

@Override
public GeneratedHttpRequest apply(Invocation invocation) {
    checkNotNull(invocation, "invocation");
    inputParamValidator.validateMethodParametersOrThrow(invocation);

    Optional<URI> endpoint = Optional.absent();
    HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class);
    if (r != null) {
        endpoint = Optional.fromNullable(r.getEndpoint());
        if (endpoint.isPresent())
            logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation);
    } else if (caller != null) {
        endpoint = getEndpointFor(caller);
        if (endpoint.isPresent())
            logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation);
        else/*  w w  w . ja  v a 2 s. c  o  m*/
            endpoint = findEndpoint(invocation);
    } else {
        endpoint = findEndpoint(invocation);
    }

    if (!endpoint.isPresent())
        throw new NoSuchElementException(format("no endpoint found for %s", invocation));
    GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation)
            .caller(caller);
    String requestMethod = null;
    if (r != null) {
        requestMethod = r.getMethod();
        requestBuilder.fromHttpRequest(r);
    } else {
        requestMethod = tryFindHttpMethod(invocation.getInvokable()).get();
        requestBuilder.method(requestMethod);
    }

    requestBuilder.filters(getFiltersIfAnnotated(invocation));

    Multimap<String, Object> tokenValues = LinkedHashMultimap.create();

    tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion);
    tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion);
    // URI template in rfc6570 form
    UriBuilder uriBuilder = uriBuilder(endpoint.get().toString());

    overridePathEncoding(uriBuilder, invocation);

    if (caller != null)
        tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder));
    tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder));
    Multimap<String, Object> formParams;
    if (caller != null) {
        formParams = addFormParams(tokenValues, caller);
        formParams.putAll(addFormParams(tokenValues, invocation));
    } else {
        formParams = addFormParams(tokenValues, invocation);
    }
    Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation);
    Multimap<String, String> headers = buildHeaders(tokenValues, invocation);

    if (r != null)
        headers.putAll(r.getHeaders());

    if (shouldAddHostHeader(invocation)) {
        StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost());
        if (endpoint.get().getPort() != -1)
            hostHeader.append(":").append(endpoint.get().getPort());
        headers.put(HOST, hostHeader.toString());
    }

    Payload payload = null;
    for (HttpRequestOptions options : findOptionsIn(invocation)) {
        injector.injectMembers(options);// TODO test case
        for (Entry<String, String> header : options.buildRequestHeaders().entries()) {
            headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues));
        }
        for (Entry<String, String> query : options.buildQueryParameters().entries()) {
            queryParams.put(query.getKey(), replaceTokens(query.getValue(), tokenValues));
        }
        for (Entry<String, String> form : options.buildFormParameters().entries()) {
            formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues));
        }

        String pathSuffix = options.buildPathSuffix();
        if (pathSuffix != null) {
            uriBuilder.appendPath(pathSuffix);
        }
        String stringPayload = options.buildStringPayload();
        if (stringPayload != null)
            payload = Payloads.newStringPayload(stringPayload);
    }

    if (queryParams.size() > 0) {
        uriBuilder.query(queryParams);
    }

    requestBuilder.headers(filterOutContentHeaders(headers));

    requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues)));

    if (payload == null) {
        PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class);
        payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload()
                : findOrNull(invocation.getArgs(), Payload.class);
    }

    List<? extends Part> parts = getParts(invocation,
            ImmutableMultimap.<String, Object>builder().putAll(tokenValues).putAll(formParams).build());

    if (parts.size() > 0) {
        if (formParams.size() > 0) {
            parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts));
        }
        payload = new MultipartForm(MultipartForm.BOUNDARY, parts);
    } else if (formParams.size() > 0) {
        payload = Payloads
                .newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE));
    } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) {
        if (payload == null)
            payload = Payloads.newByteArrayPayload(new byte[] {});
        payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0));
    }
    if (payload != null) {
        requestBuilder.payload(payload);
    }
    GeneratedHttpRequest request = requestBuilder.build();

    org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation);
    if (mapBinder != null) {
        Map<String, Object> mapParams;
        if (caller != null) {
            mapParams = buildPayloadParams(caller);
            mapParams.putAll(buildPayloadParams(invocation));
        } else {
            mapParams = buildPayloadParams(invocation);
        }
        if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) {
            PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class);
            addMapPayload(mapParams, params, headers);
        }
        request = mapBinder.bindToRequest(request, mapParams);
    } else {
        request = decorateRequest(request);
    }

    if (request.getPayload() != null) {
        contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers);
    }
    utils.checkRequestHasRequiredProperties(request);
    return request;
}

From source file:org.apache.accumulo.examples.wikisearch.parser.FieldIndexQueryReWriter.java

private RewriterTreeNode removeNonIndexedTerms(RewriterTreeNode root, Multimap<String, String> indexedTerms)
        throws Exception {
    // public void removeNonIndexedTerms(BooleanLogicTreeNodeJexl myroot, String indexedTerms) throws Exception {
    if (indexedTerms.isEmpty()) {
        throw new Exception("removeNonIndexedTerms, indexed Terms empty");
    }//  w ww  .  j a  va  2  s.  c o  m

    // NOTE: doing a depth first enumeration didn't work when I started
    // removing nodes halfway through. The following method does work,
    // it's essentially a reverse breadth first traversal.
    List<RewriterTreeNode> nodes = new ArrayList<RewriterTreeNode>();
    Enumeration<?> bfe = root.breadthFirstEnumeration();

    while (bfe.hasMoreElements()) {
        RewriterTreeNode node = (RewriterTreeNode) bfe.nextElement();
        nodes.add(node);
    }

    // walk backwards
    for (int i = nodes.size() - 1; i >= 0; i--) {
        RewriterTreeNode node = nodes.get(i);
        if (log.isDebugEnabled()) {
            log.debug("removeNonIndexedTerms, analyzing node: " + node.toString() + "  " + node.printNode());
        }
        if (node.getType() == ParserTreeConstants.JJTANDNODE
                || node.getType() == ParserTreeConstants.JJTORNODE) {
            // If all of your children are gone, AND/OR has no purpose, remove
            if (node.getChildCount() == 0) {
                node.removeFromParent();

                // If AND/OR has only 1 child, attach it to the parent directly.
            } else if (node.getChildCount() == 1) {
                RewriterTreeNode p = (RewriterTreeNode) node.getParent();
                RewriterTreeNode c = (RewriterTreeNode) node.getFirstChild();
                node.removeFromParent();
                p.add(c);
            }
        } else if (node.getType() == ParserTreeConstants.JJTJEXLSCRIPT) { // Head node
            // If head node has no children, we have nothing to search on.
            if (node.getChildCount() == 0) {
                throw new Exception();
            }
        } else if (rangeNodeSet.contains(node.getType())) { // leave it alone
            // leave ranges untouched, they'll be handled elsewhere.
            continue;
        } else {
            if (log.isDebugEnabled()) {
                log.debug(
                        "removeNonIndexedTerms, Testing: " + node.getFieldName() + ":" + node.getFieldValue());
            }

            if (!indexedTerms
                    .containsKey(node.getFieldName().toString() + ":" + node.getFieldValue().toString())) {
                if (log.isDebugEnabled()) {
                    log.debug(node.getFieldName() + ":" + node.getFieldValue() + " is NOT indexed");
                }
                node.removeFromParent();
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(node.getFieldName() + ":" + node.getFieldValue() + " is indexed");
                }
            }
        }
    }

    return root;
}

From source file:com.flexive.core.search.genericSQL.GenericSQLDataFilter.java

/**
 * Builds an 'OR' condition.//from   w  ww .java 2 s .c o  m
 *
 * @param sb the string buffer to use
 * @param br the brace
 * @throws FxSqlSearchException if the build failed
 */
private void buildOr(StringBuilder sb, Brace br) throws FxSqlSearchException {
    // Start OR
    boolean conditionStarted = false;
    final Multimap<String, ConditionTableInfo> tables = getUsedContentTables(br, true);
    if (br.getElements().size() > 1) {
        final Map.Entry<String, ConditionTableInfo> singleTable = tables.keySet().size() == 1
                ? tables.entries().iterator().next()
                : null;

        // for "OR" we can always optimize flat storage queries,
        // as long as only one flat storage table is used and we don't have a nested 'and',
        // and the brace does not contain an IS NULL condition
        if (singleTable != null && singleTable.getValue().isFlatStorage() && !br.containsAnd()
                && !containsIsNullCondition(br)) {
            sb.append(getOptimizedFlatStorageSubquery(br, tables.keySet().iterator().next(), false));
            return;
        }

        if (singleTable != null && singleTable.getKey().equals(DatabaseConst.TBL_CONTENT)) {
            // combine main table selects into a single one
            sb.append("(SELECT id,ver," + getEmptyLanguage() + " as lang FROM " + DatabaseConst.TBL_CONTENT
                    + " cd" + " WHERE " + getOptimizedMainTableConditions(br, "cd") + ")");
            return;
        }

        // check if there are two or more queries on the same flat storage that can be grouped
        try {
            final Brace grouped = br.groupConditions(new Brace.GroupFunction() {
                @Override
                public Object apply(Condition cond) {
                    try {
                        final Pair<String, ConditionTableInfo> pi = getPropertyInfo(cond);
                        return pi.getSecond().isFlatStorage()
                                // flat storage entries can be grouped as long as they're on the same table
                                ? pi.getFirst()
                                // generate a unique ID, the statement will be ignored for grouping
                                : "condition" + cond.getId();
                    } catch (FxSqlSearchException e) {
                        throw e.asRuntimeException();
                    }
                }
            });
            if (grouped != br) {
                // reorg happened - process new version
                if (LOG.isTraceEnabled()) {
                    LOG.trace("OR statement reorganized, new statement: " + grouped);
                }
                buildOr(sb, grouped);
                return;
            }
        } catch (SqlParserException e) {
            throw new FxSqlSearchException(e);
        }
    }

    if (tables.containsKey(DatabaseConst.TBL_CONTENT_DATA)) {
        // combine content data "OR" queries into a single select
        final List<Condition> simpleConditions = getSimpleContentDataSelects(br);
        if (simpleConditions.size() > 1) {
            // avoid UNION of identically structured subqueries,
            // use "SELECT id, ver, ... FROM FX_CONTENT_DATA WHERE (cond1 or cond2 or ...) AND (filters)" instead

            final String cdSelect = simpleContentDataUnion(simpleConditions);

            // don't process conditions any further
            br.getElements().removeAll(simpleConditions);

            if (br.size() == 0) {
                // no more conditions
                sb.append(cdSelect);
                return;
            }

            // more conditions follow
            conditionStarted = true;
            sb.append('(').append(cdSelect).append("\nUNION\n");
        }
    }

    if (!conditionStarted) {
        sb.append("(");
    }

    int pos = 0;
    for (BraceElement be : br.getElements()) {
        if (pos > 0) {
            sb.append("\nUNION\n");
        }
        if (be instanceof Condition) {
            sb.append(getConditionSubQuery(br.getStatement(), (Condition) be));
        } else if (be instanceof Brace) {
            build(sb, (Brace) be);
        } else {
            throw new FxSqlSearchException(LOG, "ex.sqlSearch.filter.invalidBrace", be);
        }
        pos++;
    }
    sb.append(")");
}

From source file:ca.sqlpower.object.annotation.SPAnnotationProcessor.java

/**
 * Generates and returns source code for a commitProperty method based on
 * setter methods annotated with {@link Mutator} used in a given
 * {@link SPObject} class. The purpose of this commitProperty method is to
 * allow a session {@link SPPersister} to commit a persisted property change
 * into an {@link SPSession}. This helper method will be called by the
 * session {@link SPPersister#commit()} method.
 * //  w ww. j a v a 2s .c  o m
 * @param visitedClass
 *            The {@link SPObject} class that is being visited by the
 *            annotation processor.
 * @param setters
 *            The {@link Map} of property setter methods to their property
 *            types that can be used by an {@link SPPersister} to persist
 *            properties into an {@link SPSession}.
 * @param mutatorExtraParameters
 *            The {@link Multimap} of setter methods mapped to each of its
 *            extra parameters (second parameter and onwards).
 * @param mutatorThrownTypes
 *            The {@link Multimap} of property setter methods to their
 *            thrown exceptions.
 * @param tabs
 *            The number of tab characters to use to indent this generated
 *            method block.
 * @return The source code for the generated commitProperty method.
 * @see SPPersister#persistProperty(String, String,
 *      ca.sqlpower.dao.SPPersister.DataType, Object)
 * @see SPPersister#commit()
 */
private String generateCommitPropertyMethod(Class<? extends SPObject> visitedClass,
        Map<String, Class<?>> setters, Multimap<String, MutatorParameterObject> mutatorExtraParameters,
        Multimap<String, Class<? extends Exception>> mutatorThrownTypes, int tabs) {
    StringBuilder sb = new StringBuilder();
    final String genericObjectField = "o";
    final String objectField = "castedObject";
    final String propertyNameField = "propertyName";
    final String newValueField = "newValue";
    final String converterField = "converter";
    final String exceptionField = "e";
    final String dataTypeField = "dataType";

    boolean firstIf = true;

    // commitProperty method header.
    // public void commitProperty(
    //       SPObject o,
    //       String propertyName,
    //       Object newValue,
    //       DataType dataType,
    //       SessionPersisterSuperConverter converter) 
    //       throws SPPersistenceException {
    println(sb, tabs, String.format("public void %s(%s %s, %s %s, %s %s, %s %s, %s %s) throws %s {",
            COMMIT_PROPERTY_METHOD_NAME, SPObject.class.getSimpleName(), genericObjectField,
            String.class.getSimpleName(), propertyNameField, Object.class.getSimpleName(), newValueField,
            DataType.class.getSimpleName(), dataTypeField, SessionPersisterSuperConverter.class.getSimpleName(),
            converterField, SPPersistenceException.class.getSimpleName()));
    tabs++;

    if (!setters.isEmpty()) {
        // If the SPObject class this persister helper handles is abstract,
        // use the type generic defined in the class header.
        // Otherwise, use the SPObject class directly.
        if (Modifier.isAbstract(visitedClass.getModifiers())) {
            // T castedObject = (T) o;
            println(sb, tabs, String.format("%s %s = (%s) %s;", TYPE_GENERIC_PARAMETER, objectField,
                    TYPE_GENERIC_PARAMETER, genericObjectField));
        } else {
            // <visitedClass> castedObject = (<visitedClass>) o;
            println(sb, tabs, String.format("%s %s = (%s) %s;", visitedClass.getSimpleName(), objectField,
                    visitedClass.getSimpleName(), genericObjectField));
        }

        // Search for the matching property name and set the value.
        for (Entry<String, Class<?>> e : setters.entrySet()) {
            String methodName = e.getKey();
            Class<?> type = e.getValue();

            print(sb, tabs, "");

            if (!firstIf) {
                niprint(sb, "} else ");
            }

            // if (propertyName.equals("<method to property name>") {
            niprintln(sb, String.format("if (%s.equals(\"%s\")) {", propertyNameField,
                    SPAnnotationProcessorUtils.convertMethodToProperty(methodName)));
            tabs++;

            boolean throwsExceptions = mutatorThrownTypes.containsKey(e.getKey());

            if (throwsExceptions) {
                println(sb, tabs, "try {");
                tabs++;
            }

            // Assign each extra argument value of setter methods to variables
            // to pass into the call to the setter afterwards.
            for (MutatorParameterObject extraParam : mutatorExtraParameters.get(methodName)) {
                // <extraParam type> <extraParam name> = 
                //       <extraParam type>.valueOf("<extraParam name>");
                println(sb, tabs,
                        String.format("%s %s = %s.valueOf(\"%s\");", extraParam.getType().getSimpleName(),
                                extraParam.getName(), extraParam.getType().getSimpleName(),
                                extraParam.getValue()));
            }

            // Pass in the actual property value as the first argument to the setter.
            String conversionType;
            if (type == Object.class) {
                conversionType = dataTypeField + ".getRepresentation()";
            } else {
                conversionType = type.getSimpleName() + ".class";
            }

            // castedObject.<setter>(
            //       (<type>) converter.convertToComplexType(
            //             newValue, <dataType.getRepresentation | type.class>);
            print(sb, tabs,
                    String.format("%s.%s((%s) %s.%s(%s, %s)", objectField, methodName, type.getSimpleName(),
                            converterField, CONVERT_TO_COMPLEX_TYPE_METHOD_NAME, newValueField,
                            conversionType));

            // Pass in the variables holding the extra argument values.
            for (MutatorParameterObject extraParam : mutatorExtraParameters.get(methodName)) {
                // , <extraParam name>
                niprint(sb, ", " + extraParam.getName());
            }

            niprintln(sb, ");");
            tabs--;

            // Catch any exceptions that the setter throws.
            if (throwsExceptions) {
                for (Class<? extends Exception> thrownType : mutatorThrownTypes.get(methodName)) {

                    // } catch (<Exception type> e) {
                    println(sb, tabs,
                            String.format("} catch (%s %s) {", thrownType.getSimpleName(), exceptionField));
                    tabs++;

                    // throw new SPPersistenceException(
                    //       castedObject.getUUID(),
                    //       createSPPersistenceExceptionMessage(
                    //             castedObject,
                    //             propertyName),
                    //       e);
                    println(sb, tabs,
                            String.format("throw new %s(%s.%s(), %s(%s, %s), %s);",
                                    SPPersistenceException.class.getSimpleName(), objectField,
                                    GET_UUID_METHOD_NAME, CREATE_EXCEPTION_MESSAGE_METHOD_NAME, objectField,
                                    propertyNameField, exceptionField));
                    tabs--;
                }
                println(sb, tabs, "}");
                tabs--;
            }

            firstIf = false;
        }

        if (!firstIf) {
            println(sb, tabs, "} else {");
            tabs++;
        }
    }

    if (SPObject.class.isAssignableFrom(visitedClass.getSuperclass())) {
        // super.commitProperty(o, <property>, newValue, dataType, converter);
        println(sb, tabs, String.format("super.%s(%s, %s, %s, %s, %s);", COMMIT_PROPERTY_METHOD_NAME,
                genericObjectField, propertyNameField, newValueField, dataTypeField, converterField));
    } else {
        // Throw an SPPersistenceException if the property is not persistable or unrecognized.
        // throw new SPPersistenceException(
        //       castedObject.getUUID(),
        //       createSPPersistenceExceptionMessage(
        //             castedObject,
        //             propertyName));
        println(sb, tabs,
                String.format("throw new %s(%s.%s(), %s(%s, %s));",
                        SPPersistenceException.class.getSimpleName(), objectField, GET_UUID_METHOD_NAME,
                        CREATE_EXCEPTION_MESSAGE_METHOD_NAME, objectField, propertyNameField));
    }

    if (!firstIf) {
        tabs--;
        println(sb, tabs, "}");
    }

    tabs--;
    println(sb, tabs, "}");

    return sb.toString();
}

From source file:org.apache.accumulo.examples.wikisearch.parser.FieldIndexQueryReWriter.java

/***
 * We only want to pass ranges on if they meet a very narrow set of conditions. All ranges must be bounded i.e. x between(1,5) so their parent is an AND. We
 * will only pass a range if 1. The AND is the direct child of HEAD node 2. The AND is a child of an OR which is a direct child of HEAD node.
 * //from  w ww  .  j  a  v a  2  s . c  om
 * If there is an HEAD-AND[x,OR[b,AND[range]]], and you remove the range, this turns the tree into HEAD-AND[X,OR[B]] which becomes HEAD-AND[X,B] which will
 * miss entries, so you need to cut out the entire OR at this point and let the positive side of the AND pick it up.
 */
private RewriterTreeNode removeTreeConflicts(RewriterTreeNode root, Multimap<String, String> indexedTerms) {
    if (log.isDebugEnabled()) {
        log.debug("removeTreeConflicts");
    }

    /*
     * You can't modify the enumeration, so save it into a list. We want to walk backwards in a breadthFirstEnumeration. So we don't throw null pointers when we
     * erase nodes and shorten our list.
     */
    List<RewriterTreeNode> nodeList = new ArrayList<RewriterTreeNode>();
    Enumeration<?> nodes = root.breadthFirstEnumeration();
    while (nodes.hasMoreElements()) {
        RewriterTreeNode child = (RewriterTreeNode) nodes.nextElement();
        nodeList.add(child);
    }

    // walk backwards
    for (int i = nodeList.size() - 1; i >= 0; i--) {
        RewriterTreeNode node = nodeList.get(i);

        if (node.isRemoval()) {
            node.removeFromParent();
            continue;
        }

        RewriterTreeNode parent = (RewriterTreeNode) node.getParent();
        /*
         * All ranges must be bounded! This means the range must be part of an AND, and the parent of AND must be a HEAD node or an OR whose parent is a HEAD
         * node.
         */
        if (node.getType() == ParserTreeConstants.JJTANDNODE && (node.getLevel() == 1
                || (parent.getType() == ParserTreeConstants.JJTORNODE && parent.getLevel() == 1))) {

            if (log.isDebugEnabled()) {
                log.debug("AND at level 1 or with OR parent at level 1");
            }
            Map<Text, RangeBounds> rangeMap = getBoundedRangeMap(node);

            // can't modify the enumeration... save children to a list.
            List<RewriterTreeNode> childList = new ArrayList<RewriterTreeNode>();
            Enumeration<?> children = node.children();
            while (children.hasMoreElements()) {
                RewriterTreeNode child = (RewriterTreeNode) children.nextElement();
                childList.add(child);
            }

            for (int j = childList.size() - 1; j >= 0; j--) {
                RewriterTreeNode child = childList.get(j);
                // currently we are not allowing unbounded ranges, so they must sit under an AND node.
                if (rangeNodeSet.contains(child.getType())) {
                    if (log.isDebugEnabled()) {
                        log.debug("child type: " + JexlOperatorConstants.getOperator(child.getType()));
                    }
                    if (rangeMap == null) {
                        // remove
                        child.removeFromParent();
                    } else {
                        if (!rangeMap.containsKey(new Text(child.getFieldName()))) {
                            child.removeFromParent();
                        } else {
                            // check if it has a single non-range sibling
                            boolean singleSib = false;
                            if (log.isDebugEnabled()) {
                                log.debug("checking for singleSib.");
                            }
                            Enumeration<?> sibs = child.getParent().children();
                            while (sibs.hasMoreElements()) {
                                RewriterTreeNode sib = (RewriterTreeNode) sibs.nextElement();
                                if (!rangeNodeSet.contains(sib.getType())) {
                                    singleSib = true;
                                    break;
                                }
                            }
                            if (singleSib) {
                                child.removeFromParent();
                            } else {
                                if (indexedTerms
                                        .containsKey(child.getFieldName() + ":" + child.getFieldValue())) {
                                    if (log.isDebugEnabled()) {
                                        log.debug("removeTreeConflicts, node: " + node.getContents());
                                    }
                                    // swap parent AND with an OR
                                    node.removeAllChildren();
                                    node.setType(ParserTreeConstants.JJTORNODE);

                                    Collection<String> values = indexedTerms
                                            .get(child.getFieldName() + ":" + child.getFieldValue());
                                    for (String value : values) {
                                        RewriterTreeNode n = new RewriterTreeNode(ParserTreeConstants.JJTEQNODE,
                                                child.getFieldName(), value, child.isNegated());
                                        node.add(n);
                                    }
                                    if (log.isDebugEnabled()) {
                                        log.debug("removeTreeConflicts, node: " + node.getContents());
                                    }

                                    break;
                                } else {
                                    child.removeFromParent();
                                }

                            }
                        }
                    }
                }
            } // end inner for

        } else { // remove all ranges!
            if (node.isLeaf()) {
                continue;
            }
            // can't modify the enumeration...
            List<RewriterTreeNode> childList = new ArrayList<RewriterTreeNode>();
            Enumeration<?> children = node.children();
            while (children.hasMoreElements()) {
                RewriterTreeNode child = (RewriterTreeNode) children.nextElement();
                childList.add(child);
            }

            // walk backwards
            for (int j = childList.size() - 1; j >= 0; j--) {

                RewriterTreeNode child = childList.get(j);
                if (log.isDebugEnabled()) {
                    log.debug("removeTreeConflicts, looking at node: " + node);
                }
                if (rangeNodeSet.contains(child.getType())) {
                    // if grand parent is an OR and not top level, mark whole thing for removal.
                    RewriterTreeNode grandParent = (RewriterTreeNode) child.getParent().getParent();
                    if (grandParent.getType() == ParserTreeConstants.JJTORNODE && grandParent.getLevel() != 1) {
                        grandParent.setRemoval(true);
                    }
                    child.removeFromParent();
                }
            }
        }

    } // end outer for

    return root;
}

From source file:org.summer.dsl.model.types.util.TypeArgumentContextProvider.java

protected void resolveAgainstActualType(JvmTypeReference declaredType, JvmTypeReference actualType,
        final Multimap<JvmTypeParameter, ResolveInfo> result, final boolean allowWildcardResolutions,
        final int hint) {
    ITypeReferenceVisitorWithParameter<ResolveInfo, Void> implementation = new AbstractTypeReferenceVisitorWithParameter.InheritanceAware<ResolveInfo, Void>() {
        @Override//from  www. j a  v a 2s .c  o  m
        public Void doVisitCompoundTypeReference(JvmCompoundTypeReference reference, ResolveInfo param) {
            for (JvmTypeReference component : reference.getReferences())
                visit(component, param);
            return null;
        }

        @Override
        protected Void handleNullReference(ResolveInfo parameter) {
            return null;
        }

        @Override
        public Void doVisitTypeReference(JvmTypeReference reference, ResolveInfo param) {
            return null;
        }

        @Override
        public Void doVisitParameterizedTypeReference(final JvmParameterizedTypeReference declaredReference,
                final ResolveInfo param) {
            return new AbstractTypeReferenceVisitor.InheritanceAware<Void>() {
                @Override
                public Void doVisitCompoundTypeReference(JvmCompoundTypeReference reference) {
                    for (JvmTypeReference component : reference.getReferences())
                        visit(component);
                    return null;
                }

                @Override
                protected Void handleNullReference() {
                    final JvmType type = declaredReference.getType();
                    if (type instanceof JvmTypeParameter) {
                        for (JvmTypeConstraint constraint : ((JvmTypeParameter) type).getConstraints()) {
                            if (constraint instanceof JvmUpperBound && constraint.getTypeReference() != null) {
                                result.put((JvmTypeParameter) type,
                                        new ResolveInfo(constraint.getTypeReference(), param.kind, param.hint));
                            }
                        }
                    }
                    return null;
                }

                @Override
                public Void doVisitParameterizedTypeReference(JvmParameterizedTypeReference reference) {
                    final JvmType type = declaredReference.getType();
                    if (type instanceof JvmTypeParameter) {
                        result.put((JvmTypeParameter) type, param);
                    } else if (type instanceof JvmTypeParameterDeclarator
                            && !((JvmTypeParameterDeclarator) type).getTypeParameters().isEmpty()) {
                        TypeArgumentContext actualContext = getReceiverContext(reference);
                        if (actualContext != null) {
                            TypeArgumentContext declaredContext = getReceiverContext(declaredReference);
                            if (declaredContext == null) {
                                declaredContext = new TypeArgumentContext(
                                        Collections.<JvmTypeParameter, JvmTypeReference>emptyMap(),
                                        typeReferences, typesFactory, rawTypeHelper, primitives);
                            }
                            Collection<JvmTypeParameter> receiverBoundParameters = actualContext
                                    .getBoundParameters();
                            for (JvmTypeParameter receiverBound : receiverBoundParameters) {
                                JvmTypeReference declared = declaredContext.getBoundArgument(receiverBound);
                                JvmTypeReference actual = actualContext.getBoundArgument(receiverBound);
                                outerVisit(declared,
                                        new ResolveInfo(actual, ResolveInfoKind.EXACT, param.hint));
                            }
                            for (JvmTypeParameter declaredBoundParameter : declaredContext
                                    .getBoundParameters()) {
                                if (!result.containsKey(declaredBoundParameter)) {
                                    result.put(declaredBoundParameter, new ResolveInfo(
                                            declaredContext.internalGetBoundArgument(declaredBoundParameter),
                                            param.kind, param.hint));
                                }
                            }
                        }
                    }
                    return null;
                }

                @Override
                public Void doVisitWildcardTypeReference(JvmWildcardTypeReference reference) {
                    boolean lowerBoundFound = false;
                    for (JvmTypeConstraint constraint : reference.getConstraints()) {
                        if (constraint instanceof JvmLowerBound) {
                            lowerBoundFound = true;
                            //                        if (param.kind != ResolveInfoKind.EXACT) {
                            outerVisit(declaredReference, new ResolveInfo(constraint.getTypeReference(),
                                    allowWildcardResolutions ? ResolveInfoKind.WC_LOWER : ResolveInfoKind.LOWER,
                                    param.hint));
                            //                        }
                        }
                    }
                    if (!lowerBoundFound /* || param.kind == ResolveInfoKind.EXACT */) {
                        for (JvmTypeConstraint constraint : reference.getConstraints()) {
                            if (constraint instanceof JvmUpperBound) {
                                //                           if (param.kind != ResolveInfoKind.EXACT) {
                                outerVisit(declaredReference,
                                        new ResolveInfo(constraint.getTypeReference(),
                                                allowWildcardResolutions ? ResolveInfoKind.WC_UPPER
                                                        : ResolveInfoKind.UPPER,
                                                param.hint));
                                //                           } else {
                                //                              outerVisit(declaredReference, new ResolveInfo(constraint.getTypeReference(), 
                                //                                    lowerBoundFound ? ResolveInfoKind.EXACT : ResolveInfoKind.UPPER, param.hint));
                                //                           }
                            }
                        }
                    }
                    return null;
                }

                @Override
                public Void doVisitTypeReference(JvmTypeReference reference) {
                    return null;
                }
            }.visit(param.reference);
        }

        @Override
        public Void doVisitWildcardTypeReference(final JvmWildcardTypeReference declaredReference,
                final ResolveInfo param) {
            return new AbstractTypeReferenceVisitor.InheritanceAware<Void>() {
                @Override
                protected Void handleNullReference() {
                    return null;
                }

                @Override
                public Void doVisitCompoundTypeReference(JvmCompoundTypeReference reference) {
                    return doVisitTypeReference(reference);
                }

                @Override
                public Void doVisitWildcardTypeReference(JvmWildcardTypeReference reference) {
                    for (JvmTypeConstraint declaredConstraint : declaredReference.getConstraints()) {
                        if (declaredConstraint instanceof JvmUpperBound) {
                            for (JvmTypeConstraint actualConstraint : reference.getConstraints()) {
                                if (actualConstraint instanceof JvmUpperBound) {
                                    outerVisit(declaredConstraint.getTypeReference(),
                                            new ResolveInfo(actualConstraint.getTypeReference(),
                                                    allowWildcardResolutions ? ResolveInfoKind.WC_UPPER
                                                            : ResolveInfoKind.UPPER,
                                                    param.hint));
                                }
                            }
                        } else {
                            for (JvmTypeConstraint actualConstraint : reference.getConstraints()) {
                                if (actualConstraint instanceof JvmLowerBound) {
                                    outerVisit(declaredConstraint.getTypeReference(),
                                            new ResolveInfo(actualConstraint.getTypeReference(),
                                                    ResolveInfoKind.LOWER, param.hint));
                                }
                            }
                        }
                    }
                    return null;
                }

                @Override
                public Void doVisitTypeReference(JvmTypeReference reference) {
                    boolean lowerBoundFound = false;
                    for (JvmTypeConstraint declaredConstraint : declaredReference.getConstraints()) {
                        if (declaredConstraint instanceof JvmLowerBound) {
                            lowerBoundFound = true;
                            outerVisit(declaredConstraint.getTypeReference(),
                                    new ResolveInfo(reference, ResolveInfoKind.LOWER, param.hint));
                        }
                    }
                    if (!lowerBoundFound) {
                        for (JvmTypeConstraint declaredConstraint : declaredReference.getConstraints()) {
                            if (declaredConstraint instanceof JvmUpperBound) {
                                outerVisit(declaredConstraint.getTypeReference(),
                                        new ResolveInfo(reference, ResolveInfoKind.UPPER, param.hint));
                            }
                        }
                    }
                    return null;
                }
            }.visit(param.reference);
        }

        @Override
        public Void doVisitGenericArrayTypeReference(final JvmGenericArrayTypeReference declaredReference,
                final ResolveInfo param) {
            return new AbstractTypeReferenceVisitor.InheritanceAware<Void>() {
                @Override
                public Void doVisitCompoundTypeReference(JvmCompoundTypeReference reference) {
                    for (JvmTypeReference component : reference.getReferences())
                        visit(component);
                    return null;
                }

                @Override
                public Void doVisitGenericArrayTypeReference(JvmGenericArrayTypeReference reference) {
                    return outerVisit(declaredReference.getComponentType(),
                            new ResolveInfo(reference.getComponentType(), param.kind, param.hint));
                }

                @Override
                public Void doVisitTypeReference(JvmTypeReference reference) {
                    return null;
                }

                @Override
                protected Void handleNullReference() {
                    return null;
                }
            }.visit(param.reference);
        }

        public Void outerVisit(JvmTypeReference reference, ResolveInfo parameter) {
            return visit(reference, parameter);
        }
    };
    implementation.visit(declaredType, new ResolveInfo(actualType, ResolveInfoKind.UPPER, hint));
}

From source file:qirui.download.DownloadNotifier.java

private void updateWithLocked(Collection<DownloadInfo> downloads) {
    final Resources res = mContext.getResources();

    // Cluster downloads together
    final Multimap<String, DownloadInfo> clustered = new ArrayListMultimap();
    for (DownloadInfo info : downloads) {
        final String tag = buildNotificationTag(info);
        if (tag != null) {
            clustered.put(tag, info);/*from  ww w  . j  a  v  a2s  . c om*/
        }
    }

    // Build notification for each cluster
    for (String tag : clustered.keySet()) {
        final int type = getNotificationTagType(tag);
        final Collection<DownloadInfo> cluster = clustered.get(tag);

        final Notification.Builder builder = new Notification.Builder(mContext);

        // Use time when cluster was first shown to avoid shuffling
        final long firstShown;
        if (mActiveNotifs.containsKey(tag)) {
            firstShown = mActiveNotifs.get(tag);
        } else {
            firstShown = System.currentTimeMillis();
            mActiveNotifs.put(tag, firstShown);
        }
        builder.setWhen(firstShown);

        // Show relevant icon
        if (type == TYPE_ACTIVE) {
            builder.setSmallIcon(android.R.drawable.stat_sys_download);
        } else if (type == TYPE_WAITING) {
            builder.setSmallIcon(android.R.drawable.stat_sys_warning);
        } else if (type == TYPE_COMPLETE) {
            builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
        }

        // Build action intents
        if (type == TYPE_ACTIVE || type == TYPE_WAITING) {
            // build a synthetic uri for intent identification purposes
            final Uri uri = new Uri.Builder().scheme("active-dl").appendPath(tag).build();
            final Intent intent = new Intent(Constants.ACTION_LIST, uri, mContext, DownloadReceiver.class);
            intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster));
            builder.setContentIntent(
                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
            builder.setOngoing(true);

        } else if (type == TYPE_COMPLETE) {
            final DownloadInfo info = cluster.iterator().next();
            final Uri uri = ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId);
            builder.setAutoCancel(true);

            final String action;
            if (Downloads.Impl.isStatusError(info.mStatus)) {
                action = Constants.ACTION_LIST;
            } else {
                if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) {
                    action = Constants.ACTION_OPEN;
                } else {
                    action = Constants.ACTION_LIST;
                }
            }

            final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class);
            intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster));
            builder.setContentIntent(
                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));

            final Intent hideIntent = new Intent(Constants.ACTION_HIDE, uri, mContext, DownloadReceiver.class);
            builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0));
        }

        // Calculate and show progress
        String remainingText = null;
        String percentText = null;
        if (type == TYPE_ACTIVE) {
            long current = 0;
            long total = 0;
            long speed = 0;
            synchronized (mDownloadSpeed) {
                for (DownloadInfo info : cluster) {
                    if (info.mTotalBytes != -1) {
                        current += info.mCurrentBytes;
                        total += info.mTotalBytes;
                        speed += mDownloadSpeed.get(info.mId);
                    }
                }
            }

            if (total > 0) {
                final int percent = (int) ((current * 100) / total);
                percentText = res.getString(R.string.download_percent, percent);

                if (speed > 0) {
                    final long remainingMillis = ((total - current) * 1000) / speed;
                    remainingText = res.getString(R.string.download_remaining,
                            ReflectUtils.formatDuration(remainingMillis));
                }

                builder.setProgress(100, percent, false);
            } else {
                builder.setProgress(100, 0, true);
            }
        }

        // Build titles and description
        final Notification notif;
        if (cluster.size() == 1) {
            final DownloadInfo info = cluster.iterator().next();

            builder.setContentTitle(getDownloadTitle(res, info));

            if (type == TYPE_ACTIVE) {
                if (!TextUtils.isEmpty(info.mDescription)) {
                    builder.setContentText(info.mDescription);
                } else {
                    builder.setContentText(remainingText);
                }
                builder.setContentInfo(percentText);

            } else if (type == TYPE_WAITING) {
                builder.setContentText(res.getString(R.string.notification_need_wifi_for_size));

            } else if (type == TYPE_COMPLETE) {
                if (Downloads.Impl.isStatusError(info.mStatus)) {
                    builder.setContentText(res.getText(R.string.notification_download_failed));
                } else if (Downloads.Impl.isStatusSuccess(info.mStatus)) {
                    builder.setContentText(res.getText(R.string.notification_download_complete));
                }
            }

            notif = builder.build();

        } else {
            final Notification.InboxStyle inboxStyle = new Notification.InboxStyle(builder);

            for (DownloadInfo info : cluster) {
                inboxStyle.addLine(getDownloadTitle(res, info));
            }

            if (type == TYPE_ACTIVE) {
                builder.setContentTitle(
                        res.getQuantityString(R.plurals.notif_summary_active, cluster.size(), cluster.size()));
                builder.setContentText(remainingText);
                builder.setContentInfo(percentText);
                inboxStyle.setSummaryText(remainingText);

            } else if (type == TYPE_WAITING) {
                builder.setContentTitle(
                        res.getQuantityString(R.plurals.notif_summary_waiting, cluster.size(), cluster.size()));
                builder.setContentText(res.getString(R.string.notification_need_wifi_for_size));
                inboxStyle.setSummaryText(res.getString(R.string.notification_need_wifi_for_size));
            }

            notif = inboxStyle.build();
        }

        mNotifManager.notify(tag, 0, notif);
    }

    // Remove stale tags that weren't renewed
    final Iterator<String> it = mActiveNotifs.keySet().iterator();
    while (it.hasNext()) {
        final String tag = it.next();
        if (!clustered.containsKey(tag)) {
            mNotifManager.cancel(tag, 0);
            it.remove();
        }
    }
}