Java Code Examples for com.google.common.collect.ImmutableMap

The following examples show how to use com.google.common.collect.ImmutableMap. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: bazel   Source File: FileWriteActionTestCase.java    License: 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 2
Source Project: armeria   Source File: RefreshingAddressResolverTest.java    License: 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 3
Source Project: buck   Source File: WorkerMacroArg.java    License: 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 4
Source Project: buck   Source File: ConfigDifferenceTest.java    License: 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 5
@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 6
Source Project: metacat   Source File: CatalogThriftHiveMetastore.java    License: 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 7
@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 8
Source Project: quark   Source File: QuboleDB.java    License: 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 9
Source Project: drift   Source File: TestThriftEnumMetadata.java    License: 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 10
Source Project: Intake   Source File: SenderExample.java    License: 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 11
Source Project: presto   Source File: SqlStageExecution.java    License: 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 12
@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 13
Source Project: buck   Source File: AndroidBuckConfigTest.java    License: 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 14
Source Project: presto   Source File: TestLogicalPlanner.java    License: 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 15
@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 16
Source Project: presto   Source File: TestDereferencePushDown.java    License: 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 17
Source Project: presto   Source File: TestMemoryMetadata.java    License: 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 18
Source Project: EagleFactions   Source File: TruceCommand.java    License: 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 19
Source Project: buck   Source File: CxxPlatformXcodeConfigGeneratorTest.java    License: 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 20
Source Project: keycloak   Source File: KcOidcBrokerTest.java    License: 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 21
Source Project: hadoop-connectors   Source File: GoogleCloudStorageTest.java    License: 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 22
Source Project: auto   Source File: SimpleValueTypeTest.java    License: 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 23
Source Project: greenbeans   Source File: Handler.java    License: 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 24
Source Project: presto   Source File: TestCostCalculator.java    License: 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 25
Source Project: buck   Source File: FixEndToEndTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotRunScriptAutomaticallyOnCommandFailureIfNotEnabledForCommand(
    EndToEndTestDescriptor test, EndToEndWorkspace workspace) throws Exception {

  workspace.addBuckConfigLocalOptions(
      ImmutableMap.of(
          "fix",
          ImmutableMap.of(
              "fix_script",
              fixPyCommand(),
              "fix_script_contact",
              "[email protected]",
              "fix_script_message",
              "Running {command}; contact {contact}",
              "autofix_enabled",
              "ALWAYS",
              "autofix_commands",
              "test")));
  ProcessResult result = buckCommand(workspace, test, "build", "//:foo");

  result.assertExitCode(ExitCode.PARSE_ERROR);
  assertThat(
      result.getStderr(),
      Matchers.not(
          Matchers.containsString(
              "Running `buck fix`. Invoke this manually with `buck fix --build-id ")));
}
 
Example 26
Source Project: arcusplatform   Source File: VideoDownloadServerModule.java    License: Apache License 2.0 5 votes vote down vote up
@Provides @Named("videoTcpChannelOptions")
public Map<ChannelOption<?>, Object> provideVideoTcpChannelOptions(VideoDownloadServerConfig serverConfig) {
   return ImmutableMap.of(
      ChannelOption.SO_KEEPALIVE, serverConfig.isSoKeepAlive(),
      ChannelOption.SO_SNDBUF, serverConfig.getSndBufferSize(),
      ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, serverConfig.getWriteHighWater(),
      ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, serverConfig.getWriteLowWater()
   );
}
 
