com.google.common.collect.ImmutableList Java Examples

The following examples show how to use com.google.common.collect.ImmutableList. 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: BytecodeBinder.java    From turbine with Apache License 2.0 6 votes vote down vote up
static Type bindTy(Sig.TySig sig, Function<String, TyVarSymbol> scope) {
  switch (sig.kind()) {
    case BASE_TY_SIG:
      return Type.PrimTy.create(((Sig.BaseTySig) sig).type(), ImmutableList.of());
    case CLASS_TY_SIG:
      return bindClassTy((Sig.ClassTySig) sig, scope);
    case TY_VAR_SIG:
      return Type.TyVar.create(scope.apply(((Sig.TyVarSig) sig).name()), ImmutableList.of());
    case ARRAY_TY_SIG:
      return bindArrayTy((Sig.ArrayTySig) sig, scope);
    case WILD_TY_SIG:
      return wildTy((WildTySig) sig, scope);
    case VOID_TY_SIG:
      return Type.VOID;
  }
  throw new AssertionError(sig.kind());
}
 
Example #2
Source File: PacketHeaderConstraintsUtil.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Convert {@link PacketHeaderConstraints} to an {@link AclLineMatchExpr}.
 *
 * @param phc the packet header constraints
 * @param srcIpSpace Resolved source IP space
 * @param dstIpSpace Resolved destination IP space
 */
public static AclLineMatchExpr toAclLineMatchExpr(
    PacketHeaderConstraints phc, IpSpace srcIpSpace, IpSpace dstIpSpace) {
  List<AclLineMatchExpr> conjuncts =
      Stream.of(
              matchSrc(srcIpSpace),
              matchDst(dstIpSpace),
              dscpsToAclLineMatchExpr(phc.getDscps()),
              ecnsToAclLineMatchExpr(phc.getEcns()),
              packetLengthToAclLineMatchExpr(phc.getPacketLengths()),
              fragmentOffsetsToAclLineMatchExpr(phc.getFragmentOffsets()),
              ipProtocolsToAclLineMatchExpr(phc.getIpProtocols()),
              icmpCodeToAclLineMatchExpr(phc.getIcmpCodes()),
              icmpTypeToAclLineMatchExpr(phc.getIcmpTypes()),
              srcPortsToAclLineMatchExpr(phc.getSrcPorts()),
              dstPortsToAclLineMatchExpr(phc.getDstPorts()),
              applicationsToAclLineMatchExpr(phc.getApplications()),
              tcpFlagsToAclLineMatchExpr(phc.getTcpFlags()))
          .filter(Objects::nonNull)
          .collect(ImmutableList.toImmutableList());

  return and(conjuncts);
}
 
Example #3
Source File: UiExtensionTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Test
public void withPath() throws IOException {
    viewList = ImmutableList.of(FOO_VIEW);
    ext = new UiExtension.Builder(cl, viewList)
            .resourcePath(CUSTOM)
            .build();

    css = new String(toByteArray(ext.css()));
    assertTrue("incorrect css stream", css.contains("custom-css"));
    js = new String(toByteArray(ext.js()));
    assertTrue("incorrect js stream", js.contains("custom-js"));

    assertEquals("expected 1 view", 1, ext.views().size());
    view = ext.views().get(0);
    assertEquals("wrong view category", OTHER, view.category());
    assertEquals("wrong view id", FOO_ID, view.id());
    assertEquals("wrong view label", FOO_LABEL, view.label());

    assertNull("unexpected message handler factory", ext.messageHandlerFactory());
    assertNull("unexpected topo overlay factory", ext.topoOverlayFactory());
}
 
Example #4
Source File: NativeLinkables.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Collect all the shared libraries generated by {@link NativeLinkable}s found by transitively
 * traversing all unbroken dependency chains of {@link NativeLinkable} objects found via the
 * passed in {@link NativeLinkable} roots.
 *
 * @param alwaysIncludeRoots whether to include shared libraries from roots, even if they prefer
 *     static linkage.
 * @return a mapping of library name to the library {@link SourcePath}.
 */
