Java 类com.google.common.collect.LinkedListMultimap 实例源码

项目:n4js    文件:PolyfillValidatorFragment.java   
/**
 * Find clashes by name.
 *
 * @param myPolyMember
 *            current validated Polyfill
 * @param pivotPolyMember
 *            other polyfill in same project
 * @return pairs of contrandicting or same polyfills.
 */
private ListMultimap<TMember, TMember> findClashingMembersByName(EList<TMember> myPolyMember,
        EList<TMember> pivotPolyMember) {
    ListMultimap<TMember, TMember> ret = LinkedListMultimap.create();
    for (TMember my : myPolyMember) {
        String myName = my.getName();
        if (myName == null)
            continue; // broken AST
        for (TMember other : pivotPolyMember) {
            String otherName = other.getName();
            if (myName.equals(otherName)) {
                ret.put(my, other);
            }
        }
    }
    return ret;
}
项目:SimpleRssReader    文件:SharedPrefUtils.java   
public static String getFeedMetaDataValueAt(final Context context, final int value,
                                            final int position) {
    final LinkedListMultimap<String, String> map = getFeedMetaData(context);

    int i = 0;

    for (final String title : map.asMap().keySet()) {
        if (i == position) {
            if (value == CATEGORY) {
                return map.get(title).get(CATEGORY);
            } else if (value == FEED_URL) {
                return map.get(title).get(FEED_URL);
            }
            return map.get(title).get(FEED_ID);
        }
        i++;
    }

    return null;
}
项目:SimpleRssReader    文件:SharedPrefUtils.java   
public static List<String> getFeedMetaDataTitlesAt(final Context context,
                                                   final List<Integer> positions) {
    final LinkedListMultimap<String, String> map = getFeedMetaData(context);

    final List<String> titles = new ArrayList<>();

    int i = 0;

    for (final String title : map.asMap().keySet()) {
        if (positions.contains(i)) {
            titles.add(title);
        }
        i++;
    }

    return titles;
}
项目:SimpleRssReader    文件:SharedPrefUtils.java   
public static SearchResultsCursor getSearchResultsFor(final Context context,
                                                      final String query) {
    final LinkedListMultimap<String, String> map = getFeedMetaData(context);

    final List<Integer> positions = new ArrayList<>();
    final List<LinkedHashMap<Integer, Integer>> indices = new ArrayList<>();

    int i = 0;

    for (final String title : map.asMap().keySet()) {
        if (org.apache.commons.lang3.StringUtils.containsIgnoreCase(title, query)) {
            indices.add(SearchUtils.getIndicesForQuery(title, query));
            positions.add(i);
        }
        i++;
    }

    return new SearchResultsCursor(positions, indices);
}
项目:SimpleRssReader    文件:SharedPrefUtils.java   
@SuppressWarnings("ResultOfMethodCallIgnored")
public static void updateFeedMetaDataUrl(final Context context, final String feedUrl) {
    final LinkedListMultimap<String, String> map = getFeedMetaData(context);

    final int position = getCurrentFeedAdapterPosition(context);

    int i = 0;

    for (final String title : map.asMap().keySet()) {
        if (i == position) {
            final List<String> values = new ArrayList<>(map.get(title));

            values.set(FEED_URL, feedUrl);

            map.replaceValues(title, values);

            putFeedMetaData(context, map);
            break;
        }
        i++;
    }
}
项目:SimpleRssReader    文件:SharedPrefUtils.java   
@SuppressWarnings({"ResultOfMethodCallIgnored", "ConstantConditions"})
public static void updateFeedMetaDataAt(final Context context, final int position,
                                        final List<String> metaData) {
    final LinkedListMultimap<String, String> map = getFeedMetaData(context);

    final String currentTitle = getFeedMetaDataTitleAt(context, position);
    final String newTitle = metaData.get(TITLE);
    final String category = metaData.get(FEED_ID);

    final List<String> values = new ArrayList<>(map.removeAll(currentTitle));
    values.set(CATEGORY, category);

    map.putAll(newTitle, values);

    putFeedMetaData(context, map);
    updateCurrentFeedAdapterPosition(context, newTitle);
}
项目:de.flapdoodle.solid    文件:Collectors.java   
public static <T, L, K> Collector<T, ?, ImmutableMultimap<K, T>> groupingByValues(Function<? super T, ? extends Iterable<? extends K>> classifier) {
    return ImmutableGenericCollector.<T, LinkedListMultimap<K, T>, ImmutableMultimap<K, T>>builder()
        .supplier(LinkedListMultimap::create)
        .accumulator((map, t) -> {
            classifier.apply(t).forEach(k -> {
                map.put(k, t);
            });
        })
        .combiner((a,b) -> {
            LinkedListMultimap<K, T> ret = LinkedListMultimap.create(a);
            ret.putAll(b);
            return ret;
        })
        .finisher(map -> ImmutableMultimap.copyOf(map))
        .build();
}
项目:schemaorg-java    文件:JsonLdSerializer.java   
private ListMultimap<String, Thing> readReverse(JsonReader reader) throws IOException {
  reader.beginObject();
  ListMultimap<String, Thing> reverseMap = LinkedListMultimap.create();
  while (reader.hasNext()) {
    String property = reader.nextName();
    JsonToken token = reader.peek();
    if (token == JsonToken.BEGIN_OBJECT) {
      reverseMap.put(property, readObject(reader));
    } else if (token == JsonToken.BEGIN_ARRAY) {
      reader.beginArray();
      while (reader.hasNext()) {
        reverseMap.put(property, readObject(reader));
      }
      reader.endArray();
    } else {
      throw new JsonLdSyntaxException(
          String.format(
              "Invalid value token %s in @reverse. Should be a JSON-LD object or an "
                  + "array of JSON-LD objects",
              token));
    }
  }
  reader.endObject();
  return reverseMap;
}
项目:XPathBuilder    文件:IXPath.java   
static String getXPath(LinkedListMultimap<LinkedListMultimap<XPathElement, LinkedList<ACTIONS>>, LinkedListMultimap<ATTRIBUTES, XPathValues>> xpathListMap) {
    String xpath = "";
    for (Map.Entry<LinkedListMultimap<XPathElement, LinkedList<ACTIONS>>, LinkedListMultimap<ATTRIBUTES, XPathValues>> mapEntry : xpathListMap.entries()) {
        for (Map.Entry<XPathElement, LinkedList<ACTIONS>> elementActionsMapEntry : mapEntry.getKey().entries()) {
            for (Map.Entry<PREFIX, ELEMENTS> elementEntry : elementActionsMapEntry.getKey().entries()) {
                /** Adding into Xpath '// + element' or '/ + element' */
                xpath = xpath + XPathBuilder.getElementXpath(elementEntry.getKey(), elementEntry.getValue());
                /** Adding into Xpath '// + element' or '/ + element' */
                for (ACTIONS action : elementActionsMapEntry.getValue()) {
                    for (Map.Entry<ATTRIBUTES, XPathValues> attributesValuesMapEntry : mapEntry.getValue().entries()) {
                        /** Adding into Xpath based on action [contains|equals etc...] an [@attribute='value']  */
                        xpath = xpath + XPathBuilder.getXPath(action, attributesValuesMapEntry.getKey(), attributesValuesMapEntry.getValue());
                        /** Adding into Xpath based on action [contains|equals etc...] an [@attribute='value']  */
                    }
                }
            }
        }
    }
    return xpath;
}
项目:XPathBuilder    文件:XPath.java   
public String getXPath() {
    String xpath = "";
    if (xpathListMap.entries() != null) {
        for (Map.Entry<LinkedListMultimap<XPathElement, LinkedList<ACTIONS>>, LinkedListMultimap<ATTRIBUTES, XPathValues>> mapEntry : xpathListMap.entries()) {
            for (Map.Entry<XPathElement, LinkedList<ACTIONS>> elementActionsMapEntry : mapEntry.getKey().entries()) {
                for (Map.Entry<PREFIX, ELEMENTS> elementEntry : elementActionsMapEntry.getKey().entries()) {
                    /** Adding into Xpath '// + element' or '/ + element' */
                    xpath = xpath + XPathBuilder.getElementXpath(elementEntry.getKey(), elementEntry.getValue());
                    /** Adding into Xpath '// + element' or '/ + element' */
                    LinkedList<ACTIONS> actions = elementActionsMapEntry.getValue();
                    for (ACTIONS action : actions) {
                        for (Map.Entry<ATTRIBUTES, XPathValues> attributesValuesMapEntry : mapEntry.getValue().entries()) {
                            ATTRIBUTES attributes = attributesValuesMapEntry.getKey();
                            XPathValues list = attributesValuesMapEntry.getValue();
                            /** Adding into Xpath based on action [contains|equals etc...] an [@attribute='value']  */
                            xpath = xpath + XPathBuilder.getXPath(action, attributes, list);
                            /** Adding into Xpath based on action [contains|equals etc...] an [@attribute='value']  */
                        }
                    }
                }
            }
        }
        return xpath;
    }
    return "//div[@id='ERROR IN XPath Generation']";
}
项目:api-compiler    文件:QuotaLimitNameValidator.java   
private void checkQuotaLimitNamesAreUnique(Quota quota) {
  ListMultimap<String, QuotaLimit> limitNameCounts = LinkedListMultimap.create();
  for (QuotaLimit limit : quota.getLimitsList()) {
    limitNameCounts.put(limit.getName(), limit);
  }
  for (String limitName : limitNameCounts.keySet()) {
    List<QuotaLimit> limits = limitNameCounts.get(limitName);
    if (limits.size() > 1) {
      error(
          MessageLocationContext.create(Iterables.getLast(limits), "name"),
          "There are %d quota limits with name '%s'.",
          limits.size(),
          limitName);
    }
  }
}
项目:intellij-ce-playground    文件:CaptureService.java   
public void update() {
  CaptureTypeService service = CaptureTypeService.getInstance();
  VirtualFile dir = getCapturesDirectory();
  Multimap<CaptureType, Capture> updated = LinkedListMultimap.create();
  if (dir != null) {
    VirtualFile[] children = VfsUtil.getChildren(dir);
    for (CaptureType type : service.getCaptureTypes()) {
      Set<VirtualFile> files = findCaptureFiles(children, type);
      for (Capture capture : myCaptures.get(type)) {
        // If an existing capture exists for a file, use it: Remove it from the files and add the already existing one.
        if (files.remove(capture.getFile())) {
          updated.put(type, capture);
        }
      }
      for (VirtualFile newFile : files) {
        updated.put(type, type.createCapture(newFile));
      }
    }
  }
  myCaptures = updated;
}
项目:FinanceAnalytics    文件:InflationIssuerDiscountBuildingRepository.java   
/**
 * Build a unit of curves without the discount curve.
 * @param instruments The instruments used for the unit calibration.
 * @param initGuess The initial parameters guess.
 * @param knownData The known data (fx rates, other curves, model parameters, ...)
 * @param inflationMap The inflation curves names map.
 * @param generatorsMap The generators map.
 * @param calculator The calculator of the value on which the calibration is done (usually ParSpreadMarketQuoteCalculator (recommended) or converted present value).
 * @param sensitivityCalculator The parameter sensitivity calculator.
 * @return The new curves and the calibrated parameters.
 */