Example 27
Source Project: fdb-record-layer   Source File: RecordMetaDataBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private void updateUnionFieldsAndRecordTypes(@Nonnull Descriptors.Descriptor union, boolean processExtensionOptions) {
    final Map<String, RecordTypeBuilder> oldRecordTypes = ImmutableMap.copyOf(recordTypes);
    recordTypes.clear();
    unionFields.clear();
    for (Descriptors.FieldDescriptor unionField : union.getFields()) {
        Descriptors.Descriptor newDescriptor = unionField.getMessageType();
        Descriptors.Descriptor oldDescriptor = findOldDescriptor(unionField, union);
        if (unionFields.containsKey(newDescriptor)) {
            if (!recordTypes.containsKey(newDescriptor.getName())) {
                // Union field was seen before but the record type is unknown? This must not happen.
                throw new MetaDataException("Unknown record type for union field " + unionField.getName());
            }
            // For existing record types, the preferred field is the last one, except if there is one whose name matches.
            remapUnionField(newDescriptor, unionField);
        } else if (oldDescriptor == null) {
            // New field and record type.
            RecordTypeBuilder recordType = processRecordType(unionField, processExtensionOptions);
            if (recordType.getSinceVersion() != null && recordType.getSinceVersion() != version) {
                throw new MetaDataException(String.format("Record type version (%d) does not match meta-data version (%d)",
                        recordType.getSinceVersion(), version));
            } else {
                recordType.setSinceVersion(version);
            }
            unionFields.put(newDescriptor, unionField);
        } else {
            updateRecordType(oldRecordTypes, oldDescriptor, newDescriptor);
            unionFields.put(newDescriptor, unionField);
        }
    }
}
 
Example 28
Source Project: jlineup   Source File: ReportControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
private JobConfig createJobConfigWithUrlAndName(String url, String name) {
    return jobConfigBuilder()
            .withName(name)
            .withUrls(ImmutableMap.of(url,
                    UrlConfig.urlConfigBuilder().withWindowWidths(ImmutableList.of(600)).withMaxScrollHeight(100000).build()))
            .build();

}
 
Example 29
/**
 * Constructs an instance of GrpcCarrierConstantServiceStub, 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 GrpcCarrierConstantServiceStub(
    CarrierConstantServiceStubSettings settings,
    ClientContext clientContext,
    GrpcStubCallableFactory callableFactory)
    throws IOException {
  this.callableFactory = callableFactory;

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

  this.getCarrierConstantCallable =
      callableFactory.createUnaryCallable(
          getCarrierConstantTransportSettings,
          settings.getCarrierConstantSettings(),
          clientContext);

  backgroundResources = new BackgroundResourceAggregation(clientContext.getBackgroundResources());
}
 
Example 30
Source Project: presto   Source File: TestTransactionManager.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFailedTransactionWorkflow()
{
    try (IdleCheckExecutor executor = new IdleCheckExecutor()) {
        CatalogManager catalogManager = new CatalogManager();
        TransactionManager transactionManager = InMemoryTransactionManager.create(new TransactionManagerConfig(), executor.getExecutor(), catalogManager, finishingExecutor);

        Connector c1 = new TpchConnectorFactory().create(CATALOG, ImmutableMap.of(), new TestingConnectorContext());
        registerConnector(catalogManager, transactionManager, CATALOG, CATALOG_NAME, c1);

        TransactionId transactionId = transactionManager.beginTransaction(false);

        assertEquals(transactionManager.getAllTransactionInfos().size(), 1);
        TransactionInfo transactionInfo = transactionManager.getTransactionInfo(transactionId);
        assertFalse(transactionInfo.isAutoCommitContext());
        assertTrue(transactionInfo.getCatalogNames().isEmpty());
        assertFalse(transactionInfo.getWrittenConnectorId().isPresent());

        ConnectorMetadata metadata = transactionManager.getOptionalCatalogMetadata(transactionId, CATALOG).get().getMetadata();
        metadata.listSchemaNames(TEST_SESSION.toConnectorSession(CATALOG_NAME));
        transactionInfo = transactionManager.getTransactionInfo(transactionId);
        assertEquals(transactionInfo.getCatalogNames(), ImmutableList.of(CATALOG_NAME, INFORMATION_SCHEMA_ID, SYSTEM_TABLES_ID));
        assertFalse(transactionInfo.getWrittenConnectorId().isPresent());

        transactionManager.fail(transactionId);
        assertEquals(transactionManager.getAllTransactionInfos().size(), 1);

        assertPrestoExceptionThrownBy(() -> transactionManager.getCatalogMetadata(transactionId, CATALOG_NAME))
                .hasErrorCode(TRANSACTION_ALREADY_ABORTED);

        assertEquals(transactionManager.getAllTransactionInfos().size(), 1);

        getFutureValue(transactionManager.asyncAbort(transactionId));

        assertTrue(transactionManager.getAllTransactionInfos().isEmpty());
    }
}