com.google.common.collect.ImmutableSetMultimap Java Examples

The following examples show how to use com.google.common.collect.ImmutableSetMultimap. 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: RoleInferenceIT.java    From grakn with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test //missing role is ambiguous without cardinality constraints
public void testRoleInference_RoleHierarchyInvolved() {
    Transaction tx = genericSchemaSession.transaction(Transaction.Type.WRITE);
    ReasonerQueryFactory reasonerQueryFactory = ((TestTransactionProvider.TestTransaction)tx).reasonerQueryFactory();

    String relationString = "{ ($p, subRole2: $gc) isa binary; };";
    String relationString2 = "{ (subRole1: $gp, $p) isa binary; };";
    RelationAtom relation = (RelationAtom) reasonerQueryFactory.atomic(conjunction(relationString)).getAtom();
    RelationAtom relation2 = (RelationAtom) reasonerQueryFactory.atomic(conjunction(relationString2)).getAtom();
    Multimap<Role, Variable> roleMap = roleSetMap(relation.getRoleVarMap());
    Multimap<Role, Variable> roleMap2 = roleSetMap(relation2.getRoleVarMap());

    ImmutableSetMultimap<Role, Variable> correctRoleMap = ImmutableSetMultimap.of(
            tx.getRole("role"), new Variable("p"),
            tx.getRole("subRole2"), new Variable("gc"));
    ImmutableSetMultimap<Role, Variable> correctRoleMap2 = ImmutableSetMultimap.of(
            tx.getRole("role"), new Variable("p"),
            tx.getRole("subRole1"), new Variable("gp"));
    assertEquals(correctRoleMap, roleMap);
    assertEquals(correctRoleMap2, roleMap2);
    tx.close();
}
 
Example #2
Source File: SymbolProblem.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
public static String formatSymbolProblems(
    ImmutableSetMultimap<SymbolProblem, ClassFile> symbolProblems) {
  StringBuilder output = new StringBuilder();

  symbolProblems
      .asMap()
      .forEach(
          (problem, classFiles) -> {
            int referenceCount = classFiles.size();
            output.append(
                String.format(
                    "%s;\n  referenced by %d class file%s\n",
                    problem, referenceCount, referenceCount > 1 ? "s" : ""));
            classFiles.forEach(
                classFile -> {
                  output.append("    " + classFile.getBinaryName());
                  output.append(" (" + classFile.getClassPathEntry() + ")\n");
                });
          });

  return output.toString();
}
 
Example #3
Source File: ZipFilterActionTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test public void testZipEntryFilter_ErrorOnMismatch() throws Exception {
  ZipFilterEntryFilter filter =
      new ZipFilterEntryFilter(
          ".*R.class.*",
          ImmutableSetMultimap.of("foo.class", 1L, "baz.class", 2L),
          ImmutableMap.of("foo.class", 1L, "bar.class", 2L, "baz.class", 3L, "res/R.class", 4L),
          HashMismatchCheckMode.ERROR);
  filter.accept("foo.class", callback);
  callback.assertOp(FilterOperation.SKIP);
  filter.accept("bar.class", callback);
  callback.assertOp(FilterOperation.COPY);
  filter.accept("res/R.class", callback);
  callback.assertOp(FilterOperation.SKIP);
  filter.accept("baz.class", callback);
  assertThat(filter.sawErrors()).isTrue();
}
 
Example #4
Source File: ImmutableContextSetImpl.java    From LuckPerms with MIT License 6 votes vote down vote up
@Override
public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof ContextSet)) return false;
    final ContextSet that = (ContextSet) o;

    // fast(er) path for ImmutableContextSet comparisons
    if (that instanceof ImmutableContextSetImpl) {
        ImmutableContextSetImpl immutableThat = (ImmutableContextSetImpl) that;
        if (this.hashCode != immutableThat.hashCode) return false;
    }

    final Multimap<String, String> thatBacking;
    if (that instanceof AbstractContextSet) {
        thatBacking = ((AbstractContextSet) that).backing();
    } else {
        Map<String, Set<String>> thatMap = that.toMap();
        ImmutableSetMultimap.Builder<String, String> thatBuilder = ImmutableSetMultimap.builder();
        for (Map.Entry<String, Set<String>> e : thatMap.entrySet()) {
            thatBuilder.putAll(e.getKey(), e.getValue());
        }
        thatBacking = thatBuilder.build();
    }

    return backing().equals(thatBacking);
}
 