public static ImmutableSortedMap<String, SourcePath> getTransitiveSharedLibraries(
    ActionGraphBuilder graphBuilder,
    Iterable<? extends NativeLinkable> roots,
    boolean alwaysIncludeRoots) {
  ImmutableSet<BuildTarget> rootTargets =
      RichStream.from(roots).map(l -> l.getBuildTarget()).toImmutableSet();

  ImmutableList<? extends NativeLinkable> nativeLinkables =
      getTransitiveNativeLinkables(graphBuilder, roots);

  SharedLibrariesBuilder builder = new SharedLibrariesBuilder();
  builder.addAll(
      graphBuilder,
      nativeLinkables.stream()
          .filter(
              e ->
                  e.getPreferredLinkage() != NativeLinkableGroup.Linkage.STATIC
                      || (alwaysIncludeRoots && rootTargets.contains(e.getBuildTarget())))
          .collect(Collectors.toList()));
  return builder.build();
}
 
Example #5
Source File: D8DexMergerTest.java    From bundletool with Apache License 2.0 6 votes vote down vote up
@Test
public void inputDexFileDoesNotExist_throws() throws Exception {
  Path nonExistentDex = tmpDir.resolve("classes-non-existing.dex");

  IllegalArgumentException exception =
      assertThrows(
          IllegalArgumentException.class,
          () ->
              new D8DexMerger()
                  .merge(
                      ImmutableList.of(nonExistentDex),
                      outputDir,
                      NO_MAIN_DEX_LIST,
                      /* isDebuggable= */ false,
                      /* minSdkVersion= */ ANDROID_K_API_VERSION));

  assertThat(exception).hasMessageThat().contains("was not found");
}
 
Example #6
Source File: TestCompactionSetCreator.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test
public void testBucketedTableCompaction()
{
    List<ShardIndexInfo> inputShards = ImmutableList.of(
            shardWithBucket(1),
            shardWithBucket(2),
            shardWithBucket(2),
            shardWithBucket(1),
            shardWithBucket(2),
            shardWithBucket(1));

    long tableId = bucketedTableInfo.getTableId();
    Set<OrganizationSet> actual = compactionSetCreator.createCompactionSets(bucketedTableInfo, inputShards);

    assertEquals(actual.size(), 2);

    Set<OrganizationSet> expected = ImmutableSet.of(
            new OrganizationSet(tableId, extractIndexes(inputShards, 0, 3, 5), OptionalInt.of(1)),
            new OrganizationSet(tableId, extractIndexes(inputShards, 1, 2, 4), OptionalInt.of(2)));
    assertEquals(actual, expected);
}
 
Example #7
Source File: BaseProofMapIndexProxyIntegrationTestable.java    From exonum-java-binding with Apache License 2.0 6 votes vote down vote up
@Test
@DisabledProofTest
void verifyProof_MultiEntryMapDoesNotContain() {
  runTestWithView(database::createFork, (map) -> {
    List<MapEntry<HashCode, String>> entries = createMapEntries();
    putAll(map, entries);

    byte[] allOnes = new byte[PROOF_MAP_KEY_SIZE];
    Arrays.fill(allOnes, UnsignedBytes.checkedCast(0xFF));

    List<HashCode> otherKeys = ImmutableList.of(
        HashCode.fromBytes(allOnes),  // [11…1]
        createProofKey("PK1001"),
        createProofKey("PK1002"),
        createProofKey("PK100500")
    );

    for (HashCode key : otherKeys) {
      assertThat(map, provesThatAbsent(key));
    }
  });
}
 
Example #8
Source File: UpgradeManagerTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testPrivateUpgrades() {

  List<Checkpoint> checkpoints = ImmutableList.of(
      new org.sonatype.nexus.upgrade.example.CheckpointFoo()
  );

  List<Upgrade> upgrades = ImmutableList.of(
      new org.sonatype.nexus.upgrade.example.UpgradePrivateModel_1_1(Providers.of(mock(DatabaseInstance.class)))
  );

  UpgradeManager upgradeManager = createUpgradeManager(checkpoints, upgrades);

  List<Upgrade> plan = upgradeManager.selectUpgrades(ImmutableMap.of(), false);

  assertThat(plan, contains(
      instanceOf(org.sonatype.nexus.upgrade.example.UpgradePrivateModel_1_1.class)
  ));
}
 
