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

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

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this multimap contains no key-value pairs.

Usage

From source file:hu.bme.mit.trainbenchmark.benchmark.fourstore.driver.FourStoreDriver.java

public void insertEdges(final Multimap<String, String> edges, final String type) throws IOException {
    if (edges.isEmpty()) {
        return;// w  ww . ja  v  a 2s  .  c o m
    }

    final ArrayList<String> sourceVertices = new ArrayList<>(edges.keySet());
    final List<List<String>> sourceVerticesPartitions = Lists.partition(sourceVertices, PARTITION_SIZE);
    for (final List<String> sourceVerticesPartition : sourceVerticesPartitions) {

        final Multimap<String, String> edgePartition = ArrayListMultimap.create();
        for (final String sourceVertexURI : sourceVerticesPartition) {
            final Collection<String> targetVertexURIs = edges.get(sourceVertexURI);
            edgePartition.putAll(sourceVertexURI, targetVertexURIs);
        }

        insertEdgesPartition(edgePartition, type);
    }
}

From source file:com.squareup.osstrich.JavadocPublisher.java

private int publishArtifacts(String repoUrl, String groupId, List<Artifact> artifacts) throws IOException {
    initGitDirectory(repoUrl);// www .  j a v a2s. com

    StringBuilder commitMessage = new StringBuilder();
    commitMessage.append("Publish Javadoc\n" + "\n" + "Artifacts published:");

    Multimap<String, Artifact> published = TreeMultimap.create();
    for (Artifact artifact : artifacts) {
        if (fetchJavadoc(artifact)) {
            published.put(majorVersion(artifact.latestVersion), artifact);
            commitMessage.append("\n").append(artifact);
        }
    }

    writeIndexFiles(groupId, published);

    if (!published.isEmpty()) {
        gitCommitAndPush(commitMessage.toString());
    }

    return published.size();
}

From source file:org.sosy_lab.cpachecker.cpa.octagon.refiner.OctagonArgBasedDelegatingRefiner.java

private boolean performOctagonAnalysisRefinement(final ARGReachedSet reached,
        final OctagonAnalysisFeasabilityChecker checker) throws InterruptedException {
    UnmodifiableReachedSet reachedSet = reached.asReachedSet();
    Precision precision = reachedSet.getPrecision(reachedSet.getLastState());
    VariableTrackingPrecision octPrecision = (VariableTrackingPrecision) Precisions.asIterable(precision)
            .filter(VariableTrackingPrecision.isMatchingCPAClass(OctagonCPA.class)).get(0);

    Multimap<CFANode, MemoryLocation> increment = checker.getPrecisionIncrement();
    // no newly tracked variables, so the refinement was not successful, TODO why is this code commented out?
    if (increment.isEmpty()) {
        //  return false;
    }/*ww  w.  j  av  a  2s .c  o  m*/

    reached.removeSubtree(((ARGState) reachedSet.getFirstState()).getChildren().iterator().next(),
            octPrecision.withIncrement(increment),
            VariableTrackingPrecision.isMatchingCPAClass(OctagonCPA.class));
    logger.log(Level.INFO,
            "Refinement successful, precision incremented, following variables are now tracked additionally:\n"
                    + new TreeSet<>(increment.values()));

    return true;
}

From source file:sf.net.experimaestro.manager.plans.Plan.java

/**
 * Returns the graph corresponding to this plan
 *
 * @param map The current plan path (containg joins in input, and operators in output)
 * @return The node that is the root (sink) of the DAG
 *///from  w  w w . ja v a 2  s .  c  om