Example #5
Source File: GerritDestination.java    From copybara with Apache License 2.0 6 votes vote down vote up
@Override
public ImmutableSetMultimap<String, String> describe(@Nullable Glob originFiles) {
  ImmutableSetMultimap.Builder<String, String> builder =
      new ImmutableSetMultimap.Builder<>();
  if (submit) {
    return gitDestination.describe(originFiles);
  }
  for (Entry<String, String> entry : gitDestination.describe(originFiles).entries()) {
    if (entry.getKey().equals("type")) {
      continue;
    }
    builder.put(entry);
  }
  return builder
      .put("type", getType())
      .build();
}
 
Example #6
Source File: LinkageCheckerTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testFindInvalidReferences_constructorInAbstractClass() throws IOException {
  List<ClassPathEntry> paths = ImmutableList.of(guavaJar);
  LinkageChecker linkageChecker = LinkageChecker.create(paths);

  SymbolReferences.Builder builder = new SymbolReferences.Builder();
  builder.addMethodReference(
      new ClassFile(paths.get(0), LinkageCheckerTest.class.getName()),
      new MethodSymbol(
          "com.google.common.collect.LinkedHashMultimapGwtSerializationDependencies",
          "<init>",
          "(Ljava/util/Map;)V",
          false));

  ImmutableSetMultimap<SymbolProblem, ClassFile> symbolProblems =
      linkageChecker.cloneWith(builder.build()).findSymbolProblems();

  Truth.assertThat(symbolProblems).isEmpty();
}
 
Example #7
Source File: MultimapCodec.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Override
public ImmutableMultimap<K, V> deserialize(
    DeserializationContext context, CodedInputStream codedIn)
    throws SerializationException, IOException {
  ImmutableMultimap.Builder<K, V> result;
  if (codedIn.readBool()) {
    result = ImmutableListMultimap.builder();
  } else {
    result = ImmutableSetMultimap.builder();
  }
  int length = codedIn.readInt32();
  for (int i = 0; i < length; i++) {
    K key = context.deserialize(codedIn);
    Collection<V> values = context.deserialize(codedIn);
    result.putAll(key, values);
  }
  return result.build();
}
 
Example #8
Source File: RdeStagingMapperTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void beforeEach() {
  // Two real registrars have been created by AppEngineRule, named "New Registrar" and "The
  // Registrar". Create one included registrar (external_monitoring) and two excluded ones.
  Registrar monitoringRegistrar =
      persistNewRegistrar("monitoring", "monitoring", Registrar.Type.MONITORING, null);
  Registrar testRegistrar = persistNewRegistrar("test", "test", Registrar.Type.TEST, null);
  Registrar externalMonitoringRegistrar =
      persistNewRegistrar(
          "externalmonitor", "external_monitoring", Registrar.Type.EXTERNAL_MONITORING, 9997L);

  // Set Registrar states which are required for reporting.
  tm().transact(
          () ->
              tm().saveNewOrUpdateAll(
                      ImmutableList.of(
                          externalMonitoringRegistrar.asBuilder().setState(State.ACTIVE).build(),
                          testRegistrar.asBuilder().setState(State.ACTIVE).build(),
                          monitoringRegistrar.asBuilder().setState(State.ACTIVE).build())));

  rdeStagingMapper =
      new RdeStagingMapper(ValidationMode.STRICT, ImmutableSetMultimap.of("1", pendingDeposit));
  rdeStagingMapper.setContext(context);
}
 
Example #9
Source File: RoleInferenceIT.java    From grakn with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testRoleInference_TypedTernaryRelationWithMetaRoles_MetaRolesShouldBeOverwritten(){
    Transaction tx = roleInferenceSetSession.transaction(Transaction.Type.WRITE);
    ReasonerQueryFactory reasonerQueryFactory = ((TestTransactionProvider.TestTransaction)tx).reasonerQueryFactory();

    String patternString = "{ (role: $x, role: $y, role: $z); $x isa entity1; $y isa entity2; $z isa entity3; };";
    String patternString2 = "{ (role: $x, role: $y, role: $z) isa ternary; $x isa entity1; $y isa entity2; $z isa entity3; };";

    ImmutableSetMultimap<Role, Variable> correctRoleMap = ImmutableSetMultimap.of(
            tx.getRole("role1"), new Variable("x"),
            tx.getRole("role2"), new Variable("y"),
            tx.getRole("role3"), new Variable("z"));
    roleInference(patternString, correctRoleMap, reasonerQueryFactory);
    roleInference(patternString2, correctRoleMap, reasonerQueryFactory);
    tx.close();
}
 
