Java Code Examples for com.google.common.collect.ImmutableSetMultimap#get()

The following examples show how to use com.google.common.collect.ImmutableSetMultimap#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LinkageMonitor.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a message on {@code snapshotSymbolProblems} that do not exist in {@code
 * baselineProblems}.
 */
@VisibleForTesting
static String messageForNewErrors(
    ImmutableSetMultimap<SymbolProblem, ClassFile> snapshotSymbolProblems,
    Set<SymbolProblem> baselineProblems,
    ClassPathResult classPathResult) {
  Set<SymbolProblem> newProblems =
      Sets.difference(snapshotSymbolProblems.keySet(), baselineProblems);
  StringBuilder message =
      new StringBuilder("Newly introduced problem" + (newProblems.size() > 1 ? "s" : "") + ":\n");
  Builder<ClassPathEntry> problematicJars = ImmutableSet.builder();
  for (SymbolProblem problem : newProblems) {
    message.append(problem + "\n");

    // This is null for ClassNotFound error.
    ClassFile containingClass = problem.getContainingClass();
    if (containingClass != null) {
      problematicJars.add(containingClass.getClassPathEntry());
    }

    for (ClassFile classFile : snapshotSymbolProblems.get(problem)) {
      message.append(
          String.format(
              "  referenced from %s (%s)\n",
              classFile.getBinaryName(), classFile.getClassPathEntry()));
      problematicJars.add(classFile.getClassPathEntry());
    }
  }

  message.append("\n");
  message.append(classPathResult.formatDependencyPaths(problematicJars.build()));

  return message.toString();
}
 
Example 2
Source File: ViewGeoLocationsRestController.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
private List<JsonViewRowGeoLocation> retrieveGeoLocationsForBPartnerLocationId(final ImmutableSetMultimap<Integer, DocumentId> rowIdsByBPartnerLocationRepoId)
{
	if (rowIdsByBPartnerLocationRepoId.isEmpty())
	{
		return ImmutableList.of();
	}

	final List<JsonViewRowGeoLocation> result = new ArrayList<>();

	final ImmutableSet<Integer> bpartnerLocationRepoIds = rowIdsByBPartnerLocationRepoId.keySet();
	for (final GeographicalCoordinatesWithBPartnerLocationId bplCoordinates : bpartnersRepo.getGeoCoordinatesByBPartnerLocationIds(bpartnerLocationRepoIds))
	{
		final int bpartnerLocationRepoId = bplCoordinates.getBpartnerLocationId().getRepoId();
		final ImmutableSet<DocumentId> rowIds = rowIdsByBPartnerLocationRepoId.get(bpartnerLocationRepoId);
		if (rowIds.isEmpty())
		{
			// shall not happen
			logger.warn("Ignored unexpected bpartnerLocationId={}. We have no rows for it.", bpartnerLocationRepoId);
			continue;
		}

		final GeographicalCoordinates coordinate = bplCoordinates.getCoordinate();

		for (final DocumentId rowId : rowIds)
		{
			result.add(JsonViewRowGeoLocation.builder()
					.rowId(rowId)
					.latitude(coordinate.getLatitude())
					.longitude(coordinate.getLongitude())
					.build());
		}
	}

	return result;
}
 
Example 3
Source File: ViewGeoLocationsRestController.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
private List<JsonViewRowGeoLocation> retrieveGeoLocationsForBPartnerId(final ImmutableSetMultimap<BPartnerId, DocumentId> rowIdsByBPartnerId)
{
	if (rowIdsByBPartnerId.isEmpty())
	{
		return ImmutableList.of();
	}

	final List<JsonViewRowGeoLocation> result = new ArrayList<>();

	final ImmutableSet<BPartnerId> bpartnerIds = rowIdsByBPartnerId.keySet();
	for (final GeographicalCoordinatesWithBPartnerLocationId bplCoordinates : bpartnersRepo.getGeoCoordinatesByBPartnerIds(bpartnerIds))
	{
		final BPartnerId bpartnerId = bplCoordinates.getBPartnerId();
		final ImmutableSet<DocumentId> rowIds = rowIdsByBPartnerId.get(bpartnerId);
		if (rowIds.isEmpty())
		{
			// shall not happen
			logger.warn("Ignored unexpected bpartnerId={}. We have no rows for it.", bpartnerId);
			continue;
		}

		final GeographicalCoordinates coordinate = bplCoordinates.getCoordinate();

		for (final DocumentId rowId : rowIds)
		{
			result.add(JsonViewRowGeoLocation.builder()
					.rowId(rowId)
					.latitude(coordinate.getLatitude())
					.longitude(coordinate.getLongitude())
					.build());
		}
	}

	return result;
}
 