Example #9
Source File: RepositoryAdminPrivilegeDescriptor.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Inject
public RepositoryAdminPrivilegeDescriptor(final RepositoryManager repositoryManager, final List<Format> formats) {
  super(TYPE, repositoryManager, formats);
  this.formFields = ImmutableList.of(
      new StringTextFormField(
          P_FORMAT,
          messages.format(),
          messages.formatHelp(),
          FormField.MANDATORY
      ),
      new RepositoryCombobox(
          P_REPOSITORY,
          messages.repository(),
          messages.repositoryHelp(),
          true
      ).includeAnEntryForAllRepositories(),
      new StringTextFormField(
          P_ACTIONS,
          messages.actions(),
          messages.actionsHelp(),
          FormField.MANDATORY
      )
  );
}
 
Example #10
Source File: BlazeOptionHandlerTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testParseOptions_explicitConfig() {
  optionHandler.parseOptions(
      ImmutableList.of(
          "c0",
          "--default_override=0:c0=--test_multiple_string=rc",
          "--default_override=0:c0:conf=--test_multiple_string=config",
          "--rc_source=/somewhere/.blazerc",
          "--test_multiple_string=explicit",
          "--config=conf"),
      eventHandler);
  assertThat(eventHandler.getEvents()).isEmpty();
  assertThat(parser.getResidue()).isEmpty();
  assertThat(optionHandler.getRcfileNotes())
      .containsExactly(
          "Reading rc options for 'c0' from /somewhere/.blazerc:\n"
              + "  'c0' options: --test_multiple_string=rc",
          "Found applicable config definition c0:conf in file /somewhere/.blazerc: "
              + "--test_multiple_string=config");

  // "config" is expanded from --config=conf, which occurs last.
  TestOptions options = parser.getOptions(TestOptions.class);
  assertThat(options).isNotNull();
  assertThat(options.testMultipleString).containsExactly("rc", "explicit", "config").inOrder();
}
 
Example #11
Source File: DynamicClusterRebindTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testThrottleAppliesAfterRebind() throws Exception {
    DynamicCluster cluster = origApp.createAndManageChild(EntitySpec.create(DynamicCluster.class)
            .configure(DynamicCluster.MAX_CONCURRENT_CHILD_COMMANDS, 1)
            .configure(DynamicCluster.INITIAL_SIZE, 1)
            .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(DynamicClusterTest.ThrowOnAsyncStartEntity.class))
                    .configure(DynamicClusterTest.ThrowOnAsyncStartEntity.COUNTER, new AtomicInteger()));
    app().start(ImmutableList.of(origApp.newLocalhostProvisioningLocation()));
    EntityAsserts.assertAttributeEquals(cluster, DynamicCluster.GROUP_SIZE, 1);

    rebind(RebindOptions.create().terminateOrigManagementContext(true));
    cluster = Entities.descendants(app(), DynamicCluster.class).iterator().next();
    cluster.resize(10);
    EntityAsserts.assertAttributeEqualsEventually(cluster, DynamicCluster.GROUP_SIZE, 10);
    EntityAsserts.assertAttributeEquals(cluster, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
}
 
Example #12
Source File: HBaseTable.java    From presto-hbase-connector with Apache License 2.0 6 votes vote down vote up
public HBaseTable(String schemaName, HTableDescriptor tabDesc, HBaseConfig config) {
    this.hTableDescriptor = Objects.requireNonNull(tabDesc, "tabDesc is null");
    Objects.requireNonNull(schemaName, "schemaName is null");
    ImmutableList<ColumnMetadata> tableMeta = null;
    try {
        String tableName = tabDesc.getNameAsString() != null && tabDesc.getNameAsString().contains(":") ?
                tabDesc.getNameAsString().split(":")[1] : tabDesc.getNameAsString();
        tableMeta = Utils.getColumnMetaFromJson(schemaName, tableName, config.getMetaDir());
        if (tableMeta == null || tableMeta.size() <= 0) {
            logger.error("OOPS! Table meta info cannot be NULL, table name=" + tabDesc.getNameAsString());
            throw new Exception("Cannot find meta info of table " + tabDesc.getNameAsString() + ".");
        }
    } catch (Exception e) {
        logger.error(e, e.getMessage());
    }
    this.columnsMetadata = tableMeta;
}
 