private InflationIssuerProviderDiscount makeUnit(final InstrumentDerivative[] instruments, final double[] initGuess, 
    final InflationIssuerProviderDiscount knownData,
    LinkedHashMap<String, Currency> dscMap, LinkedHashMap<String, IndexON[]> fwdOnMap, 
    LinkedHashMap<String, IborIndex[]> fwdIborMap, LinkedHashMap<String, IndexPrice[]> priceMap,
    LinkedListMultimap<String, Pair<Object, LegalEntityFilter<LegalEntity>>> issuerMap,
    final LinkedHashMap<String, GeneratorCurve> generatorsMap,
    final InstrumentDerivativeVisitor<ParameterInflationIssuerProviderInterface, Double> calculator,
    final InstrumentDerivativeVisitor<ParameterInflationIssuerProviderInterface, InflationSensitivity> sensitivityCalculator) {
  final GeneratorInflationIssuerProviderDiscount generator = 
      new GeneratorInflationIssuerProviderDiscount(knownData, dscMap, fwdOnMap, priceMap, issuerMap, generatorsMap);
  final InflationIssuerDiscountBuildingData data = new InflationIssuerDiscountBuildingData(instruments, generator);
  final Function1D<DoubleMatrix1D, DoubleMatrix1D> curveCalculator = 
      new InflationIssuerDiscountFinderFunction(calculator, data);
  final Function1D<DoubleMatrix1D, DoubleMatrix2D> jacobianCalculator = 
      new InflationIssuerDiscountFinderJacobian(new ParameterSensitivityInflationIssuerMatrixCalculator(sensitivityCalculator),
      data);
  final double[] parameters = _rootFinder.getRoot(curveCalculator, jacobianCalculator, new DoubleMatrix1D(initGuess)).getData();
  final InflationIssuerProviderDiscount newCurves = data.getGeneratorMarket().evaluate(new DoubleMatrix1D(parameters));
  return newCurves;
}
项目:FinanceAnalytics    文件:IssuerDiscountBuildingRepository.java   
/**
 * Build a unit of curves.
 * @param instruments The instruments used for the unit calibration.
 * @param initGuess The initial parameters guess.
 * @param knownData The known data (fx rates, other curves, model parameters, ...)
 * @param discountingMap The discounting curves names map.
 * @param forwardIborMap The forward curves names map.
 * @param forwardONMap The forward curves names map.
 * @param issuerMap The issuer curves names map.
 * @param generatorsMap The generators map.
 * @param calculator The calculator of the value on which the calibration is done (usually ParSpreadMarketQuoteCalculator (recommended) or converted present value).
 * @param sensitivityCalculator The parameter sensitivity calculator.
 * @return The new curves and the calibrated parameters.
 */
