com.google.common.collect.ImmutableMap Java Examples

The following examples show how to use com.google.common.collect.ImmutableMap. 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: AndroidBuckConfigTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testNdkAppPlatformPriority() {
  ImmutableMap<String, String> ndkSection =
      new ImmutableMap.Builder<String, String>()
          .put("app_platform", "fallback")
          .put("app_platform_per_cpu_abi", "arm64 => specific")
          .build();
  AndroidBuckConfig androidBuckConfig = makeAndroidBuckConfig(ndkSection);

  // Make sure we have an fallback value.
  assertEquals(androidBuckConfig.getNdkCpuAbiFallbackAppPlatform(), Optional.of("fallback"));

  // Make sure ABI-specific values override the fallback one.
  assertEquals(androidBuckConfig.getNdkAppPlatformForCpuAbi("arm64"), Optional.of("specific"));

  // Make sure we default to fallback.
  assertEquals(androidBuckConfig.getNdkAppPlatformForCpuAbi("fake"), Optional.of("fallback"));
}
 
Example #2
Source File: Handler.java    From greenbeans with Apache License 2.0 6 votes vote down vote up
private void compileParameters(AnnotatedType[] annotatedParameterTypes, Annotation[][] annotations) {
	ImmutableList.Builder<String> parameterOrderBuilder = ImmutableList.builder();
	ImmutableMap.Builder<String, Type> nameToTypeBuilder = ImmutableMap.builder();

	for (int x = 0; x < annotatedParameterTypes.length; ++x) {
		AnnotatedType annotatedType = annotatedParameterTypes[x];
		PathParam pathParam = getPathParam(annotations[x]);
		String name;
		Type type;
		if (pathParam != null) {
			name = pathParam.value();
			type = annotatedType.getType();
		} else {
			name = NAME_ENTITY;
			type = annotatedType.getType();
		}
		parameterOrderBuilder.add(name);
		nameToTypeBuilder.put(name, type);
	}
	parameterOrder = parameterOrderBuilder.build();
	parameterNameToType = nameToTypeBuilder.build();
}
 
Example #3
Source File: CatalogThriftHiveMetastore.java    From metacat with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public PrincipalPrivilegeSet get_privilege_set(final HiveObjectRef hiveObject, final String userName,
                                               final List<String> groupNames)
    throws TException {
    MetacatContextManager.getContext().setUserName(userName);
    return requestWrapper("get_privilege_set", new Object[]{hiveObject, userName, groupNames},
        () -> {
            Map<String, List<PrivilegeGrantInfo>> groupPrivilegeSet = null;
            Map<String, List<PrivilegeGrantInfo>> userPrivilegeSet = null;

            if (groupNames != null) {
                groupPrivilegeSet = groupNames.stream()
                    .collect(Collectors.toMap(p -> p, p -> Lists.newArrayList()));
            }
            if (userName != null) {
                userPrivilegeSet = ImmutableMap.of(userName, Lists.newArrayList());
            }
            return new PrincipalPrivilegeSet(userPrivilegeSet,
                groupPrivilegeSet,
                defaultRolesPrivilegeSet);
        });
}
 
Example #4
Source File: KcOidcBrokerTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected Iterable<IdentityProviderMapperRepresentation> createIdentityProviderMappers(IdentityProviderMapperSyncMode syncMode) {
    IdentityProviderMapperRepresentation attrMapper1 = new IdentityProviderMapperRepresentation();
    attrMapper1.setName("manager-role-mapper");
    attrMapper1.setIdentityProviderMapper(ExternalKeycloakRoleToRoleMapper.PROVIDER_ID);
    attrMapper1.setConfig(ImmutableMap.<String,String>builder()
            .put(IdentityProviderMapperModel.SYNC_MODE, syncMode.toString())
            .put("external.role", ROLE_MANAGER)
            .put("role", ROLE_MANAGER)
            .build());

    IdentityProviderMapperRepresentation attrMapper2 = new IdentityProviderMapperRepresentation();
    attrMapper2.setName("user-role-mapper");
    attrMapper2.setIdentityProviderMapper(ExternalKeycloakRoleToRoleMapper.PROVIDER_ID);
    attrMapper2.setConfig(ImmutableMap.<String,String>builder()
            .put(IdentityProviderMapperModel.SYNC_MODE, syncMode.toString())
            .put("external.role", ROLE_USER)
            .put("role", ROLE_USER)
            .build());

    return Lists.newArrayList(attrMapper1, attrMapper2);
}
 