public synchronized Operator prepare(Map<Operator, Operator> map, OperatorMap opMap) {
    // Check if a plan was not already generated
    Operator old = map.get(this);
    if (old != null)
        return old;

    // Outputs will contain the list of operators that have
    // to be merged (because we have a series of different inputs)
    ArrayList<Operator> outputs = new ArrayList<>();

    for (Multimap<DotName, Operator> inputs : inputsList) {
        TaskOperator self = new TaskOperator(this);

        if (inputs.isEmpty()) {
            self.addParent(new Constant(JsonNull.getSingleton()));
            self.setMappings(ImmutableMap.of());
            outputs.add(self);
        } else {
            // --- Loop over the cartesian product of the inputs
            DotName ids[] = new DotName[inputs.keySet().size()];
            OperatorIterable inputValues[] = new OperatorIterable[inputs.keySet().size()];
            {

                int index = 0;
                for (Map.Entry<DotName, Collection<Operator>> input : inputs.asMap().entrySet()) {
                    ids[index] = input.getKey();
                    inputValues[index] = new OperatorIterable(input.getValue(), map, opMap);
                    index++;
                }
                assert index == ids.length;
            }

            // Create a new operator
            Operator inputOperators[] = new Operator[inputValues.length];

            for (int i = inputValues.length; --i >= 0;) {
                OperatorIterable values = inputValues[i];
                Union union = new Union();
                for (Operator operator : values) {
                    union.addParent(operator);
                }

                if (union.getParents().size() == 1)
                    inputOperators[i] = union.getParent(0);
                else
                    inputOperators[i] = union;

                opMap.add(inputOperators[i]);

            }

            // Find LCAs and store them in a map operator ID -> inputs
            // joins contains the list of pairwise LCAs in the operator
            // graph above
            BitSet[] joins = new BitSet[inputOperators.length];
            for (int i = 0; i < joins.length; i++) {
                joins[i] = new BitSet();
            }

            for (int i = 0; i < ids.length - 1; i++) {
                for (int j = i + 1; j < ids.length; j++) {
                    ArrayList<Operator> lca = opMap.findLCAs(inputOperators[i], inputOperators[j]);
                    for (Operator operator : lca) {
                        int key = opMap.get(operator);
                        joins[i].set(key);
                        joins[j].set(key);
                    }
                }
            }

            Lattice lattice = new Lattice(opMap);
            for (int i = 0; i < joins.length; i++) {
                lattice.add(joins[i], inputOperators[i]);
            }
            LatticeNode.MergeResult merge = lattice.merge();

            self.addParent(merge.operator);

            // Associate streams with names
            Map<DotName, Integer> mappings = new TreeMap<>();
            for (int i = 0; i < ids.length; i++) {
                mappings.put(ids[i], merge.map.get(inputOperators[i]));
            }
            self.setMappings(mappings);

            // --- Handle group by

            outputs.add(self);
        }
    }

    // End of loop over inputs

    Operator planOperator;
    if (outputs.size() == 1) {
        map.put(this, outputs.get(0));
        planOperator = outputs.get(0);
    } else {
        Union union = new Union();
        map.put(this, union);
        for (Operator output : outputs)
            union.addParent(output);
        planOperator = union;
    }

    return planOperator;

}

From source file:org.sosy_lab.cpachecker.cpa.apron.refiner.ApronARGBasedDelegatingRefiner.java

private boolean performApronAnalysisRefinement(final ARGReachedSet reached,
        final OctagonAnalysisFeasabilityChecker checker) throws InterruptedException {
    UnmodifiableReachedSet reachedSet = reached.asReachedSet();
    Precision precision = reachedSet.getPrecision(reachedSet.getLastState());
    VariableTrackingPrecision apronPrecision = (VariableTrackingPrecision) Precisions.asIterable(precision)
            .filter(VariableTrackingPrecision.isMatchingCPAClass(ApronCPA.class)).get(0);

    Multimap<CFANode, MemoryLocation> increment = checker.getPrecisionIncrement();
    // no newly tracked variables, so the refinement was not successful // TODO why is this commented out
    if (increment.isEmpty()) {
        //  return false;
    }/*w  w  w.  j  a v a 2s.  c  o m*/

    reached.removeSubtree(((ARGState) reachedSet.getFirstState()).getChildren().iterator().next(),
            apronPrecision.withIncrement(increment),
            VariableTrackingPrecision.isMatchingCPAClass(ApronCPA.class));

    logger.log(Level.INFO,
            "Refinement successful, precision incremented, following variables are now tracked additionally:\n"
                    + new TreeSet<>(increment.values()));

    return true;
}