private IssuerProviderDiscount makeUnit(final InstrumentDerivative[] instruments,
    final double[] initGuess,
    final IssuerProviderDiscount knownData,
    final LinkedHashMap<String, Currency> discountingMap,
    final LinkedHashMap<String, IborIndex[]> forwardIborMap,
    final LinkedHashMap<String, IndexON[]> forwardONMap,
    final LinkedListMultimap<String, Pair<Object, LegalEntityFilter<LegalEntity>>> issuerMap,
    final LinkedHashMap<String, GeneratorYDCurve> generatorsMap,
    final InstrumentDerivativeVisitor<ParameterIssuerProviderInterface, Double> calculator,
    final InstrumentDerivativeVisitor<ParameterIssuerProviderInterface, MulticurveSensitivity> sensitivityCalculator) {
  final GeneratorIssuerProviderDiscount generator = new GeneratorIssuerProviderDiscount(knownData, discountingMap, forwardIborMap, forwardONMap, issuerMap, generatorsMap);
  final IssuerDiscountBuildingData data = new IssuerDiscountBuildingData(instruments, generator);
  final Function1D<DoubleMatrix1D, DoubleMatrix1D> curveCalculator = new IssuerDiscountFinderFunction(calculator, data);
  // TODO: Create a way to select the SensitivityMatrixMulticurve calculator (with underlying curve or not)
  final Function1D<DoubleMatrix1D, DoubleMatrix2D> jacobianCalculator = new IssuerDiscountFinderJacobian(new ParameterSensitivityIssuerMatrixCalculator(sensitivityCalculator), data);
  final double[] parameters = _rootFinder.getRoot(curveCalculator, jacobianCalculator, new DoubleMatrix1D(initGuess)).getData();
  final IssuerProviderDiscount newCurves = data.getGeneratorMarket().evaluate(new DoubleMatrix1D(parameters));
  return newCurves;
}
项目:FinanceAnalytics    文件:IssuerMulticurveMarketDataBuilder.java   
/**
 * Returns a map of curve names to issuer details where the curve
 * configuration type is {@link IssuerCurveTypeConfiguration}.
 *
 * @param configTypes the configuration types of the curves, keyed by curve name
 * @return a map of curve names to issuer details where the curve
 * configuration type is {@link IssuerCurveTypeConfiguration}
 */