Example #5
Source File: SimpleValueTypeTest.java    From auto with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleValueType() {
  final String happy = "happy";
  final int testInt = 23;
  final Map<String, Long> testMap = ImmutableMap.of("happy", 23L);
  SimpleValueType simple = SimpleValueType.create(happy, testInt, testMap);
  assertSame(happy, simple.string());
  assertEquals(testInt, simple.integer());
  assertSame(testMap, simple.map());
  assertEquals("SimpleValueType{string=happy, integer=23, map={happy=23}}", simple.toString());
  int expectedHashCode = 1;
  expectedHashCode = (expectedHashCode * 1000003) ^ happy.hashCode();
  expectedHashCode = (expectedHashCode * 1000003) ^ ((Object) testInt).hashCode();
  expectedHashCode = (expectedHashCode * 1000003) ^ testMap.hashCode();
  assertEquals(expectedHashCode, simple.hashCode());
}
 
Example #6
Source File: ConfigDifferenceTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void compareEqualConfigs() {
  RawConfig rawConfig1 =
      RawConfig.builder()
          .putAll(ImmutableMap.of("section", ImmutableMap.of("field", "value1")))
          .putAll(ImmutableMap.of("section", ImmutableMap.of("field", "value2")))
          .build();

  RawConfig rawConfig2 =
      RawConfig.builder()
          .putAll(ImmutableMap.of("section", ImmutableMap.of("field", "value1")))
          .putAll(ImmutableMap.of("section", ImmutableMap.of("field", "value2")))
          .build();

  assertTrue(ConfigDifference.compare(rawConfig1.getValues(), rawConfig2.getValues()).isEmpty());
}
 
Example #7
Source File: GoogleCloudStorageTest.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetadataIsWrittenWhenCreatingEmptyObjects() throws IOException {
  String bucketName = getSharedBucketName();

  Map<String, byte[]> metadata =
      ImmutableMap.of(
          "key1", "value1".getBytes(StandardCharsets.UTF_8),
          "key2", "value2".getBytes(StandardCharsets.UTF_8));

  // Verify the bucket exist by creating an object
  StorageResourceId objectToCreate =
      new StorageResourceId(bucketName, "testMetadataIsWrittenWhenCreatingEmptyObjects_Object");
  rawStorage.createEmptyObject(objectToCreate, new CreateObjectOptions(false, metadata));

  // Verify we get metadata from getItemInfo
  GoogleCloudStorageItemInfo itemInfo = rawStorage.getItemInfo(objectToCreate);
  assertMapsEqual(metadata, itemInfo.getMetadata(), BYTE_ARRAY_EQUIVALENCE);
}
 
Example #8
Source File: WorkerMacroArg.java    From buck with Apache License 2.0 6 votes vote down vote up
private WorkerMacroArg(
    Arg arg,
    BuildTarget workerTarget,
    ProjectFilesystem projectFilesystem,
    WorkerTool workerTool,
    ImmutableList<String> startupCommand,
    ImmutableMap<String, String> startupEnvironment) {
  super(arg);

  Preconditions.checkArgument(
      workerTarget.getCell().equals(projectFilesystem.getBuckPaths().getCellName()),
      "filesystem cell '%s' must match target cell: %s",
      projectFilesystem.getBuckPaths().getCellName(),
      workerTarget);

  this.workerTarget = workerTarget;
  this.projectFilesystem = projectFilesystem;
  this.workerTool = workerTool;
  this.startupCommand = startupCommand;
  this.startupEnvironment = startupEnvironment;
}
 
Example #9
Source File: RefreshingAddressResolverTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void returnDnsQuestionsWhenAllQueryTimeout() throws Exception {
    try (TestDnsServer server1 = new TestDnsServer(ImmutableMap.of(), new AlwaysTimeoutHandler());
         TestDnsServer server2 = new TestDnsServer(ImmutableMap.of(), new AlwaysTimeoutHandler())) {
        final EventLoop eventLoop = eventLoopExtension.get();
        final DnsResolverGroupBuilder builder = builder(server1, server2)
                .queryTimeoutMillis(1000)
                .resolvedAddressTypes(ResolvedAddressTypes.IPV4_PREFERRED);
        try (RefreshingAddressResolverGroup group = builder.build(eventLoop)) {
            final AddressResolver<InetSocketAddress> resolver = group.getResolver(eventLoop);
            final Future<InetSocketAddress> future = resolver.resolve(
                    InetSocketAddress.createUnresolved("foo.com", 36462));
            await().until(future::isDone);
            assertThat(future.cause()).isInstanceOf(DnsTimeoutException.class);
        }
    }
}
 