Example #13
Source File: PubsubMessageToObjectNodeBeamTest.java    From gcp-ingestion with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testDoublyNestedList() throws Exception {
  ObjectNode additionalProperties = Json.createObjectNode();
  ObjectNode parent = Json.readObjectNode("{\n" //
      + "  \"payload\": [[[0],[1]],[[2]]]\n" //
      + "}\n");
  List<Field> bqFields = ImmutableList.of(Field.newBuilder("payload", LegacySQLTypeName.RECORD, //
      Field.newBuilder("list", LegacySQLTypeName.RECORD, //
          Field.newBuilder("list", LegacySQLTypeName.INTEGER).setMode(Mode.REPEATED).build()) //
          .setMode(Mode.REPEATED).build() //
  ).setMode(Mode.REPEATED).build()); //
  Map<String, Object> expected = Json.readMap("{\"payload\":[" //
      + "{\"list\":[{\"list\":[0]},{\"list\":[1]}]}," //
      + "{\"list\":[{\"list\":[2]}]}" //
      + "]}");
  TRANSFORM.transformForBqSchema(parent, bqFields, additionalProperties);
  assertEquals(expected, Json.asMap(parent));
}
 
Example #14
Source File: InterfaceNoMatchMessages.java    From batfish with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> visitInterfaceGroupInterfaceAstNode(
    InterfaceGroupInterfaceAstNode interfaceGroupInterfaceAstNode) {
  Optional<ReferenceBook> refBook =
      _referenceLibrary.getReferenceBook(interfaceGroupInterfaceAstNode.getReferenceBook());
  if (refBook.isPresent()) {
    if (refBook.get().getInterfaceGroups().stream()
        .anyMatch(
            r ->
                r.getName()
                    .equalsIgnoreCase(interfaceGroupInterfaceAstNode.getInterfaceGroup()))) {
      return ImmutableList.of();
    } else {
      return ImmutableList.of(
          getErrorMessageMissingGroup(
              interfaceGroupInterfaceAstNode.getInterfaceGroup(),
              "Interface group",
              interfaceGroupInterfaceAstNode.getReferenceBook(),
              "reference book"));
    }
  } else {
    return ImmutableList.of(
        getErrorMessageMissingBook(
            interfaceGroupInterfaceAstNode.getReferenceBook(), "Reference book"));
  }
}
 
Example #15
Source File: KeyRangeUtils.java    From client-java with Apache License 2.0 6 votes vote down vote up
/**
 * Merge SORTED potential discrete ranges into no more than {@code splitNum} large range.
 *
 * @param ranges the sorted range list to merge
 * @param splitNum upper bound of number of ranges to merge into
 * @return the minimal range which encloses all ranges in this range list.
 */
public static List<KeyRange> mergeSortedRanges(List<KeyRange> ranges, int splitNum) {
  if (splitNum <= 0) {
    throw new RuntimeException("Cannot split ranges by non-positive integer");
  }
  if (ranges == null || ranges.isEmpty() || ranges.size() <= splitNum) {
    return ranges;
  }
  // use ceil for split step
  int step = (ranges.size() + splitNum - 1) / splitNum;
  ImmutableList.Builder<KeyRange> rangeBuilder = ImmutableList.builder();
  for (int i = 0, nowPos = 0; i < splitNum; i++) {
    int nextPos = Math.min(nowPos + step - 1, ranges.size() - 1);
    KeyRange first = ranges.get(nowPos);
    KeyRange last = ranges.get(nextPos);

    Key lowerMin = toRawKey(first.getStart(), true);
    Key upperMax = toRawKey(last.getEnd(), false);

    rangeBuilder.add(makeCoprocRange(lowerMin.toByteString(), upperMax.toByteString()));
    nowPos = nowPos + step;
  }
  return rangeBuilder.build();
}
 
Example #16
Source File: BlazeAndroidBinaryNormalBuildRunContext.java    From intellij with Apache License 2.0 5 votes vote down vote up
BlazeAndroidBinaryNormalBuildRunContext(
    Project project,
    AndroidFacet facet,
    RunConfiguration runConfiguration,
    ExecutionEnvironment env,
    BlazeAndroidBinaryRunConfigurationState configState,
    Label label,
    ImmutableList<String> blazeFlags) {
  super(project, facet, runConfiguration, env, configState, label, blazeFlags);
}
 
Example #17
Source File: HorizontalWithVerticalVelocityAndUncertainty.java    From supl-client with Apache License 2.0 5 votes vote down vote up
public static Collection<Asn1Tag> getPossibleFirstTags() {
  if (TAG_verticalUncertaintySpeedType != null) {
    return ImmutableList.of(TAG_verticalUncertaintySpeedType);
  } else {
    return Asn1Integer.getPossibleFirstTags();
  }
}
 