From source file:org.sonar.java.filters.FilterVerifier.java

public static void verify(String filename, JavaIssueFilter filter, CodeVisitor... extraCodeVisitors) {
    // set the component to the filter
    filter.setComponentKey(filename);//  ww  w. j av a 2s .  c om

    IssueCollector issueCollector = new IssueCollector();
    ArrayList<CodeVisitor> codeVisitors = Lists.<CodeVisitor>newArrayList(filter, issueCollector);

    // instantiate the rules filtered by the filter
    codeVisitors.addAll(instantiateRules(filter.filteredRules()));

    for (CodeVisitor codeVisitor : extraCodeVisitors) {
        codeVisitors.add(codeVisitor);
    }

    Collection<File> classpath = FileUtils.listFiles(new File("target/test-jars"),
            new String[] { "jar", "zip" }, true);
    VisitorsBridgeForTests visitorsBridge = new VisitorsBridgeForTests(codeVisitors,
            Lists.newArrayList(classpath), null);
    JavaAstScanner.scanSingleFileForTests(new File(filename), visitorsBridge);
    VisitorsBridgeForTests.TestJavaFileScannerContext testJavaFileScannerContext = visitorsBridge
            .lastCreatedTestContext();

    Multimap<Integer, String> issuesByLines = HashMultimap.create();
    for (AnalyzerMessage analyzerMessage : testJavaFileScannerContext.getIssues()) {
        Integer issueLine = analyzerMessage.getLine();
        String ruleKey = AnnotationUtils.getAnnotation(analyzerMessage.getCheck().getClass(), Rule.class).key();
        FilterableIssue issue = mock(FilterableIssue.class);
        when(issue.ruleKey()).thenReturn(RuleKey.of("repo", ruleKey));
        when(issue.componentKey()).thenReturn(filename);
        when(issue.line()).thenReturn(issueLine);

        if (issueCollector.rejectedIssuesLines.contains(issueLine)) {

            assertThat(filter.accept(issue)).overridingErrorMessage("Line #" + issueLine
                    + " has been marked with 'NoIssue' but issue of rule '" + ruleKey + "' has been accepted!")
                    .isFalse();
        } else if (issueCollector.acceptedIssuesLines.contains(issueLine)) {
            // force check on accepted issues
            assertThat(filter.accept(issue)).overridingErrorMessage(
                    "Line #" + issueLine + " has been marked with 'WithIssue' but no issue have been raised!")
                    .isTrue();
        } else {
            issuesByLines.put(issueLine, ruleKey);
        }
    }

    if (!issuesByLines.isEmpty()) {
        List<Integer> lines = Lists.newArrayList(issuesByLines.keySet());
        Collections.sort(lines);
        StringBuilder builder = new StringBuilder();
        for (Integer line : lines) {
            builder.append("\n#" + line + ": " + issuesByLines.get(line).toString());
        }

        Fail.fail("The following lines have not been marked with 'WithIssue' or 'NoIssue' and raised issues:"
                + builder.toString());
    }
}

From source file:org.apache.calcite.rel.rules.AbstractMaterializedViewRule.java

/**
 * It will flatten a multimap containing table references to table references,
 * producing all possible combinations of mappings. Each of the mappings will
 * be bi-directional.//from   w ww.ja  v a 2 s .c o  m
 */