Example #10
Source File: WorkspaceAndProjectGenerator.java    From buck with Apache License 2.0 5 votes vote down vote up
private void generateProjects(
    Map<Path, ProjectGenerator> projectGenerators,
    ListeningExecutorService listeningExecutorService,
    String workspaceName,
    Path outputDirectory,
    WorkspaceGenerator workspaceGenerator,
    ImmutableSet<BuildTarget> targetsInRequiredProjects,
    ImmutableSetMultimap.Builder<PBXProject, PBXTarget> generatedProjectToPbxTargetsBuilder,
    ImmutableMap.Builder<BuildTarget, PBXTarget> buildTargetToPbxTargetMapBuilder,
    ImmutableMap.Builder<PBXTarget, Path> targetToProjectPathMapBuilder)
    throws IOException, InterruptedException {
  if (combinedProject) {
    generateCombinedProject(
        workspaceName,
        outputDirectory,
        workspaceGenerator,
        targetsInRequiredProjects,
        generatedProjectToPbxTargetsBuilder,
        buildTargetToPbxTargetMapBuilder,
        targetToProjectPathMapBuilder);
  } else {
    generateProject(
        projectGenerators,
        listeningExecutorService,
        workspaceGenerator,
        targetsInRequiredProjects,
        generatedProjectToPbxTargetsBuilder,
        buildTargetToPbxTargetMapBuilder,
        targetToProjectPathMapBuilder);
  }
}
 
Example #11
Source File: ConsoleUiActionTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testUserDoesntHaveAccessToAnyRegistrar_showsWhoAreYouPage() {
  action.registrarAccessor =
      AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of());
  action.run();
  assertThat(response.getPayload()).contains("<h1>You need permission</h1>");
  assertThat(response.getPayload()).contains("not associated with Nomulus.");
  assertThat(response.getPayload()).contains("gtag('config', 'sampleId')");
  assertMetric("<null>", "false", "[]", "FORBIDDEN");
}
 
Example #12
Source File: MultimapGwtTest.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
public void testSerialization() {
    BeanWithMultimapTypes bean = new BeanWithMultimapTypes();

    // insertion order for both keys and values
    bean.immutableMultimap = ImmutableMultimap.of( "foo", 3, "bar", 4, "foo", 2, "foo", 5 );
    bean.immutableListMultimap = ImmutableListMultimap.of( "foo", 3, "bar", 4, "foo", 2, "foo", 5 );
    bean.multimap = LinkedListMultimap.create( bean.immutableListMultimap );
    bean.setMultimap = LinkedHashMultimap.create( bean.immutableListMultimap );
    bean.linkedHashMultimap = LinkedHashMultimap.create( bean.immutableMultimap );
    bean.linkedListMultimap = LinkedListMultimap.create( bean.immutableListMultimap );
    bean.listMultimap = LinkedListMultimap.create( bean.immutableMultimap );

    // no order
    bean.immutableSetMultimap = ImmutableSetMultimap.of( "foo", 3 );
    bean.hashMultimap = HashMultimap.create( bean.immutableSetMultimap );

    // natural ordering on both keys and values
    bean.sortedSetMultimap = TreeMultimap.create( bean.immutableMultimap );
    bean.treeMultimap = TreeMultimap.create( bean.immutableMultimap );

    // insertion order on values but no order on keys
    bean.arrayListMultimap = ArrayListMultimap.create( ImmutableListMultimap.of( "foo", 3, "foo", 2, "foo", 5 ) );

    String expected = "{" +
            "\"multimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"immutableMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"immutableSetMultimap\":{\"foo\":[3]}," +
            "\"immutableListMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"setMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"hashMultimap\":{\"foo\":[3]}," +
            "\"linkedHashMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"sortedSetMultimap\":{\"bar\":[4],\"foo\":[2,3,5]}," +
            "\"treeMultimap\":{\"bar\":[4],\"foo\":[2,3,5]}," +
            "\"listMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"arrayListMultimap\":{\"foo\":[3,2,5]}," +
            "\"linkedListMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}" +
            "}";

    assertEquals( expected, BeanWithMultimapTypesMapper.INSTANCE.write( bean ) );
}
 