Example #18
Source File: TextDiffSubjectTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void displayed_sideBySideDiff_hasDiff() throws IOException {
  ImmutableList<String> actual = readAllLinesFromResource(ACTUAL_RESOURCE);
  ImmutableList<String> expected = readAllLinesFromResource(EXPECTED_RESOURCE);
  String diff = Joiner.on('\n').join(readAllLinesFromResource(SIDE_BY_SIDE_DIFF_RESOURCE));
  assertThat(TextDiffSubject.generateSideBySideDiff(expected, actual)).isEqualTo(diff);
}
 
Example #19
Source File: TestClusterTopology.java    From helix with Apache License 2.0 5 votes vote down vote up
@Test
public void whenSerializingClusterTopology() throws IOException {
  List<ClusterTopology.Instance> instances =
      ImmutableList.of(new ClusterTopology.Instance("instance"));

  List<ClusterTopology.Zone> zones = ImmutableList.of(new ClusterTopology.Zone("zone", instances));

  ClusterTopology clusterTopology =
      new ClusterTopology("cluster0", zones, Collections.emptySet());
  ObjectMapper mapper = new ObjectMapper();
  String result = mapper.writeValueAsString(clusterTopology);

  Assert.assertEquals(result,
      "{\"id\":\"cluster0\",\"zones\":[{\"id\":\"zone\",\"instances\":[{\"id\":\"instance\"}]}],\"allInstances\":[]}");
}
 
Example #20
Source File: RangerPolicyFactory.java    From ranger with Apache License 2.0 5 votes vote down vote up
private static List<String> pickFewRandomly(final List<String> list) {
	int resultSize = RANDOM.nextInt(list.size());
	
	Set<String> results = Sets.newHashSet();
	for (int i = 0; i < resultSize; i++) {
		results.add(pickOneRandomly(list));
	}
	return ImmutableList.copyOf(results);
}
 
Example #21
Source File: DefaultJRestlessContainerRequestTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Test
public void testHeadersNotSame() throws IOException {
	Map<String, List<String>> headers = ImmutableMap.of("a", ImmutableList.of("a0", "a1"));
	JRestlessContainerRequest request = new DefaultJRestlessContainerRequest(URI.create("/123"), URI.create("/456"), "DELETE",
			new ByteArrayInputStream("123".getBytes()), headers);
	assertNotSame(headers, request.getHeaders());
}
 
Example #22
Source File: MetricCollection.java    From heroic with Apache License 2.0 5 votes vote down vote up
/**
 * Merge the given collections and return a new metric collection with the sorted values.
 * <p>
 * This expects the source collections being merged to be sorted.
 * <p>
 * This API is not safe, checks must be performed to verify that the encapsulated data type is
 * the same as expected.
 */
static MetricCollection mergeSorted(
    final MetricType type, final List<List<? extends Metric>> values
) {
    final List<Metric> data = ImmutableList.copyOf(Iterators.mergeSorted(
        ImmutableList.copyOf(values.stream().map(Iterable::iterator).iterator()),
        Metric.comparator));
    return build(type, data);
}
 
Example #23
Source File: EntitySshToolTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomSshToolClassConfiguredOnEntityWithPrefix() throws Exception {
    MachineEntity entity = app.addChild(EntitySpec.create(MachineEntity.class)
            .configure(BrooklynConfigKeys.SSH_TOOL_CLASS, RecordingSshTool.class.getName()));
    entity.start(ImmutableList.of(machine));
    runCustomSshToolClass(entity);
}
 
Example #24
Source File: TypeCoercionTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static ImmutableList<RelDataType> combine(
    List<RelDataType> list0,
    List<RelDataType> list1) {
  return ImmutableList.<RelDataType>builder()
      .addAll(list0)
      .addAll(list1)
      .build();
}
 