Example 4
Source File: ClassUsageTrackerTest.java    From buck with Apache License 2.0 5 votes vote down vote up
private void assertFilesRead(Path jarPath, String... files) {
  ImmutableSetMultimap<Path, Path> classUsageMap = tracker.getClassUsageMap();

  ImmutableSet<Path> paths = classUsageMap.get(jarPath);

  assertEquals(files.length, paths.size());

  for (String file : files) {
    assertTrue(fileWasRead(jarPath, file));
  }
}
 
Example 5
Source File: TreasuryShareRound.java    From Rails with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create a list of certificates that a player may buy in a Stock Round,
 * taking all rules into account.
 *
 * @return List of buyable certificates.
 */
@Override
public void setBuyableCerts() {
    ImmutableSet<PublicCertificate> certs;
    PublicCertificate cert;
    PortfolioModel from;
    int price;
    int number;

    int cash = operatingCompany.getCash();

    /* Get the unique Pool certificates and check which ones can be bought */
    from = pool;
    ImmutableSetMultimap<PublicCompany, PublicCertificate> map =
            from.getCertsPerCompanyMap();

    for (PublicCompany comp : map.keySet()) {
        certs = map.get(comp);
        // if (certs.isEmpty()) continue; // TODO: Check if removal is correct

        cert = Iterables.get(certs, 0);

        // TODO For now, only consider own certificates.
        // This will have to be revisited with 1841.
        if (comp != operatingCompany) continue;

        // Shares already owned
        int ownedShare =
                operatingCompany.getPortfolioModel().getShare(operatingCompany);
        // Max share that may be owned
        int maxShare = GameDef.getGameParameterAsInt(this, GameDef.Parm.TREASURY_SHARE_LIMIT);
        // Max number of shares to add
        int maxBuyable =
                (maxShare - ownedShare) / operatingCompany.getShareUnit();
        // Max number of shares to buy
        number = Math.min(certs.size(), maxBuyable);
        if (number == 0) continue;

        price = comp.getMarketPrice();

        // Does the company have enough cash?
        while (number > 0 && cash < number * price)
            number--;

        if (number > 0) {
            possibleActions.add(new BuyCertificate(comp, cert.getShare(), from.getParent(), price,
                    number));
        }
    }

}
 
Example 6
Source File: DerivedQuerySelector2016.java    From tac-kbp-eal with MIT License 4 votes vote down vote up
private ImmutableSetMultimap<String, EntryPoint> gatherEntryPointsFound(
    final ImmutableSet<Symbol> docIDsToScore, final File baseSystemDir,
    final Set<String> systemsToUse, final ImmutableMap<Symbol, File> goldDocIDToFileMap,
    final CoreNLPXMLLoader coreNLPXMLLoader,
    final ImmutableMap<Symbol, File> coreNLPProcessedRawDocs) throws IOException {
  final ImmutableSetMultimap.Builder<String, EntryPoint> entryPointsFoundBySystemB =
      ImmutableSetMultimap.builder();

  // we log the distribution of event types in the corpus for diagnostic purposes
  final ImmutableMultiset.Builder<String> allEREEventTypes = ImmutableMultiset.builder();

  for (Symbol docID : docIDsToScore) {
    // EvalHack - 2016 dry run contains some files for which Serif spuriously adds this document ID
    docID = Symbol.from(docID.asString().replace("-kbp", ""));
    final EREDocument ereDoc = getEREDocument(docID, goldDocIDToFileMap);
    final CoreNLPDocument coreNLPDoc =
        coreNLPXMLLoader.loadFrom(coreNLPProcessedRawDocs.get(docID));
    final EREAligner ereAligner = EREAligner.create(ereDoc, Optional.of(coreNLPDoc),
        ontologyMapper);

    // build an index of RoleAndIds to hoppers for lookup in the loop below
    final ImmutableSetMultimap<RoleAndID, DocAndHopper> argsToDocEvents =
        indexArgsToEventHopper(docID, ereDoc, allEREEventTypes);

    for (final String system : systemsToUse) {
      final File systemDir = new File(baseSystemDir, system);

      try (final SystemOutputStore systemOutput = KBPEA2016OutputLayout.get().open(systemDir)) {
        final ImmutableSet.Builder<RoleAndID> alignedEREArgs = ImmutableSet.builder();

        // first, gather all document-level arguments which this system found which can
        // be aligned to ERE
        final Iterable<Response> responses = FluentIterable
            .from(systemOutput.read(docID).arguments().responses())
            .filter(BANNED_ROLES_FILTER)
            .filter(Predicates.compose(not(in(BANNED_EVENTS)), type()));

        for (final Response response : responses) {
          final Optional<ScoringCorefID> argID =
              ereAligner.argumentForResponse(response);
          // query entry points can only be entities, not value fillers
          if (argID.isPresent() && argID.get().scoringEntityType().isEntityType()) {
            alignedEREArgs.add(RoleAndID.of(response.type().asString(), response.role().asString(),
                argID.get().withinTypeID()));
          }
        }

        // second, map these to document-level hoppers
        for (final RoleAndID alignedArg : alignedEREArgs.build()) {
          for (final DocAndHopper docAndHopper : argsToDocEvents.get(alignedArg)) {
            entryPointsFoundBySystemB.put(system, EntryPoint.of(docAndHopper, alignedArg));
          }
        }
      }
    }
  }

  log.info("Distribution of event types in ERE: {}",
      Multisets.copyHighestCountFirst(allEREEventTypes.build()));

  return entryPointsFoundBySystemB.build();
}
 