Example #10
Source File: DartClientOptionsProvider.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> createOptions() {
    ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>();
    return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE)
            .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE)
            .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE)
            .put(DartClientCodegen.BROWSER_CLIENT, BROWSER_CLIENT_VALUE)
            .put(DartClientCodegen.PUB_NAME, PUB_NAME_VALUE)
            .put(DartClientCodegen.PUB_VERSION, PUB_VERSION_VALUE)
            .put(DartClientCodegen.PUB_DESCRIPTION, PUB_DESCRIPTION_VALUE)
            .put(DartClientCodegen.PUB_AUTHOR, PUB_AUTHOR_VALUE)
            .put(DartClientCodegen.PUB_AUTHOR_EMAIL, PUB_AUTHOR_EMAIL_VALUE)
            .put(DartClientCodegen.PUB_HOMEPAGE, PUB_HOMEPAGE_VALUE)
            .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE)
            .put(DartClientCodegen.USE_ENUM_EXTENSION, USE_ENUM_EXTENSION)
            .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE)
            .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)
            .put(DartClientCodegen.SUPPORT_DART2, "false")
            .put(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "true")
            .put(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, "true")
            .build();
}
 
Example #11
Source File: CxxPlatformXcodeConfigGeneratorTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testResultHasCxxLibraryValueTakenFromPlatformCxxflags() {
  CxxPlatform platform =
      CxxPlatform.builder()
          .from(DEFAULT_PLATFORM)
          .setCxxflags(StringArg.from(ImmutableList.of("-stdlib=somevalue")))
          .build();
  ImmutableMap<String, ImmutableMap<String, String>> buildConfigs =
      CxxPlatformXcodeConfigGenerator.getDefaultXcodeBuildConfigurationsFromCxxPlatform(
          platform, new LinkedHashMap<>(), DEFAULT_PATH_RESOLVER);
  ImmutableMap<String, String> config =
      buildConfigs.get(CxxPlatformXcodeConfigGenerator.DEBUG_BUILD_CONFIGURATION_NAME);
  assertThat(
      config.get(CxxPlatformXcodeConfigGenerator.CLANG_CXX_LIBRARY),
      Matchers.equalTo("somevalue"));
}
 
Example #12
Source File: RedisSinkTaskReconnectIT.java    From kafka-connect-redis with Apache License 2.0 6 votes vote down vote up
@Test
public void initialConnectionIssues(
    @DockerContainer(container = "redis") Container container,
    @Port(container = "redis", internalPort = 6379) InetSocketAddress address) throws ExecutionException, InterruptedException, IOException {
  log.info("address = {}", address);
  final String topic = "putWrite";
  SinkTaskContext context = mock(SinkTaskContext.class);
  when(context.assignment()).thenReturn(ImmutableSet.of());
  this.task.initialize(context);
  container.stop();

  ExecutorService service = Executors.newSingleThreadExecutor();
  Future<?> future = service.submit(() -> task.start(
        ImmutableMap.of(RedisSinkConnectorConfig.HOSTS_CONFIG, String.format("%s:%s", address.getHostString(), address.getPort())
      )
  ));
  container.start();
  Time.SYSTEM.sleep(2000);
  future.get();
}
 
Example #13
Source File: QuboleDB.java    From quark with Apache License 2.0 6 votes vote down vote up
@Override
public ImmutableMap<String, Schema> getSchemas() throws QuarkException {
  Map<String, List<SchemaOrdinal>> schemas;
  try {
    schemas = getSchemaListDescribed();
  } catch (ExecutionException | InterruptedException e) {
    LOG.error("Getting Schema metadata for " + this.endpoint
        + " failed. Error: " + e.getMessage(), e);
    throw new QuarkException(e);
  }
  ImmutableMap.Builder<String, Schema> schemaBuilder = new ImmutableMap.Builder<>();

  for (String schemaName: schemas.keySet()) {
    String schemaKey = schemaName;
    if (!this.isCaseSensitive()) {
      schemaKey = schemaName.toUpperCase();
    }
    schemaBuilder.put(schemaKey, new QuboleSchema(schemaKey,
        schemas.get(schemaName), this.isCaseSensitive(), this.getDataTypes()));
  }
  return schemaBuilder.build();
}
 