Example #25
Source File: NdkCxxPlatformIntegrationTest.java    From buck with Apache License 2.0 5 votes vote down vote up
private void assertLibraryArchiveContentDoesNotContain(
    ProjectWorkspace workspace,
    ProjectFilesystem projectFilesystem,
    Path libPath,
    ImmutableSet<String> expectedEntries,
    String content)
    throws Exception {

  NdkCxxToolchainPaths ndkCxxToolchainPaths =
      createNdkCxxToolchainPaths(workspace, projectFilesystem);
  Path arToolPath = ndkCxxToolchainPaths.getToolchainBinPath().resolve("ar");
  Path extractedLibraryPath = tmp.newFolder("extracted-library");

  ProcessExecutorParams params =
      ProcessExecutorParams.builder()
          .setCommand(ImmutableList.of(arToolPath.toString(), "-x", libPath.toString()))
          .setDirectory(extractedLibraryPath)
          .build();
  Result arExecResult = new DefaultProcessExecutor(new TestConsole()).launchAndExecute(params);
  assertEquals(
      String.format(
          "ar failed.\nstdout:\n%sstderr:\n%s",
          arExecResult.getStdout(), arExecResult.getStderr()),
      0,
      arExecResult.getExitCode());

  ImmutableSet<Path> extractedFiles =
      Files.list(extractedLibraryPath).collect(ImmutableSet.toImmutableSet());

  assertEquals(expectedEntries, expectedEntries);
  for (Path extractedFile : extractedFiles) {
    makeFileReadable(extractedFile);
    assertFalse(
        dumpObjectFile(ndkCxxToolchainPaths.getToolchainBinPath(), extractedFile)
            .contains(content));
  }
}
 
Example #26
Source File: RuleAnalysisRulesBuildIntegrationTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void ruleAnalysisRulesCanReturnNamedOutputs() throws IOException {
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "rule_with_named_outputs", tmp)
          .setUp();
  setKnownRuleTypesFactoryFactory(workspace, new BasicRuleRuleDescription());

  Path resultPath = workspace.buildAndReturnOutput("//:foo");
  assertTrue(resultPath.endsWith("d-d-default!!!"));
  resultPath = workspace.buildAndReturnOutput("//:foo[bar]");
  assertTrue(resultPath.endsWith("baz"));
  resultPath = workspace.buildAndReturnOutput("//:foo[qux]");
  assertTrue(resultPath.endsWith("quux"));

  RuleOutput expectedOutput =
      new RuleOutput(
          "foo",
          3,
          ImmutableList.of(),
          ImmutableList.of(),
          ImmutableList.of(
              Paths.get("foo__", "d-d-default!!!"),
              Paths.get("foo__", "baz"),
              Paths.get("foo__", "quux")));

  assertJsonEquals(expectedOutput, resultPath);
}
 
Example #27
Source File: QueryCommandTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test(expected = QueryException.class)
public void testRunMultiQueryWithIncorrectNumberOfSets() throws Exception {
  queryCommand.setArguments(
      ImmutableList.of(
          "deps(%Ss) union testsof(%Ss) union %Ss",
          "//foo:libfoo", "//foo:libfootoo", "--", "//bar:libbar", "//bar:libbaz"));
  queryCommand.formatAndRunQuery(params, env);
}
 