Example 7
Source File: WorkspaceAndProjectGenerator.java    From buck with Apache License 2.0 4 votes vote down vote up
/**
 * Create individual schemes for each project and associated tests. Provided as a workaround for a
 * change in Xcode 10 where Apple started building all scheme targets and tests when clicking on a
 * single item from the test navigator. These schemes will be written inside of the xcodeproj.
 *
 * @param buildTargetToPBXTarget Map that, when reversed, is used to look up of the BuildTarget to
 *     generate the output directory for the scheme.
 * @param schemeTargets Targets to be considered for scheme. Allows external filtering of targets
 *     included in the project's scheme.
 * @param generatedProjectToPbxTargets
 * @param targetToProjectPathMap
 * @param buildForTestTargets
 * @param ungroupedTestTargets
 * @throws IOException
 */
private void writeWorkspaceSchemesForProjects(
    ImmutableMap<BuildTarget, PBXTarget> buildTargetToPBXTarget,
    ImmutableSet<PBXTarget> schemeTargets,
    ImmutableSetMultimap<PBXProject, PBXTarget> generatedProjectToPbxTargets,
    ImmutableMap<PBXTarget, Path> targetToProjectPathMap,
    ImmutableSetMultimap<String, PBXTarget> buildForTestTargets,
    ImmutableSetMultimap<String, PBXTarget> ungroupedTestTargets)
    throws IOException {

  ImmutableSetMultimap<PBXTarget, BuildTarget> pbxTargetToBuildTarget =
      buildTargetToPBXTarget.asMultimap().inverse();

  // create all the scheme generators for each project
  for (PBXProject project : generatedProjectToPbxTargets.keys()) {
    String schemeName = project.getName();

    ImmutableSet<PBXTarget> projectTargets = generatedProjectToPbxTargets.get(project);

    ImmutableSet<PBXTarget> orderedBuildTestTargets =
        projectTargets.stream()
            .filter(pbxTarget -> buildForTestTargets.values().contains(pbxTarget))
            .collect(ImmutableSet.toImmutableSet());

    ImmutableSet<PBXTarget> orderedRunTestTargets =
        projectTargets.stream()
            .filter(pbxTarget -> ungroupedTestTargets.values().contains(pbxTarget))
            .collect(ImmutableSet.toImmutableSet());

    // add all non-test targets as full build targets
    ImmutableSet<PBXTarget> orderedBuildTargets =
        projectTargets.stream()
            .filter(pbxTarget -> schemeTargets.contains(pbxTarget))
            .filter(pbxTarget -> !orderedBuildTestTargets.contains(pbxTarget))
            .collect(ImmutableSet.toImmutableSet());

    // generate scheme inside xcodeproj
    ImmutableSet<BuildTarget> buildTargets =
        pbxTargetToBuildTarget.get(project.getTargets().get(0));
    BuildTarget buildTarget = buildTargets.iterator().next();
    Path projectOutputDirectory =
        buildTarget
            .getCellRelativeBasePath()
            .getPath()
            .toPath(rootCell.getFilesystem().getFileSystem())
            .resolve(project.getName() + ".xcodeproj");

    SchemeGenerator schemeGenerator =
        buildSchemeGenerator(
            targetToProjectPathMap,
            projectOutputDirectory,
            schemeName,
            Optional.empty(),
            Optional.empty(),
            orderedBuildTargets,
            orderedBuildTestTargets,
            orderedRunTestTargets,
            Optional.empty(),
            Optional.empty(),
            Optional.empty());

    schemeGenerator.writeScheme();
    schemeGenerators.put(schemeName, schemeGenerator);
  }
}
 