private LinkedListMultimap<String, Pair<Object, LegalEntityFilter<LegalEntity>>> createIssuerMap(
    Multimap<String, CurveTypeConfiguration> configTypes) {

  LinkedListMultimap<String, Pair<Object, LegalEntityFilter<LegalEntity>>> results = LinkedListMultimap.create();

  for (Map.Entry<String, CurveTypeConfiguration> entry : configTypes.entries()) {
    String curveName = entry.getKey();
    CurveTypeConfiguration configType = entry.getValue();

    if (configType instanceof IssuerCurveTypeConfiguration) {
      IssuerCurveTypeConfiguration issuerType = (IssuerCurveTypeConfiguration) configType;
      results.put(curveName, Pairs.<Object, LegalEntityFilter<LegalEntity>>of(issuerType.getKeys(), issuerType.getFilters()));
    }
  }
  return results;
}
项目:anima    文件:LocalSessionMgr.java   
/**
 * 
 * @param sid
 * @param serverType
 * @param sequence
 * @param localSession
 * @return
 */
public LocalSession addSession(String serverId,String serverType,int sessionId,LocalSession localSession) {
    if (localSession == null) {
        return null;
    }
    localSession.setServerId(serverId);
    localSession.setServerType(serverType);
    localSession.setId(sessionId);
    localSession.setlistener(this.closeListener);
    localSession.setStatus(ISession.STATUS_WORKING);
    sessionBySid.put(serverId, localSession);

    synchronized(sessionByStype) {
        LinkedListMultimap<String, LocalSession> multimap = sessionByStype.get(serverType);
        if (multimap == null) {
            multimap = LinkedListMultimap.create();
            sessionByStype.put(serverType, multimap);
        }
        multimap.put(serverId, localSession);
    }
    return localSession;
}
项目:magnolia-news    文件:NewsSearchRenderableDefinition.java   
@Inject
public NewsSearchRenderableDefinition(Node content, RD definition, RenderingModel<?> parent, TemplatingFunctions templatingFunctions) {
    super(content, definition, parent);
    this.templatingFunctions = templatingFunctions;
    setWorkspace(NewsRepositoryConstants.COLLABORATION);
    setNodetype(NewsNodeTypes.News.NAME);

    filter = LinkedListMultimap.create();
    Set<String> parameters = webContext.getParameters().keySet();
    for (String parameterKey : parameters) {
        if (allowedParameters().contains(parameterKey)) {
            String[] parameterValues = webContext.getParameterValues(parameterKey);
            for (String parameterValue : parameterValues) {
                if (StringUtils.isNotEmpty(parameterValue)) {
                    filter.get(parameterKey).add(parameterValue);
                }
            }
        }
        webContext.remove(parameterKey);
    }
    LOGGER.debug("Running constructor NewsSearchRenderableDefinition");
}
项目:magnolia-templating    文件:ResultsAreaRenderableDefinition.java   
@Inject
public ResultsAreaRenderableDefinition(Node content, RD definition, RenderingModel<?> parent, FoundationTemplatingFunctions templatingFunctions, RenderingUtils renderingUtils) {
    super(content, definition, parent, templatingFunctions);
    this.renderingUtils = renderingUtils;

    paramFilter = LinkedListMultimap.create();
    Set<String> parameters = webContext.getParameters().keySet();
    for (String parameterKey : parameters) {
        if (allowedParameters().contains(parameterKey)) {
            String[] parameterValues = webContext.getParameterValues(parameterKey);
            for (String parameterValue : parameterValues) {
                if (StringUtils.isNotEmpty(parameterValue)) {
                    paramFilter.get(parameterKey).add(parameterValue);
                }
            }
        }
        webContext.remove(parameterKey);
    }
}
项目:core-java    文件:ReferenceValidator.java   
/**
 * Returns those fields and functions, that may be used for the enrichment at the moment.
 *
 * @return a {@code ValidationResult} data transfer object, containing the valid fields and
 * functions.
 */