private static List<BiMap<RelTableRef, RelTableRef>> generateTableMappings(
        Multimap<RelTableRef, RelTableRef> multiMapTables) {
    final List<BiMap<RelTableRef, RelTableRef>> result = new ArrayList<>();
    if (multiMapTables.isEmpty()) {
        return result;
    }
    result.add(HashBiMap.<RelTableRef, RelTableRef>create());
    for (Entry<RelTableRef, Collection<RelTableRef>> e : multiMapTables.asMap().entrySet()) {
        boolean added = false;
        for (RelTableRef target : e.getValue()) {
            if (added) {
                for (BiMap<RelTableRef, RelTableRef> m : result) {
                    final BiMap<RelTableRef, RelTableRef> newM = HashBiMap.<RelTableRef, RelTableRef>create(m);
                    newM.put(e.getKey(), target);
                    result.add(newM);
                }
            } else {
                for (BiMap<RelTableRef, RelTableRef> m : result) {
                    m.put(e.getKey(), target);
                }
                added = true;
            }
        }
        // Mapping needs to exist
        assert added;
    }
    return result;
}

From source file:dmg.util.command.TextHelpPrinter.java

@Override
public String getHelp(Object instance) {
    Class<?> clazz = instance.getClass();
    Command command = clazz.getAnnotation(Command.class);

    StringWriter out = new StringWriter();
    PrintWriter writer = new PrintWriter(out);

    writer.println(heading("NAME"));
    writer.append("       ").append(literal(command.name()));
    if (!command.hint().isEmpty()) {
        writer.append(" -- ").append(command.hint());
    }//  w ww.  j  ava2  s  .  c o m
    writer.println();
    writer.println();

    writer.println(heading("SYNOPSIS"));
    writer.append(Strings.wrap("       ", literal(command.name()) + " " + getSignature(clazz), WIDTH));
    writer.println();

    if (clazz.getAnnotation(Deprecated.class) != null) {
        writer.append(Strings.wrap("       ",
                "This command is deprecated and will be removed in a future release.", WIDTH));
        writer.println();
    }

    if (!command.description().isEmpty()) {
        writer.println(heading("DESCRIPTION"));
        writer.append(Strings.wrap("       ", command.description(), WIDTH));
    }
    writer.println();

    List<Field> arguments = AnnotatedCommandUtils.getArguments(clazz);
    if (!arguments.isEmpty() && any(arguments, shouldBeDocumented)) {
        writer.println(heading("ARGUMENTS"));
        for (Field field : arguments) {
            Argument argument = field.getAnnotation(Argument.class);
            writer.append("       ").println(getMetaVar(field, argument));
            String help = argument.usage();
            if (!argument.required()) {
                help = Joiner.on(' ').join(help, getDefaultDescription(instance, field));
            }
            if (field.getAnnotation(ExpandWith.class) != null) {
                help = Joiner.on(' ').join(help, "Glob patterns will be expanded.");
            }
            if (!help.isEmpty()) {
                writer.append(Strings.wrap("              ", help, WIDTH));
            }
        }
        writer.println();
    }

    Multimap<String, Field> options = AnnotatedCommandUtils.getOptionsByCategory(clazz);
    if (!options.isEmpty()) {
        writer.println(heading("OPTIONS"));
        for (Map.Entry<String, Collection<Field>> category : options.asMap().entrySet()) {
            if (!category.getKey().isEmpty()) {
                writer.println();
                writer.append("       ").println(heading(category.getKey() + ":"));
            }
            for (Field field : category.getValue()) {
                Class<?> type = field.getType();
                Option option = field.getAnnotation(Option.class);
                if (option != null) {
                    writer.append("       ").append(literal("  -" + option.name()));
                    if (!type.isArray()) {
                        if (!Boolean.class.equals(type) && !Boolean.TYPE.equals(type)) {
                            writer.append("=").append(getMetaVar(type, option));
                        }
                    } else if (option.separator().isEmpty()) {
                        writer.append("=").append(getMetaVar(type.getComponentType(), option));
                        writer.append(value("..."));
                    } else {
                        String metaVar = getMetaVar(type.getComponentType(), option);
                        writer.append("=").append(metaVar);
                        writer.append("[").append(option.separator()).append(metaVar).append("]");
                        writer.append(value("..."));
                    }
                    writer.println();
                    String usage = option.usage();
                    if (!option.required()) {
                        usage = Joiner.on(' ').join(usage, getDefaultDescription(instance, field));
                    }
                    if (!usage.isEmpty()) {
                        writer.append(Strings.wrap("              ", usage, WIDTH));
                    }
                }
                CommandLine cmd = field.getAnnotation(CommandLine.class);
                if (cmd != null && cmd.allowAnyOption()) {
                    writer.append("       ").append(valuespec(cmd.valueSpec())).println();
                    String usage = cmd.usage();
                    if (!usage.isEmpty()) {
                        writer.append(Strings.wrap("              ", usage, WIDTH));
                    }
                }
            }
        }
    }
    writer.flush();

    return out.toString();
}