Example 8
Source File: WorkspaceAndProjectGenerator.java    From buck with Apache License 2.0 4 votes vote down vote up
private void writeWorkspaceSchemes(
    String workspaceName,
    Path outputDirectory,
    ImmutableMap<String, XcodeWorkspaceConfigDescriptionArg> schemeConfigs,
    ImmutableSetMultimap<String, Optional<TargetNode<?>>> schemeNameToSrcTargetNode,
    ImmutableSetMultimap<String, PBXTarget> buildForTestTargets,
    ImmutableSetMultimap<String, PBXTarget> ungroupedTestTargets,
    ImmutableMap<PBXTarget, Path> targetToProjectPathMap,
    ImmutableMap<BuildTarget, PBXTarget> buildTargetToPBXTarget)
    throws IOException {
  for (Map.Entry<String, XcodeWorkspaceConfigDescriptionArg> schemeConfigEntry :
      schemeConfigs.entrySet()) {
    String schemeName = schemeConfigEntry.getKey();
    XcodeWorkspaceConfigDescriptionArg schemeConfigArg = schemeConfigEntry.getValue();
    if (schemeConfigArg.getSrcTarget().isPresent()
        && !focusModules.isFocusedOn(schemeConfigArg.getSrcTarget().get())) {
      continue;
    }

    ImmutableSet<PBXTarget> orderedBuildTargets =
        schemeNameToSrcTargetNode.get(schemeName).stream()
            .distinct()
            .flatMap(RichStream::from)
            .map(TargetNode::getBuildTarget)
            .map(buildTargetToPBXTarget::get)
            .filter(Objects::nonNull)
            .collect(ImmutableSet.toImmutableSet());
    ImmutableSet<PBXTarget> orderedBuildTestTargets = buildForTestTargets.get(schemeName);
    ImmutableSet<PBXTarget> orderedRunTestTargets = ungroupedTestTargets.get(schemeName);

    Optional<String> runnablePath = schemeConfigArg.getExplicitRunnablePath();
    Optional<String> remoteRunnablePath;
    if (schemeConfigArg.getIsRemoteRunnable().orElse(false)) {
      // XXX TODO(beng): Figure out the actual name of the binary to launch
      remoteRunnablePath = Optional.of("/" + workspaceName);
    } else {
      remoteRunnablePath = Optional.empty();
    }

    Path schemeOutputDirectory =
        combinedProject
            ? outputDirectory
            : outputDirectory.resolve(workspaceName + ".xcworkspace");

    Optional<ImmutableMap<SchemeActionType, PBXTarget>> expandVariablesBasedOn = Optional.empty();
    if (schemeConfigArg.getExpandVariablesBasedOn().isPresent()) {
      Map<SchemeActionType, PBXTarget> mapTargets =
        schemeConfigArg.getExpandVariablesBasedOn().get().entrySet()
          .stream().collect(Collectors.toMap(Map.Entry::getKey, e -> buildTargetToPBXTarget.get(e.getValue()) ));
      expandVariablesBasedOn = Optional.of(ImmutableMap.copyOf(mapTargets));
    }

    SchemeGenerator schemeGenerator =
        buildSchemeGenerator(
            targetToProjectPathMap,
            schemeOutputDirectory,
            schemeName,
            schemeConfigArg.getSrcTarget().map(buildTargetToPBXTarget::get),
            Optional.of(schemeConfigArg),
            orderedBuildTargets,
            orderedBuildTestTargets,
            orderedRunTestTargets,
            runnablePath,
            remoteRunnablePath,
            expandVariablesBasedOn);
    schemeGenerator.writeScheme();
    schemeGenerators.put(schemeName, schemeGenerator);
  }
}
 