ValidationResult validate() {
    final List<EnrichmentFunction<?, ?, ?>> functions = new LinkedList<>();
    final Multimap<FieldDescriptor, FieldDescriptor> fields = LinkedListMultimap.create();
    for (FieldDescriptor enrichmentField : enrichmentDescriptor.getFields()) {
        final Collection<FieldDescriptor> sourceFields = findSourceFields(enrichmentField);
        putEnrichmentsByField(functions, fields, enrichmentField, sourceFields);
    }
    final ImmutableMultimap<FieldDescriptor, FieldDescriptor> sourceToTargetMap =
            ImmutableMultimap.copyOf(fields);
    final ImmutableList<EnrichmentFunction<?, ?, ?>> enrichmentFunctions =
            ImmutableList.copyOf(functions);
    final ValidationResult result = new ValidationResult(enrichmentFunctions,
                                                         sourceToTargetMap);
    return result;
}
项目:magnolia-blog    文件:BlogSearchRenderableDefinition.java   
@Inject
public BlogSearchRenderableDefinition(Node content, RD definition, RenderingModel<?> parent, TemplatingFunctions templatingFunctions) {
    super(content, definition, parent);
    this.templatingFunctions = templatingFunctions;

    setWorkspace(BlogRepositoryConstants.COLLABORATION);
    setNodetype(BlogsNodeTypes.Blog.NAME);

    filter = LinkedListMultimap.create();
    Set<String> parameters = webContext.getParameters().keySet();
    for (String parameterKey : parameters) {
        if (allowedParameters().contains(parameterKey)) {
            String[] parameterValues = webContext.getParameterValues(parameterKey);
            for (String parameterValue : parameterValues) {
                if (StringUtils.isNotEmpty(parameterValue)) {
                    filter.get(parameterKey).add(parameterValue);
                }
            }
        }
        webContext.remove(parameterKey);
    }
    LOGGER.debug("Running constructor BlogSearchRenderableDefinition");
}
项目:j2objc    文件:Rewriter.java   
@Override
public void endVisit(FieldDeclaration node) {
  LinkedListMultimap<Integer, VariableDeclarationFragment> newDeclarations =
      rewriteExtraDimensions(node.getType(), node.getFragments());
  if (newDeclarations != null) {
    List<BodyDeclaration> bodyDecls = TreeUtil.getBodyDeclarations(node.getParent());
    int location = 0;
    while (location < bodyDecls.size() && !node.equals(bodyDecls.get(location))) {
      location++;
    }
    for (Integer dimensions : newDeclarations.keySet()) {
      List<VariableDeclarationFragment> fragments = newDeclarations.get(dimensions);
      FieldDeclaration newDecl = new FieldDeclaration(fragments.get(0));
      newDecl.getFragments().addAll(fragments.subList(1, fragments.size()));
      bodyDecls.add(++location, newDecl);
    }
  }
}
项目:flora-on-server    文件:SimpleOccurrenceClusterer.java   
public SimpleOccurrenceClusterer(Iterator<SimpleOccurrence> simpleOccurrences, int minDist) {
    Map<Point2D, SimpleOccurrence> occMap = new HashMap<>();
    out = LinkedListMultimap.create();
    Multimap<Integer, SimpleOccurrence> singletons = LinkedListMultimap.create();
    int counter = 0;

    while(simpleOccurrences.hasNext()) {
        SimpleOccurrence so = simpleOccurrences.next();
        UTMCoordinate utm = so._getUTMCoordinates();
        if(utm != null) {
            if(!so.getPrecision()._isImprecise())
                occMap.put(new Point2DAlwaysDifferent(utm.getX(), utm.getY(), null, null), so);
            else {
                singletons.put(counter, so);
                counter++;
            }
        }
    }
    DBSCANClusterer<Point2D> cls = new DBSCANClusterer<>(minDist, 0);
    List<Cluster<Point2D>> clusters = cls.cluster(occMap.keySet());

    for (int i = 0; i < clusters.size(); i++) {
        for(Point2D p : clusters.get(i).getPoints()) {
            out.put(i + counter, occMap.get(p));
        }
    }
    out.putAll(singletons);
}
项目:infix    文件:StaticTestingUtils.java   
public static final ListMultimap<Integer, String> parseMessage(String baseMsg) {
    ListMultimap<Integer, String> dict = LinkedListMultimap.create();
    char[] baseMsgArray = baseMsg.toCharArray();
    int index = 0;
    for (int i = 0; i < baseMsgArray.length; i++) {
        if (baseMsgArray[i] == 0x01) {
            String fixField = baseMsg.substring(index, i);
            char[] fixFieldArray = fixField.toCharArray();
            for (int j = 0; j < fixFieldArray.length; j++) {
                if (fixFieldArray[j] == '=') {
                    String num = fixField.substring(0, j);
                    int n = Integer.parseInt(num);
                    String val = fixField.substring(j + 1, fixField.length());
                    dict.put(n, val);
                    break;
                }
            }
            index = i + 1;
        }
    }
    return dict;
}
项目:uapi    文件:ServiceHolder.java   
ServiceHolder(
        final String from,
        final Object service,
        final String serviceId,
        final Dependency[] dependencies,
        final ISatisfyHook satisfyHook
) {
    ArgumentChecker.notNull(from, "from");
    ArgumentChecker.notNull(service, "service");
    ArgumentChecker.notEmpty(serviceId, "serviceId");
    ArgumentChecker.notNull(dependencies, "dependencies");
    ArgumentChecker.notNull(satisfyHook, "satisfyHook");
    this._svc = service;
    this._svcId = serviceId;
    this._from = from;
    this._qualifiedSvcId = new QualifiedServiceId(serviceId, from);
    this._satisfyHook = satisfyHook;
    this._dependencies = LinkedListMultimap.create();
    this._stateMonitors = new LinkedList<>();

    Observable.from(dependencies)
            .subscribe(dependency -> this._dependencies.put(dependency, null));

    // Create StateMonitor here since it need read dependencies information.
    this._stateManagement = new StateManagement();
}
项目:gerrit    文件:EventRecorder.java   
public EventRecorder(DynamicSet<UserScopedEventListener> eventListeners, IdentifiedUser user) {
  recordedEvents = LinkedListMultimap.create();

  eventListenerRegistration =
      eventListeners.add(
          new UserScopedEventListener() {
            @Override
            public void onEvent(Event e) {
              if (e instanceof ReviewerDeletedEvent) {
                recordedEvents.put(ReviewerDeletedEvent.TYPE, (ReviewerDeletedEvent) e);
              } else if (e instanceof RefEvent) {
                RefEvent event = (RefEvent) e;
                String key =
                    refEventKey(
                        event.getType(), event.getProjectNameKey().get(), event.getRefName());
                recordedEvents.put(key, event);
              }
            }

            @Override
            public CurrentUser getUser() {
              return user;
            }
          });
}
项目:gerrit    文件:AutoRegisterModules.java   
AutoRegisterModules discover() throws InvalidPluginException {
  sysSingletons = new HashSet<>();
  sysListen = LinkedListMultimap.create();
  initJs = null;

  sshGen.setPluginName(pluginName);
  httpGen.setPluginName(pluginName);

  scan();

  if (!sysSingletons.isEmpty() || !sysListen.isEmpty() || initJs != null) {
    sysModule = makeSystemModule();
  }
  sshModule = sshGen.create();
  httpModule = httpGen.create();
  return this;
}
项目:android-retrolambda-lombok    文件:Source.java   
public Map<Node, Collection<SourceStructure>> getSourceStructures() {
    if (cachedSourceStructures != null) return cachedSourceStructures;
    parseCompilationUnit();
    ListMultimap<Node, SourceStructure> map = LinkedListMultimap.create();

    org.parboiled.Node<Node> pNode = parsingResult.parseTreeRoot;

    buildSourceStructures(pNode, null, map);

    Map<Node, Collection<SourceStructure>> result = map.asMap();

    for (Collection<SourceStructure> structures : result.values()) {
        for (SourceStructure structure : structures) {
            structure.setPosition(new Position(
                    mapPosition(structure.getPosition().getStart()),
                    mapPosition(structure.getPosition().getEnd())));
        }
    }

    return cachedSourceStructures = result;
}
项目:worker-service    文件:CommandsTest.java   
EmailAnswer submitEmailHelper(String email, String platform, int workerID, Consumer<Context> responseVerifier) throws Exception {
    return submit(communication -> {
                when(communication.submitWorker(email, platform, LinkedListMultimap.create())).thenReturn(CompletableFuture.completedFuture(workerID));
            },
            context -> {
                when(context.getPathTokens().get("platform")).thenReturn(platform);
                Email build = Email.newBuilder().setEmail(email).build();
                TypedData data = mock(TypedData.class);
                try {
                    when(data.getText()).thenReturn(printer.print(build));
                } catch (InvalidProtocolBufferException e) {
                    throw new RuntimeException(e);
                }
                when(context.getRequest().getBody()).thenReturn(Promise.value(data));
            },
            Commands::submitEmail,
            responseVerifier
    );
}
项目:MOE    文件:MetadataScrubber.java   
/**
 * A utility method that is useful for stripping a list of words from all the fields of the
 * RevisionMetadata.
 *
 * @param rm the RevisionMetadata to scrub
 * @param words the list of words to replace
 * @param replacement the String to replace the target words with
 * @param wordAlone true if the words to match must surrounded by word boundaries
 * @return a copy representing the RevisionMetadata resulting from the scrub
 */