Example #13
Source File: CcLinkingOutputs.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Gathers up a map from library identifiers to sets of LibraryToLink which share that library
 * identifier.
 */
public static ImmutableSetMultimap<String, LinkerInputs.LibraryToLink> getLibrariesByIdentifier(
    Iterable<LinkerInputs.LibraryToLink> inputs) {
  ImmutableSetMultimap.Builder<String, LinkerInputs.LibraryToLink> result =
      new ImmutableSetMultimap.Builder<>();
  for (LinkerInputs.LibraryToLink library : inputs) {
    Preconditions.checkNotNull(library.getLibraryIdentifier());
    result.put(library.getLibraryIdentifier(), library);
  }
  return result.build();
}
 
Example #14
Source File: FusingAndroidManifestMergerTest.java    From bundletool with Apache License 2.0 5 votes vote down vote up
@Test
public void merge_noBaseManifest() {
  SetMultimap<BundleModuleName, AndroidManifest> manifests =
      ImmutableSetMultimap.of(
          BundleModuleName.create("feature"),
          AndroidManifest.create(androidManifest("com.testapp")));

  CommandExecutionException exception =
      assertThrows(CommandExecutionException.class, () -> merger.merge(manifests));
  assertThat(exception).hasMessageThat().isEqualTo("Expected to have base module.");
}
 
Example #15
Source File: FileContentProvider.java    From bazel with Apache License 2.0 5 votes vote down vote up
public final ImmutableSetMultimap<Predicate<ClassName>, ClassName> findReferencedTypes(
    ImmutableSet<Predicate<ClassName>> typeFilters) {
  ImmutableSetMultimap.Builder<ClassName, Predicate<ClassName>> collectedTypes =
      ImmutableSetMultimap.builder();
  // Takes an advantage of hit-all-referenced-types ASM Remapper to perform type collection.
  try (S inputStream = get()) {
    ClassReader cr = new ClassReader(inputStream);
    cr.accept(
        new ClassRemapper(
            new ClassWriter(ClassWriter.COMPUTE_FRAMES),
            new Remapper() {
              @Override
              public String map(String internalName) {
                ClassName className = ClassName.create(internalName);
                collectedTypes.putAll(
                    className,
                    typeFilters.stream()
                        .filter(className::acceptTypeFilter)
                        .collect(Collectors.toList()));
                return super.map(internalName);
              }
            }),
        /* parsingOptions= */ 0);
  } catch (IOException e) {
    throw new IOError(e);
  }
  return collectedTypes.build().inverse();
}
 
Example #16
Source File: RegistryLockGetActionTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
  user = userFromRegistrarContact(AppEngineRule.makeRegistrarContact3());
  fakeClock.setTo(DateTime.parse("2000-06-08T22:00:00.0Z"));
  authResult = AuthResult.create(AuthLevel.USER, UserAuthInfo.create(user, false));
  accessor =
      AuthenticatedRegistrarAccessor.createForTesting(
          ImmutableSetMultimap.of(
              "TheRegistrar", OWNER,
              "NewRegistrar", OWNER));
  action =
      new RegistryLockGetAction(
          Method.GET, response, accessor, authResult, Optional.of("TheRegistrar"));
}
 