Example #14
Source File: FileWriteActionTestCase.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Before
public final void createExecutorAndContext() throws Exception {
  BinTools binTools = BinTools.forUnitTesting(directories, analysisMock.getEmbeddedTools());
  executor = new TestExecutorBuilder(fileSystem, directories, binTools).build();
  context =
      new ActionExecutionContext(
          executor,
          /*actionInputFileCache=*/ null,
          ActionInputPrefetcher.NONE,
          actionKeyContext,
          /*metadataHandler=*/ null,
          /*rewindingEnabled=*/ false,
          LostInputsCheck.NONE,
          new FileOutErr(),
          new StoredEventHandler(),
          /*clientEnv=*/ ImmutableMap.of(),
          /*topLevelFilesets=*/ ImmutableMap.of(),
          /*artifactExpander=*/ null,
          /*actionFileSystem=*/ null,
          /*skyframeDepsResult=*/ null,
          NestedSetExpander.DEFAULT);
}
 
Example #15
Source File: AbstractProgrammingSubmissionServiceImpl.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Page<ProgrammingSubmission> getPageOfProgrammingSubmissions(long pageIndex, long pageSize, String orderBy, String orderDir, String authorJid, String problemJid, String containerJid) {
    ImmutableMap.Builder<SingularAttribute<? super SM, ? extends Object>, String> filterColumnsBuilder = ImmutableMap.builder();
    if (authorJid != null) {
        filterColumnsBuilder.put(AbstractProgrammingSubmissionModel_.createdBy, authorJid);
    }
    if (problemJid != null) {
        filterColumnsBuilder.put(AbstractProgrammingSubmissionModel_.problemJid, problemJid);
    }
    if (containerJid != null) {
        filterColumnsBuilder.put(AbstractProgrammingSubmissionModel_.containerJid, containerJid);
    }

    Map<SingularAttribute<? super SM, ? extends Object>, String> filterColumns = filterColumnsBuilder.build();

    long totalRowsCount = programmingSubmissionDao.countByFiltersEq("", filterColumns);
    List<SM> submissionModels = programmingSubmissionDao.findSortedByFiltersEq(orderBy, orderDir, "", filterColumns, pageIndex * pageSize, pageSize);
    Map<String, List<GM>> gradingModelsMap = programmingGradingDao.getBySubmissionJids(Lists.transform(submissionModels, m -> m.jid));

    List<ProgrammingSubmission> submissions = Lists.transform(submissionModels, m -> ProgrammingSubmissionServiceUtils.createSubmissionFromModels(m, gradingModelsMap.get(m.jid)));

    return new Page<>(submissions, totalRowsCount, pageIndex, pageSize);
}
 
Example #16
Source File: TestLogicalPlanner.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test
public void testDistributedSort()
{
    ImmutableList<PlanMatchPattern.Ordering> orderBy = ImmutableList.of(sort("ORDERKEY", DESCENDING, LAST));
    assertDistributedPlan(
            "SELECT orderkey FROM orders ORDER BY orderkey DESC",
            output(
                    exchange(REMOTE, GATHER, orderBy,
                            exchange(LOCAL, GATHER, orderBy,
                                    sort(orderBy,
                                            exchange(REMOTE, REPARTITION,
                                                    tableScan("orders", ImmutableMap.of(
                                                            "ORDERKEY", "orderkey"))))))));

    assertDistributedPlan(
            "SELECT orderkey FROM orders ORDER BY orderkey DESC",
            Session.builder(this.getQueryRunner().getDefaultSession())
                    .setSystemProperty(DISTRIBUTED_SORT, Boolean.toString(false))
                    .build(),
            output(
                    sort(orderBy,
                            exchange(LOCAL, GATHER,
                                    exchange(REMOTE, GATHER,
                                            tableScan("orders", ImmutableMap.of(
                                                    "ORDERKEY", "orderkey")))))));
}
 