Example 9
Source File: WorkspaceAndProjectGenerator.java    From buck with Apache License 2.0 4 votes vote down vote up
private void writeWorkspaceSchemes(
    String workspaceName,
    Path outputDirectory,
    ImmutableMap<String, XcodeWorkspaceConfigDescriptionArg> schemeConfigs,
    ImmutableSetMultimap<String, Optional<TargetNode<?>>> schemeNameToSrcTargetNode,
    ImmutableSetMultimap<String, PBXTarget> buildForTestTargets,
    ImmutableSetMultimap<String, PBXTarget> ungroupedTestTargets,
    ImmutableMap<PBXTarget, Path> targetToProjectPathMap,
    ImmutableMap<BuildTarget, PBXTarget> buildTargetToPBXTarget)
    throws IOException {
  for (Map.Entry<String, XcodeWorkspaceConfigDescriptionArg> schemeConfigEntry :
      schemeConfigs.entrySet()) {
    String schemeName = schemeConfigEntry.getKey();
    XcodeWorkspaceConfigDescriptionArg schemeConfigArg = schemeConfigEntry.getValue();
    if (schemeConfigArg.getSrcTarget().isPresent()
        && !focusedTargetMatcher.matches(schemeConfigArg.getSrcTarget().get())) {
      continue;
    }

    ImmutableSet<PBXTarget> orderedBuildTargets =
        schemeNameToSrcTargetNode.get(schemeName).stream()
            .distinct()
            .flatMap(RichStream::from)
            .map(TargetNode::getBuildTarget)
            .map(buildTargetToPBXTarget::get)
            .filter(Objects::nonNull)
            .collect(ImmutableSet.toImmutableSet());
    ImmutableSet<PBXTarget> orderedBuildTestTargets = buildForTestTargets.get(schemeName);
    ImmutableSet<PBXTarget> orderedRunTestTargets = ungroupedTestTargets.get(schemeName);

    Optional<String> runnablePath = schemeConfigArg.getExplicitRunnablePath();
    Optional<String> remoteRunnablePath;
    if (schemeConfigArg.getIsRemoteRunnable().orElse(false)) {
      // XXX TODO(beng): Figure out the actual name of the binary to launch
      remoteRunnablePath = Optional.of("/" + workspaceName);
    } else {
      remoteRunnablePath = Optional.empty();
    }

    Path schemeOutputDirectory = outputDirectory.resolve(workspaceName + ".xcworkspace");

    Optional<ImmutableMap<SchemeActionType, PBXTarget>> expandVariablesBasedOn = Optional.empty();
    if (schemeConfigArg.getExpandVariablesBasedOn().isPresent()) {
      Map<SchemeActionType, PBXTarget> mapTargets =
        schemeConfigArg.getExpandVariablesBasedOn().get().entrySet()
        .stream().collect(Collectors.toMap(Map.Entry::getKey, e -> buildTargetToPBXTarget.get(e.getValue()) ));
      expandVariablesBasedOn = Optional.of(ImmutableMap.copyOf(mapTargets));
    }

    SchemeGenerator schemeGenerator =
        buildSchemeGenerator(
            targetToProjectPathMap,
            schemeOutputDirectory,
            schemeName,
            schemeConfigArg.getSrcTarget().map(buildTargetToPBXTarget::get),
            Optional.of(schemeConfigArg),
            orderedBuildTargets,
            orderedBuildTestTargets,
            orderedRunTestTargets,
            runnablePath,
            remoteRunnablePath,
            expandVariablesBasedOn);
    schemeGenerator.writeScheme();
    schemeGenerators.put(schemeName, schemeGenerator);
  }
}
 
Example 10
Source File: ClassUsageTrackerTest.java    From buck with Apache License 2.0 4 votes vote down vote up
private boolean fileWasRead(Path jarPath, String fileName) {
  ImmutableSetMultimap<Path, Path> classUsageMap = tracker.getClassUsageMap();
  ImmutableSet<Path> paths = classUsageMap.get(jarPath);

  return paths.contains(Paths.get(fileName));
}