Example #17
Source File: MultimapGwtTest.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
public void testDeserialization() {
    String input = "{" +
            "\"multimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"immutableMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"immutableSetMultimap\":{\"foo\":[3]}," +
            "\"immutableListMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"setMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"hashMultimap\":{\"foo\":[3]}," +
            "\"linkedHashMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"sortedSetMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"treeMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"listMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"arrayListMultimap\":{\"foo\":[3,2,5]}," +
            "\"linkedListMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}" +
            "}";

    BeanWithMultimapTypes result = BeanWithMultimapTypesMapper.INSTANCE.read( input );
    assertNotNull( result );

    ImmutableListMultimap<String, Integer> expectedOrderedKeysAndValues = ImmutableListMultimap
            .of( "foo", 3, "bar", 4, "foo", 2, "foo", 5 );
    ImmutableSetMultimap<String, Integer> expectedNonOrdered = ImmutableSetMultimap.of( "foo", 3 );

    assertEquals( LinkedHashMultimap.create( expectedOrderedKeysAndValues ), result.multimap );
    assertEquals( ImmutableMultimap.copyOf( expectedOrderedKeysAndValues ), result.immutableMultimap );
    assertEquals( expectedOrderedKeysAndValues, result.immutableListMultimap );
    assertEquals( LinkedHashMultimap.create( expectedOrderedKeysAndValues ), result.setMultimap );
    assertEquals( LinkedHashMultimap.create( expectedOrderedKeysAndValues ), result.linkedHashMultimap );
    assertEquals( LinkedListMultimap.create( expectedOrderedKeysAndValues ), result.listMultimap );
    assertEquals( LinkedListMultimap.create( expectedOrderedKeysAndValues ), result.linkedListMultimap );

    assertEquals( TreeMultimap.create( expectedOrderedKeysAndValues ), result.sortedSetMultimap );
    assertEquals( TreeMultimap.create( expectedOrderedKeysAndValues ), result.treeMultimap );

    assertEquals( expectedNonOrdered, result.immutableSetMultimap );
    assertEquals( HashMultimap.create( expectedNonOrdered ), result.hashMultimap );

    assertEquals( ArrayListMultimap.create( ImmutableListMultimap.of( "foo", 3, "foo", 2, "foo", 5 ) ), result.arrayListMultimap );
}
 
Example #18
Source File: Metadata.java    From copybara with Apache License 2.0 5 votes vote down vote up
/**
 * We never allow deleting hidden labels. Use a different name if you want to rename one.
 */
public final Metadata addHiddenLabels(ImmutableMultimap<String, String> hiddenLabels) {
  checkNotNull(hiddenLabels, "hidden labels cannot be null");
  return new Metadata(message, author,
      ImmutableSetMultimap.<String, String>builder()
          .putAll(this.hiddenLabels)
          .putAll(hiddenLabels).build());
}
 
Example #19
Source File: TopologyAwareNodeSelectorFactory.java    From presto with Apache License 2.0 5 votes vote down vote up
private NodeMap createNodeMap(Optional<CatalogName> catalogName)
{
    Set<InternalNode> nodes = catalogName
            .map(nodeManager::getActiveConnectorNodes)
            .orElseGet(() -> nodeManager.getNodes(ACTIVE));

    Set<String> coordinatorNodeIds = nodeManager.getCoordinators().stream()
            .map(InternalNode::getNodeIdentifier)
            .collect(toImmutableSet());

    ImmutableSetMultimap.Builder<HostAddress, InternalNode> byHostAndPort = ImmutableSetMultimap.builder();
    ImmutableSetMultimap.Builder<InetAddress, InternalNode> byHost = ImmutableSetMultimap.builder();
    ImmutableSetMultimap.Builder<NetworkLocation, InternalNode> workersByNetworkPath = ImmutableSetMultimap.builder();
    for (InternalNode node : nodes) {
        if (includeCoordinator || !coordinatorNodeIds.contains(node.getNodeIdentifier())) {
            NetworkLocation location = networkTopology.locate(node.getHostAndPort());
            for (int i = 0; i <= location.getSegments().size(); i++) {
                workersByNetworkPath.put(location.subLocation(0, i), node);
            }
        }
        try {
            byHostAndPort.put(node.getHostAndPort(), node);

            InetAddress host = InetAddress.getByName(node.getInternalUri().getHost());
            byHost.put(host, node);
        }
        catch (UnknownHostException e) {
            if (inaccessibleNodeLogCache.getIfPresent(node) == null) {
                inaccessibleNodeLogCache.put(node, true);
                LOG.warn(e, "Unable to resolve host name for node: %s", node);
            }
        }
    }

    return new NodeMap(byHostAndPort.build(), byHost.build(), workersByNetworkPath.build(), coordinatorNodeIds);
}
 
Example #20
Source File: MutableContextSetImpl.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public @NonNull ImmutableContextSet immutableCopy() {
    // if the map is empty, don't create a new instance
    if (this.map.isEmpty()) {
        return ImmutableContextSetImpl.EMPTY;
    }
    synchronized (this.map) {
        return new ImmutableContextSetImpl(ImmutableSetMultimap.copyOf(this.map));
    }
}
 