Example #17
Source File: SqlStageExecution.java    From presto with Apache License 2.0 6 votes vote down vote up
private SqlStageExecution(StageStateMachine stateMachine, RemoteTaskFactory remoteTaskFactory, NodeTaskMap nodeTaskMap, boolean summarizeTaskInfo, Executor executor, FailureDetector failureDetector)
{
    this.stateMachine = stateMachine;
    this.remoteTaskFactory = requireNonNull(remoteTaskFactory, "remoteTaskFactory is null");
    this.nodeTaskMap = requireNonNull(nodeTaskMap, "nodeTaskMap is null");
    this.summarizeTaskInfo = summarizeTaskInfo;
    this.executor = requireNonNull(executor, "executor is null");
    this.failureDetector = requireNonNull(failureDetector, "failureDetector is null");

    ImmutableMap.Builder<PlanFragmentId, RemoteSourceNode> fragmentToExchangeSource = ImmutableMap.builder();
    for (RemoteSourceNode remoteSourceNode : stateMachine.getFragment().getRemoteSourceNodes()) {
        for (PlanFragmentId planFragmentId : remoteSourceNode.getSourceFragmentIds()) {
            fragmentToExchangeSource.put(planFragmentId, remoteSourceNode);
        }
    }
    this.exchangeSources = fragmentToExchangeSource.build();
}
 
Example #18
Source File: JvmAuthTokenProviderTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTokenNoRefresh() throws IOException, InterruptedException {
  MockGoogleCredentials credentials = new MockGoogleCredentials("mock-token");
  TokenRefreshDetector refreshDetector = new TokenRefreshDetector();
  credentials.addChangeListener(refreshDetector);
  credentials.refresh();
  assertEquals(1, refreshDetector.count);

  FirebaseOptions options = new FirebaseOptions.Builder()
      .setCredentials(credentials)
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);

  JvmAuthTokenProvider provider = new JvmAuthTokenProvider(app, DIRECT_EXECUTOR);
  TestGetTokenListener listener = new TestGetTokenListener();
  provider.getToken(false, listener);
  assertToken(listener.get(), "mock-token", ImmutableMap.<String, Object>of());
  assertEquals(1, refreshDetector.count);
}
 
Example #19
Source File: SenderExample.java    From Intake with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws AuthorizationException, InvocationCommandException, CommandException {
    Map<String, User> users = new ImmutableMap.Builder<String, User>()
            .put("aaron", new User("Aaron"))
            .put("michelle", new User("Michelle"))
            .build();

    Namespace namespace = new Namespace();
    namespace.put("sender", users.get("aaron")); // Our sender

    Injector injector = Intake.createInjector();
    injector.install(new SenderModule(users));

    ParametricBuilder builder = new ParametricBuilder(injector);

    Dispatcher dispatcher = new SimpleDispatcher();
    builder.registerMethodsAsCommands(dispatcher, new SenderExample());

    dispatcher.call("greet", namespace, ImmutableList.<String>of());
    dispatcher.call("privmsg aaron", namespace, ImmutableList.<String>of());
    dispatcher.call("privmsg michelle", namespace, ImmutableList.<String>of());
    dispatcher.call("poke aaron", namespace, ImmutableList.<String>of());
    dispatcher.call("poke michelle", namespace, ImmutableList.<String>of());
}
 
Example #20
Source File: TestDereferencePushDown.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test
public void testDereferencePushdownUnnest()
{
    assertPlan("WITH t(msg, array) AS (VALUES ROW(CAST(ROW(1, 2.0) AS ROW(x BIGINT, y DOUBLE)), ARRAY[1, 2, 3])) " +
                    "SELECT a.msg.x " +
                    "FROM t a JOIN t b ON a.msg.y = b.msg.y " +
                    "CROSS JOIN UNNEST (a.array) " +
                    "WHERE a.msg.x + b.msg.x < BIGINT '10'",
            output(ImmutableList.of("expr"),
                    strictProject(ImmutableMap.of("expr", expression("a_x")),
                            unnest(
                                    join(INNER, ImmutableList.of(equiJoinClause("a_y", "b_y")),
                                            Optional.of("a_x + b_x < BIGINT '10'"),
                                            anyTree(
                                                    strictProject(ImmutableMap.of("a_y", expression("msg.y"), "a_x", expression("msg.x"), "a_z", expression("array")),
                                                            values("msg", "array"))),
                                            anyTree(
                                                    strictProject(ImmutableMap.of("b_y", expression("msg.y"), "b_x", expression("msg.x")),
                                                            values("msg"))))))));
}
 