Example #28
Source File: TestFileBasedAccessControl.java    From presto with Apache License 2.0 5 votes vote down vote up
@Test
public void testTableRules()
{
    ConnectorAccessControl accessControl = createAccessControl("table.json");
    accessControl.checkCanSelectFromColumns(ALICE, new SchemaTableName("test", "test"), ImmutableSet.of());
    accessControl.checkCanSelectFromColumns(ALICE, new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());
    accessControl.checkCanSelectFromColumns(ALICE, new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of("bobcolumn"));
    accessControl.checkCanShowColumns(ALICE, new SchemaTableName("bobschema", "bobtable"));
    assertEquals(
            accessControl.filterColumns(ALICE, new SchemaTableName("bobschema", "bobtable"), ImmutableList.of(column("a"))),
            ImmutableList.of(column("a")));
    accessControl.checkCanSelectFromColumns(BOB, new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());
    accessControl.checkCanShowColumns(BOB, new SchemaTableName("bobschema", "bobtable"));
    assertEquals(
            accessControl.filterColumns(BOB, new SchemaTableName("bobschema", "bobtable"), ImmutableList.of(column("a"))),
            ImmutableList.of(column("a")));
    accessControl.checkCanInsertIntoTable(BOB, new SchemaTableName("bobschema", "bobtable"));
    accessControl.checkCanDeleteFromTable(BOB, new SchemaTableName("bobschema", "bobtable"));
    accessControl.checkCanSelectFromColumns(CHARLIE, new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());
    accessControl.checkCanSelectFromColumns(CHARLIE, new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of("bobcolumn"));
    accessControl.checkCanInsertIntoTable(CHARLIE, new SchemaTableName("bobschema", "bobtable"));
    accessControl.checkCanSelectFromColumns(JOE, new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());
    accessControl.checkCanCreateViewWithSelectFromColumns(BOB, new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());
    accessControl.checkCanDropTable(ADMIN, new SchemaTableName("bobschema", "bobtable"));
    accessControl.checkCanRenameTable(ADMIN, new SchemaTableName("bobschema", "bobtable"), new SchemaTableName("aliceschema", "newbobtable"));
    accessControl.checkCanRenameTable(ALICE, new SchemaTableName("aliceschema", "alicetable"), new SchemaTableName("aliceschema", "newalicetable"));
    accessControl.checkCanRenameView(ADMIN, new SchemaTableName("bobschema", "bobview"), new SchemaTableName("aliceschema", "newbobview"));
    accessControl.checkCanRenameView(ALICE, new SchemaTableName("aliceschema", "aliceview"), new SchemaTableName("aliceschema", "newaliceview"));
    assertDenied(() -> accessControl.checkCanInsertIntoTable(ALICE, new SchemaTableName("bobschema", "bobtable")));
    assertDenied(() -> accessControl.checkCanDropTable(BOB, new SchemaTableName("bobschema", "bobtable")));
    assertDenied(() -> accessControl.checkCanRenameTable(BOB, new SchemaTableName("bobschema", "bobtable"), new SchemaTableName("bobschema", "newbobtable")));
    assertDenied(() -> accessControl.checkCanRenameTable(ALICE, new SchemaTableName("aliceschema", "alicetable"), new SchemaTableName("bobschema", "newalicetable")));
    assertDenied(() -> accessControl.checkCanInsertIntoTable(BOB, new SchemaTableName("test", "test")));
    assertDenied(() -> accessControl.checkCanSelectFromColumns(ADMIN, new SchemaTableName("secret", "secret"), ImmutableSet.of()));
    assertDenied(() -> accessControl.checkCanSelectFromColumns(JOE, new SchemaTableName("secret", "secret"), ImmutableSet.of()));
    assertDenied(() -> accessControl.checkCanCreateViewWithSelectFromColumns(JOE, new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of()));
    assertDenied(() -> accessControl.checkCanRenameView(BOB, new SchemaTableName("bobschema", "bobview"), new SchemaTableName("bobschema", "newbobview")));
    assertDenied(() -> accessControl.checkCanRenameView(ALICE, new SchemaTableName("aliceschema", "alicetable"), new SchemaTableName("bobschema", "newalicetable")));
}
 
Example #29
Source File: LogicalFilterExpression.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
@Override
public PlannerGraph rewritePlannerGraph(@Nonnull final List<? extends PlannerGraph> childGraphs) {
    return PlannerGraph.fromNodeAndChildGraphs(
            new PlannerGraph.LogicalOperatorNodeWithInfo(
                    NodeInfo.PREDICATE_FILTER_OPERATOR,
                    ImmutableList.of("WHERE {{pred}}"),
                    ImmutableMap.of("pred", Attribute.gml(getPredicate().toString()))),
            childGraphs);
}
 
Example #30
Source File: BuilderMethodClassifier.java    From auto with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an {@code Optional} describing how to convert a value from the setter's parameter type
 * to the getter's return type using one of the given methods, or {@code Optional.empty()} if the
 * conversion isn't possible. An error will have been reported in the latter case.
 */
private Optional<Function<String, String>> getConvertingSetterFunction(
    ImmutableList<ExecutableElement> copyOfMethods,
    ExecutableElement valueGetter,
    ExecutableElement setter,
    TypeMirror parameterType) {
  DeclaredType targetType = MoreTypes.asDeclared(getterToPropertyType.get(valueGetter));
  for (ExecutableElement copyOfMethod : copyOfMethods) {
    Optional<Function<String, String>> function =
        getConvertingSetterFunction(copyOfMethod, targetType, parameterType);
    if (function.isPresent()) {
      return function;
    }
  }
  String targetTypeSimpleName = targetType.asElement().getSimpleName().toString();
  errorReporter.reportError(
      setter,
      "Parameter type %s of setter method should be %s to match getter %s.%s,"
          + " or it should be a type that can be passed to %s.%s to produce %s",
      parameterType,
      targetType,
      autoValueClass,
      valueGetter.getSimpleName(),
      targetTypeSimpleName,
      copyOfMethods.get(0).getSimpleName(),
      targetType);
  return Optional.empty();
}