Example #21
Source File: ServiceManager.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
ImmutableMultimap<State, Service> servicesByState() {
  ImmutableSetMultimap.Builder<State, Service> builder = ImmutableSetMultimap.builder();
  monitor.enter();
  try {
    for (Entry<State, Service> entry : servicesByState.entries()) {
      if (!(entry.getValue() instanceof NoOpService)) {
        builder.put(entry);
      }
    }
  } finally {
    monitor.leave();
  }
  return builder.build();
}
 
Example #22
Source File: ChunkLoaderManager.java    From ChickenChunks with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static void cleanChunks(WorldServer world) {
    int dim = CommonUtils.getDimension(world);
    int viewdist = ServerUtils.mc().getConfigurationManager().getViewDistance();

    HashSet<ChunkCoordIntPair> loadedChunks = new HashSet<ChunkCoordIntPair>();
    for (EntityPlayer player : ServerUtils.getPlayersInDimension(dim)) {
        int playerChunkX = (int) player.posX >> 4;
        int playerChunkZ = (int) player.posZ >> 4;

        for (int cx = playerChunkX - viewdist; cx <= playerChunkX + viewdist; cx++)
            for (int cz = playerChunkZ - viewdist; cz <= playerChunkZ + viewdist; cz++)
                loadedChunks.add(new ChunkCoordIntPair(cx, cz));
    }

    ImmutableSetMultimap<ChunkCoordIntPair, Ticket> persistantChunks = world.getPersistentChunks();
    PlayerManager manager = world.getPlayerManager();

    for (Chunk chunk : (List<Chunk>) world.theChunkProviderServer.loadedChunks) {
        ChunkCoordIntPair coord = chunk.getChunkCoordIntPair();
        if (!loadedChunks.contains(coord) && !persistantChunks.containsKey(coord) && world.theChunkProviderServer.chunkExists(coord.chunkXPos, coord.chunkZPos)) {
            PlayerInstance instance = manager.getOrCreateChunkWatcher(coord.chunkXPos, coord.chunkZPos, false);
            if (instance == null) {
                world.theChunkProviderServer.unloadChunksIfNotNearSpawn(coord.chunkXPos, coord.chunkZPos);
            } else {
                while (instance.playersWatchingChunk.size() > 0)
                    instance.removePlayer((EntityPlayerMP) instance.playersWatchingChunk.get(0));
            }
        }
    }

    if (ServerUtils.getPlayersInDimension(dim).isEmpty() && world.getPersistentChunks().isEmpty() && !DimensionManager.shouldLoadSpawn(dim)) {
        DimensionManager.unloadWorld(dim);
    }
}
 
Example #23
Source File: SourceFiles.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
/**
 * This method generates names and keys for the framework classes necessary for all of the
 * bindings. It is responsible for the following:
 * <ul>
 * <li>Choosing a name that associates the binding with all of the dependency requests for this
 * type.
 * <li>Choosing a name that is <i>probably</i> associated with the type being bound.
 * <li>Ensuring that no two bindings end up with the same name.
 * </ul>
 *
 * @return Returns the mapping from {@link BindingKey} to field, sorted by the name of the field.
 */
static ImmutableMap<BindingKey, FrameworkField> generateBindingFieldsForDependencies(
    DependencyRequestMapper dependencyRequestMapper,
    Iterable<? extends DependencyRequest> dependencies) {
  ImmutableSetMultimap<BindingKey, DependencyRequest> dependenciesByKey =
      indexDependenciesByKey(dependencies);
  Map<BindingKey, Collection<DependencyRequest>> dependenciesByKeyMap =
      dependenciesByKey.asMap();
  ImmutableMap.Builder<BindingKey, FrameworkField> bindingFields = ImmutableMap.builder();
  for (Entry<BindingKey, Collection<DependencyRequest>> entry
      : dependenciesByKeyMap.entrySet()) {
    BindingKey bindingKey = entry.getKey();
    Collection<DependencyRequest> requests = entry.getValue();
    Class<?> frameworkClass =
        dependencyRequestMapper.getFrameworkClass(requests.iterator().next());
    // collect together all of the names that we would want to call the provider
    ImmutableSet<String> dependencyNames =
        FluentIterable.from(requests).transform(new DependencyVariableNamer()).toSet();

    if (dependencyNames.size() == 1) {
      // if there's only one name, great! use it!
      String name = Iterables.getOnlyElement(dependencyNames);
      bindingFields.put(bindingKey,
          FrameworkField.createWithTypeFromKey(frameworkClass, bindingKey, name));
    } else {
      // in the event that a field is being used for a bunch of deps with different names,
      // add all the names together with "And"s in the middle. E.g.: stringAndS
      Iterator<String> namesIterator = dependencyNames.iterator();
      String first = namesIterator.next();
      StringBuilder compositeNameBuilder = new StringBuilder(first);
      while (namesIterator.hasNext()) {
        compositeNameBuilder.append("And").append(
            CaseFormat.LOWER_CAMEL.to(UPPER_CAMEL, namesIterator.next()));
      }
      bindingFields.put(bindingKey, FrameworkField.createWithTypeFromKey(
          frameworkClass, bindingKey, compositeNameBuilder.toString()));
    }
  }
  return bindingFields.build();
}
 