public static RevisionMetadata stripFromAllFields(
    RevisionMetadata rm, List<String> words, String replacement, boolean wordAlone) {

  String newId = rm.id();
  String newAuthor = rm.author();
  String newDescription = rm.description();
  ListMultimap<String, String> newFields = LinkedListMultimap.create(rm.fields());
  for (String word : words) {
    String regex = (wordAlone) ? ("(?i)(\\b)" + word + "(\\b)") : ("(?i)" + word);
    newId = newId.replaceAll(regex, replacement);
    newAuthor = newAuthor.replaceAll(regex, replacement);
    newDescription = newDescription.replaceAll(regex, replacement);
    for (Entry<String, String> entry : newFields.entries()) {
      entry.setValue(entry.getValue().replaceAll(regex, replacement));
    }
  }
  return rm.toBuilder()
      .id(newId)
      .author(newAuthor)
      .description(newDescription)
      .replacingFieldsWith(ImmutableSetMultimap.copyOf(newFields))
      .build();
}
项目:sqlg    文件:SqlgUtil.java   
public static void setParametersOnStatement(SqlgGraph sqlgGraph, LinkedList<SchemaTableTree> schemaTableTreeStack, PreparedStatement preparedStatement, int parameterIndex) throws SQLException {
    Multimap<String, Object> keyValueMap = LinkedListMultimap.create();
    for (SchemaTableTree schemaTableTree : schemaTableTreeStack) {
        for (HasContainer hasContainer : schemaTableTree.getHasContainers()) {
            if (!sqlgGraph.getSqlDialect().supportsBulkWithinOut() || !isBulkWithinAndOut(sqlgGraph, hasContainer)) {
                WhereClause whereClause = WhereClause.from(hasContainer.getPredicate());
                whereClause.putKeyValueMap(hasContainer, keyValueMap);
            }
        }
        for (AndOrHasContainer andOrHasContainer : schemaTableTree.getAndOrHasContainers()) {
            andOrHasContainer.setParameterOnStatement(keyValueMap);
        }
    }
    List<ImmutablePair<PropertyType, Object>> typeAndValues = SqlgUtil.transformToTypeAndValue(keyValueMap);
    //This is for selects
    setKeyValuesAsParameter(sqlgGraph, false, parameterIndex, preparedStatement, typeAndValues);
}
项目:galaxy-fds-sdk-java    文件:Signer.java   
/**
 * Sign the specified http request.
 *
 * @param httpMethod  The http request method({@link #HttpMethod})
 * @param uri The uri string
 * @param httpHeaders The http request headers
 * @param secretAccessKeyId The user's secret access key
 * @param algorithm   The sign algorithm({@link #SignAlgorithm})
 * @return Byte buffer of the signed result
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws URISyntaxException
 */