From source file:org.sosy_lab.cpachecker.cpa.bdd.BddRefiner.java

/**
 * This method performs an value-analysis refinement.
 *
 * @param reached the current reached set
 * @param errorPath the current error path
 * @returns true, if the value-analysis refinement was successful, else false
 * @throws CPAException when value-analysis interpolation fails
 *///from  www. j ava2  s.  c  om
private boolean performValueAnalysisRefinement(final ARGReachedSet reached, final MutableARGPath errorPath)
        throws CPAException, InterruptedException {
    numberOfValueAnalysisRefinements++;

    int currentErrorPathId = errorPath.toString().hashCode();

    // same error path as in last iteration -> no progress
    if (currentErrorPathId == previousErrorPathId) {
        throw new RefinementFailedException(Reason.RepeatedCounterexample, errorPath.immutableCopy());
    }

    previousErrorPathId = currentErrorPathId;

    UnmodifiableReachedSet reachedSet = reached.asReachedSet();
    Precision precision = reachedSet.getPrecision(reachedSet.getLastState());
    VariableTrackingPrecision bddPrecision = (VariableTrackingPrecision) Precisions.asIterable(precision)
            .filter(VariableTrackingPrecision.isMatchingCPAClass(BDDCPA.class)).get(0);

    Multimap<CFANode, MemoryLocation> increment = interpolatingRefiner.determinePrecisionIncrement(errorPath);
    Pair<ARGState, CFAEdge> refinementRoot = interpolatingRefiner.determineRefinementRoot(errorPath, increment,
            false);

    // no increment - value-analysis refinement was not successful
    if (increment.isEmpty()) {
        return false;
    }

    VariableTrackingPrecision refinedBDDPrecision = bddPrecision.withIncrement(increment);

    numberOfSuccessfulValueAnalysisRefinements++;
    reached.removeSubtree(refinementRoot.getFirst(), refinedBDDPrecision,
            VariableTrackingPrecision.isMatchingCPAClass(BDDCPA.class));
    return true;
}

From source file:org.solovyev.android.messenger.realms.sms.SmsAccountConnection.java

private void onSmsReceived(@Nonnull BroadcastReceiver broadcastReceiver, @Nonnull Intent intent)
        throws AccountException {
    final SmsAccount account = getAccount();
    final Multimap<String, SmsData> messagesByPhoneNumber = getMessagesByPhoneNumber(intent);

    if (!messagesByPhoneNumber.isEmpty()) {
        final User user = account.getUser();
        final UserService userService = getUserService();
        final ChatService chatService = getChatService();

        final List<User> contacts = userService.getContacts(user.getEntity());

        for (Map.Entry<String, Collection<SmsData>> entry : messagesByPhoneNumber.asMap().entrySet()) {
            final User contact = findOrCreateContact(entry.getKey(), contacts);
            final Chat chat = chatService.getOrCreatePrivateChat(user.getEntity(), contact.getEntity());

            final List<Message> messages = new ArrayList<Message>(entry.getValue().size());
            for (SmsData smsData : entry.getValue()) {
                final Message message = toMessage(smsData, account, contact, chat);
                if (message != null) {
                    messages.add(message);
                }//w w  w .  j ava  2 s  .c  o m
            }

            chatService.saveMessages(chat.getEntity(), messages);
        }
    }

    if (account.getConfiguration().isStopFurtherProcessing()) {
        broadcastReceiver.abortBroadcast();
    }
}