Example #24
Source File: UpdateRegistrarRdapBaseUrlsAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private ImmutableSetMultimap<String, String> getRdapBaseUrlsPerIanaId() {
  // All TLDs have the same data, so just keep trying until one works
  // (the expectation is that all / any should work)
  ImmutableList<String> tlds = ImmutableList.sortedCopyOf(Registries.getTldsOfType(TldType.REAL));
  checkArgument(!tlds.isEmpty(), "There must exist at least one REAL TLD.");
  Throwable finalThrowable = null;
  for (String tld : tlds) {
    HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
    String id;
    try {
      id = loginAndGetId(requestFactory, tld);
    } catch (Throwable e) {
      // Login failures are bad but not unexpected for certain TLDs. We shouldn't store those
      // but rather should only store useful Throwables.
      logger.atWarning().log("Error logging in to MoSAPI server: " + e.getMessage());
      continue;
    }
    try {
      return getRdapBaseUrlsPerIanaIdWithTld(tld, id, requestFactory);
    } catch (Throwable throwable) {
      logger.atWarning().log(
          String.format(
              "Error retrieving RDAP urls with TLD %s: %s", tld, throwable.getMessage()));
      finalThrowable = throwable;
    }
  }
  throw new RuntimeException(
      String.format("Error contacting MosAPI server. Tried TLDs %s", tlds), finalThrowable);
}
 
Example #25
Source File: WorkspaceAndProjectGenerator.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Add a workspace scheme for each extension bundled with the source target of the workspace.
 *
 * @param projectGraph
 * @param schemeName
 * @param schemeArguments
 * @param schemeConfigsBuilder
 * @param schemeNameToSrcTargetNodeBuilder
 */
private static void addWorkspaceExtensionSchemes(
    TargetGraph projectGraph,
    String schemeName,
    XcodeWorkspaceConfigDescriptionArg schemeArguments,
    ImmutableMap.Builder<String, XcodeWorkspaceConfigDescriptionArg> schemeConfigsBuilder,
    ImmutableSetMultimap.Builder<String, Optional<TargetNode<?>>>
        schemeNameToSrcTargetNodeBuilder) {
  if (!schemeArguments.getSrcTarget().isPresent()) {
    return;
  }

  LOG.debug("Potentially adding extension schemes for %s", schemeName);

  BuildTarget sourceBuildTarget = schemeArguments.getSrcTarget().get();
  TargetNode<?> sourceTargetNode = projectGraph.get(sourceBuildTarget);
  Set<BuildTarget> sourceTargetBuildDeps = sourceTargetNode.getBuildDeps();

  // Filter all of the source target's deps to find the bundled extensions that get an implicit
  // scheme.
  ImmutableSet<BuildTarget> implicitSchemeBuildTargets =
      sourceTargetBuildDeps.stream()
          .filter(t -> shouldIncludeImplicitExtensionSchemeForTargetNode(projectGraph.get(t)))
          .collect(ImmutableSet.toImmutableSet());

  // Create scheme for each bundled extension to allow Xcode to automatically begin debugging them
  // when this scheme it selected.
  implicitSchemeBuildTargets.forEach(
      (buildTarget -> {
        String extensionSchemeName = schemeName + "+" + buildTarget.getShortName();
        TargetNode<?> targetNode = projectGraph.get(buildTarget);

        schemeConfigsBuilder.put(
            extensionSchemeName, createImplicitExtensionWorkspaceArgs(sourceBuildTarget));

        schemeNameToSrcTargetNodeBuilder.put(extensionSchemeName, Optional.of(sourceTargetNode));
        schemeNameToSrcTargetNodeBuilder.put(extensionSchemeName, Optional.of(targetNode));
      }));
}
 