public static byte[] sign(HttpMethod httpMethod, URI uri,
    LinkedListMultimap<String, String> httpHeaders, String secretAccessKeyId,
    SignAlgorithm algorithm) throws NoSuchAlgorithmException,
    InvalidKeyException {
  Preconditions.checkNotNull(httpMethod);
  Preconditions.checkNotNull(uri);
  Preconditions.checkNotNull(secretAccessKeyId);
  Preconditions.checkNotNull(algorithm);

  String stringToSign = constructStringToSign(httpMethod,
      uri, httpHeaders);
  if (LOG.isDebugEnabled()) {
    LOG.debug("Sign for request: " + httpMethod + " " + uri
        + ", stringToSign=" + stringToSign);
  }

  Mac mac = Mac.getInstance(algorithm.name());
  mac.init(new SecretKeySpec(secretAccessKeyId.getBytes(), algorithm.name()));
  return mac.doFinal(stringToSign.getBytes());
}
项目:error-prone    文件:AssistedParameters.java   
private Multimap<Type, VariableTree> partitionParametersByType(
    List<VariableTree> parameters, VisitorState state) {

  Types types = state.getTypes();
  Multimap<Type, VariableTree> multimap = LinkedListMultimap.create();

  variables:
  for (VariableTree node : parameters) {
    // Normalize Integer => int
    Type type = types.unboxedTypeOrType(ASTHelpers.getType(node));
    for (Type existingType : multimap.keySet()) {
      if (types.isSameType(existingType, type)) {
        multimap.put(existingType, node);
        continue variables;
      }
    }

    // A new type for the map.
    multimap.put(type, node);
  }

  return multimap;
}
项目:magnolia-templating    文件:ResultsAreaRenderableDefinition.java   
@Inject
public ResultsAreaRenderableDefinition(Node content, RD definition, RenderingModel<?> parent, FoundationTemplatingFunctions templatingFunctions, RenderingUtils renderingUtils) {
    super(content, definition, parent, templatingFunctions);
    this.renderingUtils = renderingUtils;

    paramFilter = LinkedListMultimap.create();
    Set<String> parameters = webContext.getParameters().keySet();
    for (String parameterKey : parameters) {
        if (allowedParameters().contains(parameterKey)) {
            String[] parameterValues = webContext.getParameterValues(parameterKey);
            for (String parameterValue : parameterValues) {
                if (StringUtils.isNotEmpty(parameterValue)) {
                    paramFilter.get(parameterKey).add(parameterValue);
                }
            }
        }
        webContext.remove(parameterKey);
    }
}
项目:SPLevo    文件:MergeVariationPointsHandler.java   
private Multimap<String, SoftwareElement> collectSoftwareElementsToMove(Set<VariationPoint> vpsToMerge,
        VariationPoint survivingVP) {
    Multimap<String, SoftwareElement> variantSoftwareElements = LinkedListMultimap.create();
    for (VariationPoint vp : vpsToMerge) {

        // skip the surviving vp to not modify the emf elements
        if (survivingVP == vp) {
            continue;
        }

        for (Variant variant : vp.getVariants()) {
            variantSoftwareElements.putAll(variant.getId(), variant.getImplementingElements());
        }
    }
    return variantSoftwareElements;
}
项目:org.pshdl    文件:HDLFunctions.java   
public static void init(CompilerInformation info, IServiceProvider sp) {
    signatures = LinkedListMultimap.create();
    provider = LinkedListMultimap.create();
    dynamicProvider = LinkedListMultimap.create();
    final Collection<IDynamicFunctionProvider> dyns = sp.getAllDynamicFunctionProvider();
    for (final IDynamicFunctionProvider dynProv : dyns) {
        final HDLQualifiedName[] registeredNames = dynProv.getDynamicFunctions();
        for (final HDLQualifiedName hdlQualifiedName : registeredNames) {
            dynamicProvider.put(hdlQualifiedName, dynProv);
        }
    }
    final Collection<INativeFunctionProvider> nativeStaticProvider = sp.getAllNativeFunctionProvider();
    for (final INativeFunctionProvider snfp : nativeStaticProvider) {
        final HDLFunctionImplementation[] functionImpl = snfp.getStaticFunctions();
        for (final HDLFunctionImplementation funcImpl : functionImpl) {
            for (final HDLFunction hdlFunction : funcImpl.signatures()) {
                final HDLQualifiedName fqnFunction = new HDLQualifiedName(hdlFunction.getName());
                provider.put(fqnFunction, funcImpl);
                signatures.put(fqnFunction, hdlFunction);
            }
        }
    }
}
项目:MuSICo    文件:EnglishNLP.java   
public static void readVerbClasses(String path) throws IOException {
    levin_verb_classes = LinkedListMultimap.create();
    BufferedReader input = new BufferedReader( new FileReader(new File(path)) );
    String aux = null;
    String levin_class = null;
    String[] verbs = null;
    int n_classes = 0;
    while ( ( aux = input.readLine() ) != null ) {
        if ( aux.startsWith("VERB") ) {
            String[] data = aux.split("\\s+",2);
            levin_class = data[0];
            n_classes++;
        } else if ( aux.trim().length() != 0) {
            verbs = aux.split("\\s+");
            for (int z = 0; z < verbs.length; z++) levin_verb_classes.put(verbs[z],levin_class);
        }
    }
    System.out.println("Total Levin classes: " + n_classes);
    System.out.println("Number of unique verbs: " + levin_verb_classes.keySet().size());    
    input.close();
}
项目:bazel    文件:BuildEncyclopediaProcessor.java   
/**
 * Create a mapping of rules based on rule type and family.
 */