Example #21
Source File: TestThriftEnumMetadata.java    From drift with Apache License 2.0 6 votes vote down vote up
@Test
public void testValid()
{
    ThriftEnumMetadata<Letter> metadata = thriftEnumMetadata(Letter.class);
    assertEquals(metadata.getEnumClass(), Letter.class);
    assertEquals(metadata.getEnumName(), "Letter");
    assertEquals(metadata.getByEnumConstant(), ImmutableMap.<Letter, Integer>builder()
            .put(Letter.A, 65)
            .put(Letter.B, 66)
            .put(Letter.C, 67)
            .put(Letter.D, 68)
            .put(Letter.UNKNOWN, -1)
            .build());
    assertEquals(metadata.getByEnumValue(), ImmutableMap.<Integer, Letter>builder()
            .put(65, Letter.A)
            .put(66, Letter.B)
            .put(67, Letter.C)
            .put(68, Letter.D)
            .put(-1, Letter.UNKNOWN)
            .build());
    assertEquals(metadata.getUnknownEnumConstant(), Optional.of(Letter.UNKNOWN));
}
 
Example #22
Source File: TestMemoryMetadata.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSchema()
{
    assertEquals(metadata.listSchemaNames(SESSION), ImmutableList.of("default"));
    metadata.createSchema(SESSION, "test", ImmutableMap.of(), new PrestoPrincipal(USER, SESSION.getUser()));
    assertEquals(metadata.listSchemaNames(SESSION), ImmutableList.of("default", "test"));
    assertEquals(metadata.listTables(SESSION, Optional.of("test")), ImmutableList.of());

    SchemaTableName tableName = new SchemaTableName("test", "first_table");
    metadata.createTable(
            SESSION,
            new ConnectorTableMetadata(
                    tableName,
                    ImmutableList.of(),
                    ImmutableMap.of()),
            false);

    assertEquals(metadata.listTables(SESSION, Optional.empty()), ImmutableList.of(tableName));
    assertEquals(metadata.listTables(SESSION, Optional.of("test")), ImmutableList.of(tableName));
    assertEquals(metadata.listTables(SESSION, Optional.of("default")), ImmutableList.of());
}
 
Example #23
Source File: TruceCommand.java    From EagleFactions with MIT License 6 votes vote down vote up
private void sendInvite(final Player player, final Faction playerFaction, final Faction targetFaction) throws CommandException
{
	final AllyRequest invite = new AllyRequest(playerFaction.getName(), targetFaction.getName());
	if(EagleFactionsPlugin.TRUCE_INVITE_LIST.contains(invite))
		throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, Messages.YOU_HAVE_ALREADY_INVITED_THIS_FACTION_TO_THE_TRUCE));

	EagleFactionsPlugin.TRUCE_INVITE_LIST.add(invite);

	final Optional<Player> optionalInvitedFactionLeader = super.getPlugin().getPlayerManager().getPlayer(targetFaction.getLeader());

	optionalInvitedFactionLeader.ifPresent(x-> optionalInvitedFactionLeader.get().sendMessage(getInviteGetMessage(playerFaction)));
	targetFaction.getOfficers().forEach(x-> super.getPlugin().getPlayerManager().getPlayer(x).ifPresent(y-> getInviteGetMessage(playerFaction)));

	player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, MessageLoader.parseMessage(Messages.YOU_HAVE_INVITED_FACTION_TO_THE_TRUCE, TextColors.GREEN, ImmutableMap.of(Placeholders.FACTION_NAME, Text.of(TextColors.GOLD, targetFaction.getName())))));

	final Task.Builder taskBuilder = Sponge.getScheduler().createTaskBuilder();
	taskBuilder.execute(() -> EagleFactionsPlugin.TRUCE_INVITE_LIST.remove(invite)).delay(2, TimeUnit.MINUTES).name("EagleFaction - Remove Invite").submit(super.getPlugin());
}
 
Example #24
Source File: ProtoOutputFormatterCallback.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
protected void addAttributes(
    Build.Rule.Builder rulePb, Rule rule, Object extraDataForAttrHash) {
  // We know <code>currentTarget</code> will be one of these two types of configured targets
  // because this method is only triggered in ProtoOutputFormatter.toTargetProtoBuffer when
  // the target in currentTarget is an instanceof Rule.
  ImmutableMap<Label, ConfigMatchingProvider> configConditions;
  if (currentTarget instanceof AliasConfiguredTarget) {
    configConditions = ((AliasConfiguredTarget) currentTarget).getConfigConditions();
  } else if (currentTarget instanceof RuleConfiguredTarget) {
    configConditions = ((RuleConfiguredTarget) currentTarget).getConfigConditions();
  } else {
    // Other subclasses of ConfiguredTarget don't have attribute information.
    return;
  }
  ConfiguredAttributeMapper attributeMapper =
      ConfiguredAttributeMapper.of(rule, configConditions);
  Map<Attribute, Build.Attribute> serializedAttributes = Maps.newHashMap();
  for (Attribute attr : rule.getAttributes()) {
    if (!shouldIncludeAttribute(rule, attr)) {
      continue;
    }
    Object attributeValue = attributeMapper.get(attr.getName(), attr.getType());
    Build.Attribute serializedAttribute =
        AttributeFormatter.getAttributeProto(
            attr,
            attributeValue,
            rule.isAttributeValueExplicitlySpecified(attr),
            /*encodeBooleanAndTriStateAsIntegerAndString=*/ true);
    serializedAttributes.put(attr, serializedAttribute);
  }
  rulePb.addAllAttribute(serializedAttributes.values());
}
 