Example #26
Source File: TurbineRoundEnvironment.java    From turbine with Apache License 2.0 5 votes vote down vote up
public TurbineRoundEnvironment(
    ModelFactory factory,
    ImmutableSet<ClassSymbol> syms,
    boolean processingOver,
    boolean errorRaised,
    ImmutableSetMultimap<ClassSymbol, Symbol> allAnnotations) {
  this.factory = factory;
  this.syms = syms;
  this.processingOver = processingOver;
  this.errorRaised = errorRaised;
  this.allAnnotations = allAnnotations;
}
 
Example #27
Source File: LinkageCheckerTest.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testFindSymbolProblems_catchesNoClassDefFoundError() throws IOException {
  // SLF4J classes catch NoClassDefFoundError to detect the availability of logger backends
  // the tool should not show errors for such classes.
  List<ClassPathEntry> paths = resolvePaths("org.slf4j:slf4j-api:jar:1.7.21");

  LinkageChecker linkageChecker = LinkageChecker.create(paths);

  ImmutableSetMultimap<SymbolProblem, ClassFile> symbolProblems =
      linkageChecker.findSymbolProblems();

  Truth.assertThat(symbolProblems).isEmpty();
}
 
Example #28
Source File: SetMultimapPropertiesTest.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
@Test
public void testMutate() {
  SetMultimapPropertyType value = new SetMultimapPropertyType.Builder()
      .putNumbers(1, "one")
      .putNumbers(1, "uno")
      .putNumbers(2, "two")
      .putNumbers(2, "dos")
      .mutateNumbers(numbers -> numbers.removeAll(2))
      .build();
  assertEquals(ImmutableSetMultimap.of(1, "one", 1, "uno"), value.getNumbers());
}
 
Example #29
Source File: RuleApplicabilityIT.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test //should assign (role : $x, role1: $y, role: $z) which is compatible with 3 ternary rules
public void relationWithUnspecifiedRoles_someRoleplayersTyped(){
    try(Transaction tx = ruleApplicabilitySession.transaction(Transaction.Type.WRITE)) {
        ReasonerQueryFactory reasonerQueryFactory = ((TestTransactionProvider.TestTransaction)tx).reasonerQueryFactory();

        String relationString = "{ ($x, $y, $z);$y isa singleRoleEntity; $z isa twoRoleEntity; };";
        RelationAtom relation = (RelationAtom) reasonerQueryFactory.atomic(conjunction(relationString)).getAtom();
        ImmutableSetMultimap<Role, Variable> roleMap = ImmutableSetMultimap.of(
                tx.getRole("role"), new Variable("x"),
                tx.getRole("someRole"), new Variable("y"),
                tx.getRole("role"), new Variable("z"));
        assertEquals(roleMap, roleSetMap(relation.getRoleVarMap()));
        assertEquals(5, relation.getApplicableRules().count());
    }
}
 
Example #30
Source File: ConsoleUiActionTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  action.enabled = true;
  action.logoFilename = "logo.png";
  action.productName = "Nomulus";
  action.integrationEmail = "[email protected]";
  action.supportEmail = "[email protected]";
  action.announcementsEmail = "[email protected]";
  action.supportPhoneNumber = "1 (888) 555 0123";
  action.technicalDocsUrl = "http://example.com/technical-docs";
  action.req = request;
  action.response = response;
  action.registrarConsoleMetrics = new RegistrarConsoleMetrics();
  action.userService = UserServiceFactory.getUserService();
  action.xsrfTokenManager = new XsrfTokenManager(new FakeClock(), action.userService);
  action.method = Method.GET;
  action.paramClientId = Optional.empty();
  action.authResult = AuthResult.create(AuthLevel.USER, UserAuthInfo.create(user, false));
  action.analyticsConfig = ImmutableMap.of("googleAnalyticsId", "sampleId");

  action.registrarAccessor =
      AuthenticatedRegistrarAccessor.createForTesting(
          ImmutableSetMultimap.of(
              "TheRegistrar", OWNER,
              "NewRegistrar", OWNER,
              "NewRegistrar", ADMIN,
              "AdminRegistrar", ADMIN));
  RegistrarConsoleMetrics.consoleRequestMetric.reset();
}