private void createRuleMapping(Iterable<RuleDocumentation> docEntries,
    Map<String, ListMultimap<RuleType, RuleDocumentation>> ruleMapping)
    throws BuildEncyclopediaDocException {
  for (RuleDocumentation ruleDoc : docEntries) {
    RuleClass ruleClass = ruleClassProvider.getRuleClassMap().get(ruleDoc.getRuleName());
    if (ruleClass != null) {
      String ruleFamily = ruleDoc.getRuleFamily();
      if (!ruleMapping.containsKey(ruleFamily)) {
        ruleMapping.put(ruleFamily, LinkedListMultimap.<RuleType, RuleDocumentation>create());
      }
      if (ruleClass.isDocumented()) {
        ruleMapping.get(ruleFamily).put(ruleDoc.getRuleType(), ruleDoc);
      }
    } else {
      throw ruleDoc.createException("Can't find RuleClass for " + ruleDoc.getRuleName());
    }
  }
}
项目:bazel    文件:PreciseAspectResolver.java   
@Override
public ImmutableMultimap<Attribute, Label> computeAspectDependencies(Target target,
    DependencyFilter dependencyFilter)
    throws InterruptedException {
  Multimap<Attribute, Label> result = LinkedListMultimap.create();
  if (target instanceof Rule) {
    Multimap<Attribute, Label> transitions =
        ((Rule) target).getTransitions(DependencyFilter.NO_NODEP_ATTRIBUTES);
    for (Entry<Attribute, Label> entry : transitions.entries()) {
      Target toTarget;
      try {
        toTarget = packageProvider.getTarget(eventHandler, entry.getValue());
        result.putAll(
            AspectDefinition.visitAspectsIfRequired(
                target,
                entry.getKey(),
                toTarget,
                dependencyFilter));
      } catch (NoSuchThingException e) {
        // Do nothing. One of target direct deps has an error. The dependency on the BUILD file
        // (or one of the files included in it) will be reported in the query result of :BUILD.
      }
    }
  }
  return ImmutableMultimap.copyOf(result);
}
项目:bazel    文件:ImmutableSortedKeyListMultimapTest.java   
@Test
public void builderPutAllMultimap() {
  Multimap<String, Integer> toPut = LinkedListMultimap.create();
  toPut.put("foo", 1);
  toPut.put("bar", 4);
  toPut.put("foo", 2);
  toPut.put("foo", 3);
  Multimap<String, Integer> moreToPut = LinkedListMultimap.create();
  moreToPut.put("foo", 6);
  moreToPut.put("bar", 5);
  moreToPut.put("foo", 7);
  ImmutableSortedKeyListMultimap.Builder<String, Integer> builder
      = ImmutableSortedKeyListMultimap.builder();
  builder.putAll(toPut);
  builder.putAll(moreToPut);
  Multimap<String, Integer> multimap = builder.build();
  assertThat(multimap).valuesForKey("foo").containsExactly(1, 2, 3, 6, 7).inOrder();
  assertThat(multimap).valuesForKey("bar").containsExactly(4, 5).inOrder();
  assertThat(multimap).hasSize(7);
}