Example #25
Source File: OmnibusTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void extraLdFlags() throws NoSuchBuildTargetException {
  NativeLinkable a = new OmnibusNode("//:a");
  NativeLinkTarget root = new OmnibusRootNode("//:root", ImmutableList.of(a));
  String flag = "-flag";

  // Verify the libs.
  ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
  SourcePathResolverAdapter pathResolver = graphBuilder.getSourcePathResolver();
  BuildTarget target = BuildTargetFactory.newInstance("//:rule");
  FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
  ImmutableMap<String, SourcePath> libs =
      toSonameMap(
          Omnibus.getSharedLibraries(
              target,
              filesystem,
              TestBuildRuleParams.create(),
              TestCellPathResolver.get(filesystem),
              graphBuilder,
              CxxPlatformUtils.DEFAULT_CONFIG,
              CxxPlatformUtils.DEFAULT_PLATFORM,
              ImmutableList.of(StringArg.of(flag)),
              ImmutableList.of(root),
              ImmutableList.of()));
  assertThat(
      Arg.stringify(
          getCxxLinkRule(graphBuilder, libs.get(root.getBuildTarget().toString())).getArgs(),
          pathResolver),
      Matchers.hasItem(flag));
  assertThat(
      Arg.stringify(
          getCxxLinkRule(graphBuilder, libs.get("libomnibus.so")).getArgs(), pathResolver),
      Matchers.hasItem(flag));
}
 
Example #26
Source File: LastHopOutgoingInterfaceManager.java    From batfish with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
LastHopOutgoingInterfaceManager(
    BDDPacket pkt, Map<NodeInterfacePair, BDDFiniteDomain<NodeInterfacePair>> finiteDomains) {
  _finiteDomains = ImmutableMap.copyOf(finiteDomains);
  _receivingNodes =
      _finiteDomains.keySet().stream()
          .map(NodeInterfacePair::getHostname)
          .collect(ImmutableSet.toImmutableSet());
  _trueBdd = pkt.getFactory().one();
}
 
Example #27
Source File: DedupQueueShadedClientTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Test
public void testHostDiscovery() throws Exception {
    TestingServer server = new TestingServer();

    try (CuratorFramework curator = CuratorFrameworkFactory.newClient(
            server.getConnectString(), new RetryNTimes(3, 100))) {
        curator.start();

        ObjectMapper objectMapper = new ObjectMapper();
        curator.newNamespaceAwareEnsurePath("/ostrich/emodb-dedupq").ensure(curator.getZookeeperClient());
        curator.create().forPath("/ostrich/emodb-dedupq/local_default", objectMapper.writeValueAsString(
                ImmutableMap.builder()
                        .put("name", "test-name")
                        .put("id", "test-id")
                        .put("payload", objectMapper.writeValueAsString(ImmutableMap.of(
                                "serviceUrl", "/dedupq/1",
                                "adminUrl", "/")))
                        .build())
                .getBytes(Charsets.UTF_8));

        AuthDedupQueueService client = EmoServicePoolBuilder.create(AuthDedupQueueService.class)
                .withHostDiscovery(new EmoZooKeeperHostDiscovery(curator, "emodb-dedupq"))
                .withServiceFactory(DedupQueueClientFactory.forClusterAndHttpClient("local_default", client()))
                .withCachingPolicy(ServiceCachingPolicyBuilder.getMultiThreadedClientPolicy())
                .buildProxy(new ExponentialBackoffRetry(5, 50, 1000, TimeUnit.MILLISECONDS));

        long size = client.getMessageCount(API_KEY, "test-queue");
        assertEquals(size, 10);
    }
}
 
Example #28
Source File: AssetBlobCleanupTaskManager.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private void scheduleAssetBlobCleanupTask(final String format, final String contentStore) {
  Map<String, String> settings = ImmutableMap.of(FORMAT_FIELD_ID, format, CONTENT_STORE_FIELD_ID, contentStore);
  if (taskScheduler.getTaskByTypeId(TYPE_ID, settings) == null) {
    TaskConfiguration taskConfiguration = taskScheduler.createTaskConfigurationInstance(TYPE_ID);
    taskConfiguration.setName("Cleanup unused " + format + " blobs from " + contentStore);
    taskConfiguration.setString(FORMAT_FIELD_ID, format);
    taskConfiguration.setString(CONTENT_STORE_FIELD_ID, contentStore);
    Schedule schedule = taskScheduler.getScheduleFactory().cron(new Date(), CRON_SCHEDULE);
    log.info("Scheduling cleanup of unused {} blobs from {}", format, contentStore);
    taskScheduler.scheduleTask(taskConfiguration, schedule);
  }
}
 
Example #29
Source File: TestCostCalculator.java    From presto with Apache License 2.0 5 votes vote down vote up
@Test
public void testRepartitionedJoinWithExchange()
{
    TableScanNode ts1 = tableScan("ts1", "orderkey");
    TableScanNode ts2 = tableScan("ts2", "orderkey_0");
    ExchangeNode remoteExchange1 = partitionedExchange(new PlanNodeId("re1"), REMOTE, ts1, ImmutableList.of(new Symbol("orderkey")), Optional.empty());
    ExchangeNode remoteExchange2 = partitionedExchange(new PlanNodeId("re2"), REMOTE, ts2, ImmutableList.of(new Symbol("orderkey_0")), Optional.empty());
    ExchangeNode localExchange = partitionedExchange(new PlanNodeId("le"), LOCAL, remoteExchange2, ImmutableList.of(new Symbol("orderkey_0")), Optional.empty());

    JoinNode join = join("join",
            remoteExchange1,
            localExchange,
            JoinNode.DistributionType.PARTITIONED,
            "orderkey",
            "orderkey_0");

    Map<String, PlanNodeStatsEstimate> stats = ImmutableMap.<String, PlanNodeStatsEstimate>builder()
            .put("join", statsEstimate(join, 12000))
            .put("re1", statsEstimate(remoteExchange1, 10000))
            .put("re2", statsEstimate(remoteExchange2, 10000))
            .put("le", statsEstimate(localExchange, 6000))
            .put("ts1", statsEstimate(ts1, 6000))
            .put("ts2", statsEstimate(ts2, 1000))
            .build();
    Map<String, Type> types = ImmutableMap.of(
            "orderkey", BIGINT,
            "orderkey_0", BIGINT);

    assertFragmentedEqualsUnfragmented(join, stats, types);
}
 
Example #30
Source File: GrpcAdGroupAudienceViewServiceStub.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an instance of GrpcAdGroupAudienceViewServiceStub, using the given settings. This is
 * protected so that it is easy to make a subclass, but otherwise, the static factory methods
 * should be preferred.
 */
protected GrpcAdGroupAudienceViewServiceStub(
    AdGroupAudienceViewServiceStubSettings settings,
    ClientContext clientContext,
    GrpcStubCallableFactory callableFactory)
    throws IOException {
  this.callableFactory = callableFactory;

  GrpcCallSettings<GetAdGroupAudienceViewRequest, AdGroupAudienceView>
      getAdGroupAudienceViewTransportSettings =
          GrpcCallSettings.<GetAdGroupAudienceViewRequest, AdGroupAudienceView>newBuilder()
              .setMethodDescriptor(getAdGroupAudienceViewMethodDescriptor)
              .setParamsExtractor(
                  new RequestParamsExtractor<GetAdGroupAudienceViewRequest>() {
                    @Override
                    public Map<String, String> extract(GetAdGroupAudienceViewRequest request) {
                      ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
                      params.put("resource_name", String.valueOf(request.getResourceName()));
                      return params.build();
                    }
                  })
              .build();

  this.getAdGroupAudienceViewCallable =
      callableFactory.createUnaryCallable(
          getAdGroupAudienceViewTransportSettings,
          settings.getAdGroupAudienceViewSettings(),
          clientContext);

  backgroundResources = new BackgroundResourceAggregation(clientContext.getBackgroundResources());
}