com.google.common.collect.ImmutableBiMap Java Examples

The following examples show how to use com.google.common.collect.ImmutableBiMap. 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: ResourcesFilter.java    From buck with Apache License 2.0 6 votes vote down vote up
private void maybeAddPostFilterCmdStep(
    BuildContext context,
    BuildableContext buildableContext,
    ImmutableList.Builder<Step> steps,
    ImmutableBiMap<Path, Path> inResDirToOutResDirMap) {
  postFilterResourcesCmd.ifPresent(
      cmd -> {
        OutputStream filterResourcesDataOutputStream = null;
        try {
          Path filterResourcesDataPath = getFilterResourcesDataPath();
          getProjectFilesystem().createParentDirs(filterResourcesDataPath);
          filterResourcesDataOutputStream =
              getProjectFilesystem().newFileOutputStream(filterResourcesDataPath);
          writeFilterResourcesData(filterResourcesDataOutputStream, inResDirToOutResDirMap);
          buildableContext.recordArtifact(filterResourcesDataPath);
          addPostFilterCommandSteps(cmd, context.getSourcePathResolver(), steps);
        } catch (IOException e) {
          throw new RuntimeException("Could not generate/save filter resources data json", e);
        } finally {
          IOUtils.closeQuietly(filterResourcesDataOutputStream);
        }
      });
}
 
Example #2
Source File: PrefixConverters.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Create a prefix {@link Converter} for {@link XPathExpressionException} defined in a particular YANG
 * {@link Module} .Instantiation requires establishing how a module's imports are mapped to actual modules
 * and their namespaces. This information is cached and used for improved lookups.
 *
 * @param ctx A SchemaContext
 * @param module Module in which the XPath is defined
 * @return A new Converter
 */
public static @NonNull Converter<String, QNameModule> create(final SchemaContext ctx, final Module module) {
    // Always check for null ctx
    requireNonNull(ctx, "Schema context may not be null");

    // Use immutable map builder for detection of duplicates (which should never occur)
    final Builder<String, QNameModule> b = ImmutableBiMap.builder();
    b.put(module.getPrefix(), module.getQNameModule());

    for (ModuleImport i : module.getImports()) {
        final Optional<? extends Module> mod = ctx.findModule(i.getModuleName(), i.getRevision());
        checkArgument(mod.isPresent(), "Unsatisfied import of %s by module %s", i, module);

        b.put(i.getPrefix(), mod.get().getQNameModule());
    }

    return Maps.asConverter(b.build());
}
 
Example #3
Source File: TieredSFCIndexFactory.java    From geowave with Apache License 2.0 6 votes vote down vote up
/**
 * Used to create a Single Tier Index Strategy. For example, this would be used to generate a
 * strategy that has Point type spatial data.
 *
 * @param baseDefinitions the numeric dimensions of the strategy
 * @param maxBitsPerDimension the maximum bits to use for each dimension
 * @param sfc the type of space filling curve (e.g. Hilbert)
 * @return an Index Strategy object with a single tier
 */
public static TieredSFCIndexStrategy createSingleTierStrategy(
    final NumericDimensionDefinition[] baseDefinitions,
    final int[] maxBitsPerDimension,
    final SFCType sfc) {
  final SFCDimensionDefinition[] sfcDimensions =
      new SFCDimensionDefinition[baseDefinitions.length];
  int maxBitsOfPrecision = Integer.MIN_VALUE;
  for (int d = 0; d < baseDefinitions.length; d++) {
    sfcDimensions[d] = new SFCDimensionDefinition(baseDefinitions[d], maxBitsPerDimension[d]);
    maxBitsOfPrecision = Math.max(maxBitsPerDimension[d], maxBitsOfPrecision);
  }

  final SpaceFillingCurve[] orderedSfcs =
      new SpaceFillingCurve[] {SFCFactory.createSpaceFillingCurve(sfcDimensions, sfc)};

  return new TieredSFCIndexStrategy(
      baseDefinitions,
      orderedSfcs,
      ImmutableBiMap.of(0, (byte) maxBitsOfPrecision));
}
 
Example #4
Source File: QueryResponseFromERE.java    From tac-kbp-eal with MIT License 6 votes vote down vote up
private static ImmutableSet<CharOffsetSpan> matchJustificationsForDoc(
    final Iterable<DocEventFrameReference> eventFramesMatchedInDoc,
    final DocumentSystemOutput2015 docSystemOutput) {

  final Optional<ImmutableBiMap<String, ResponseSet>> responseSetMap =
      docSystemOutput.linking().responseSetIds();
  checkState(responseSetMap.isPresent());
  final ImmutableSet.Builder<CharOffsetSpan> offsetsB = ImmutableSet.builder();

  for (final DocEventFrameReference docEventFrameReference : eventFramesMatchedInDoc) {
    final ResponseSet rs =
        checkNotNull(responseSetMap.get().get(docEventFrameReference.eventFrameID()));
    final ImmutableSet<Response> responses = rs.asSet();
    final ImmutableSet<CharOffsetSpan> spans = FluentIterable.from(responses)
        .transformAndConcat(ResponseFunctions.predicateJustifications()).toSet();
    offsetsB.addAll(spans);
  }
  return offsetsB.build();
}
 
Example #5
Source File: AutoValueProcessor.java    From auto with Apache License 2.0 6 votes vote down vote up
private void defineVarsForType(
    TypeElement type,
    AutoValueTemplateVars vars,
    ImmutableSet<ExecutableElement> toBuilderMethods,
    ImmutableMap<ExecutableElement, TypeMirror> propertyMethodsAndTypes,
    Optional<BuilderSpec.Builder> maybeBuilder) {
  ImmutableSet<ExecutableElement> propertyMethods = propertyMethodsAndTypes.keySet();
  // We can't use ImmutableList.toImmutableList() for obscure Google-internal reasons.
  vars.toBuilderMethods =
      ImmutableList.copyOf(toBuilderMethods.stream().map(SimpleMethod::new).collect(toList()));
  ImmutableListMultimap<ExecutableElement, AnnotationMirror> annotatedPropertyFields =
      propertyFieldAnnotationMap(type, propertyMethods);
  ImmutableListMultimap<ExecutableElement, AnnotationMirror> annotatedPropertyMethods =
      propertyMethodAnnotationMap(type, propertyMethods);
  vars.props =
      propertySet(propertyMethodsAndTypes, annotatedPropertyFields, annotatedPropertyMethods);
  vars.serialVersionUID = getSerialVersionUID(type);
  // Check for @AutoValue.Builder and add appropriate variables if it is present.
  maybeBuilder.ifPresent(
      builder -> {
        ImmutableBiMap<ExecutableElement, String> methodToPropertyName =
            propertyNameToMethodMap(propertyMethods).inverse();
        builder.defineVars(vars, methodToPropertyName);
        vars.builderAnnotations = copiedClassAnnotations(builder.builderType());
      });
}
 
Example #6
Source File: NeuralNetworkEvaluator.java    From jpmml-evaluator with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public BiMap<String, NeuralEntity> load(NeuralNetwork neuralNetwork){
	ImmutableBiMap.Builder<String, NeuralEntity> builder = new ImmutableBiMap.Builder<>();

	AtomicInteger index = new AtomicInteger(1);

	NeuralInputs neuralInputs = neuralNetwork.getNeuralInputs();
	for(NeuralInput neuralInput : neuralInputs){
		builder = EntityUtil.put(neuralInput, index, builder);
	}

	List<NeuralLayer> neuralLayers = neuralNetwork.getNeuralLayers();
	for(NeuralLayer neuralLayer : neuralLayers){
		List<Neuron> neurons = neuralLayer.getNeurons();

		for(int i = 0; i < neurons.size(); i++){
			Neuron neuron = neurons.get(i);

			builder = EntityUtil.put(neuron, index, builder);
		}
	}

	return builder.build();
}
 
Example #7
Source File: AccessibilityHierarchyAndroid.java    From Accessibility-Test-Framework-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Populate bimap to contain all unique view element class names of a given {@link
 * windowHierarchyElements}.
 */
public ViewElementClassNamesAndroid(
    List<WindowHierarchyElementAndroid> windowHierarchyElements) {
  Map<String, Integer> classIdMap = new HashMap<>();
  for (WindowHierarchyElementAndroid window : windowHierarchyElements) {
    for (ViewHierarchyElementAndroid view : window.getAllViews()) {
      Set<String> classReferenceSet = getSuperclassSet(view);

      for (String className : classReferenceSet) {
        Integer classNameId = classIdMap.get(className);
        if (classNameId == null) {
          classNameId = classIdMap.size();
          classIdMap.put(className, classNameId);
        }
        view.addIdToSuperclassViewList(classNameId);
      }
    }
  }
  this.uniqueViewElementsClassNames = ImmutableBiMap.copyOf(classIdMap);
}
 
Example #8
Source File: SouthboundMapper.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Return the MD-SAL QoS type class corresponding to the QoS type {@link Qos}.
 *
 * @param type the QoS type to match {@link String}
 * @return class matching the input QoS type {@link QosTypeBase}
 */
public static  Class<? extends QosTypeBase> createQosType(final String type) {
    Preconditions.checkNotNull(type);
    if (type.isEmpty()) {
        LOG.info("QoS type not supplied");
        return QosTypeBase.class;
    } else {
        ImmutableBiMap<String, Class<? extends QosTypeBase>> mapper =
                SouthboundConstants.QOS_TYPE_MAP.inverse();
        if (mapper.get(type) == null) {
            LOG.info("QoS type not found in model: {}", type);
            return QosTypeBase.class;
        } else {
            return mapper.get(type);
        }
    }
}
 
Example #9
Source File: BDDFiniteDomain.java    From batfish with Apache License 2.0 6 votes vote down vote up
/** Use the given variable. */
BDDFiniteDomain(BDDInteger var, Set<V> values) {
  int size = values.size();
  BDD one = var.getFactory().one();
  _var = var;
  _varBits = var.getVars();
  if (size == 0) {
    _valueToBdd = ImmutableBiMap.of();
    _isValidValue = one;
  } else if (size == 1) {
    V value = values.iterator().next();
    _valueToBdd = ImmutableBiMap.of(value, one);
    _isValidValue = one;
  } else {
    int bitsRequired = computeBitsRequired(size);
    checkArgument(bitsRequired <= var.getBitvec().length);
    _valueToBdd = computeValueBdds(var, values);
    _isValidValue = var.leq(size - 1);
  }
  _bddToValue = _valueToBdd.inverse();
}
 
Example #10
Source File: RuleSetModelEvaluator.java    From jpmml-evaluator with GNU Affero General Public License v3.0 6 votes vote down vote up
private ImmutableBiMap.Builder<String, SimpleRule> collectRule(Rule rule, AtomicInteger index, ImmutableBiMap.Builder<String, SimpleRule> builder){

			if(rule instanceof SimpleRule){
				SimpleRule simpleRule = (SimpleRule)rule;

				builder = EntityUtil.put(simpleRule, index, builder);
			} else

			if(rule instanceof CompoundRule){
				CompoundRule compoundRule = (CompoundRule)rule;

				builder = collectRules(compoundRule.getRules(), index, builder);
			} else

			{
				throw new UnsupportedElementException(rule);
			}

			return builder;
		}
 
Example #11
Source File: ResourcesFilter.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Sets up filtering of resources, images/drawables and strings in particular, based on build rule
 * parameters {@link #resourceFilter} and {@link #resourceCompressionMode}.
 *
 * <p>{@link FilterResourcesSteps.ResourceFilter} {@code resourceFilter} determines which
 * drawables end up in the APK (based on density - mdpi, hdpi etc), and also whether higher
 * density drawables get scaled down to the specified density (if not present).
 *
 * <p>{@link #resourceCompressionMode} determines whether non-english string resources are
 * packaged separately as assets (and not bundled together into the {@code resources.arsc} file).
 *
 * @param whitelistedStringDirs overrides storing non-english strings as assets for resources
 *     inside these directories.
 */
@VisibleForTesting
FilterResourcesSteps createFilterResourcesSteps(
    ImmutableSet<Path> whitelistedStringDirs,
    ImmutableSet<String> locales,
    Optional<String> localizedStringFileName,
    ImmutableBiMap<Path, Path> resSourceToDestDirMap) {
  FilterResourcesSteps.Builder filterResourcesStepBuilder =
      FilterResourcesSteps.builder()
          .setProjectFilesystem(getProjectFilesystem())
          .setInResToOutResDirMap(resSourceToDestDirMap)
          .setResourceFilter(resourceFilter);

  if (resourceCompressionMode.isStoreStringsAsAssets()) {
    filterResourcesStepBuilder.enableStringWhitelisting();
    filterResourcesStepBuilder.setWhitelistedStringDirs(whitelistedStringDirs);
  }

  filterResourcesStepBuilder.setLocales(locales);
  filterResourcesStepBuilder.setLocalizedStringFileName(localizedStringFileName);

  return filterResourcesStepBuilder.build();
}
 
Example #12
Source File: SouthboundMapper.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
public static List<ProtocolEntry> createMdsalProtocols(final Bridge bridge) {
    Set<String> protocols = null;
    try {
        protocols = bridge.getProtocolsColumn().getData();
    } catch (SchemaVersionMismatchException e) {
        schemaMismatchLog("protocols", "Bridge", e);
    }
    List<ProtocolEntry> protocolList = new ArrayList<>();
    if (protocols != null && !protocols.isEmpty()) {
        ImmutableBiMap<String, Class<? extends OvsdbBridgeProtocolBase>> mapper =
                SouthboundConstants.OVSDB_PROTOCOL_MAP.inverse();
        for (String protocol : protocols) {
            if (protocol != null) {
                final Class<? extends OvsdbBridgeProtocolBase> mapped = mapper.get(protocol);
                if (mapped != null) {
                    protocolList.add(new ProtocolEntryBuilder().setProtocol(mapped).build());
                }
            }
        }
    }
    return protocolList;
}
 
Example #13
Source File: SignatureFilterTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    tester = new ControllerTester();
    applications = tester.controller().applications();
    filter = new SignatureFilter(tester.controller());
    signer = new RequestSigner(privateKey, id.serializedForm(), tester.clock());

    tester.curator().writeTenant(new CloudTenant(appId.tenant(),
                                                 new BillingInfo("id", "code"),
                                                 ImmutableBiMap.of()));
    tester.curator().writeApplication(new Application(appId, tester.clock().instant()));
}
 
Example #14
Source File: SingularGuavaBiMap.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@java.lang.SuppressWarnings("all")
public SingularGuavaBiMap<A, B> build() {
  com.google.common.collect.ImmutableBiMap<java.lang.Object, java.lang.Object> rawTypes = this.rawTypes == null ? com.google.common.collect.ImmutableBiMap.<java.lang.Object, java.lang.Object>of() : this.rawTypes.build();
  com.google.common.collect.ImmutableBiMap<Integer, Float> integers = this.integers == null ? com.google.common.collect.ImmutableBiMap.<Integer, Float>of() : this.integers.build();
  com.google.common.collect.ImmutableBiMap<A, B> generics = this.generics == null ? com.google.common.collect.ImmutableBiMap.<A, B>of() : this.generics.build();
  com.google.common.collect.ImmutableBiMap<Number, String> extendsGenerics = this.extendsGenerics == null ? com.google.common.collect.ImmutableBiMap.<Number, String>of() : this.extendsGenerics.build();
  return new SingularGuavaBiMap<A, B>(rawTypes, integers, generics, extendsGenerics);
}
 
Example #15
Source File: AbstractBug301935Test.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testGetTokenDefMap_02() {
	ITokenDefProvider tokenDefProvider = get(ITokenDefProvider.class);
	ImmutableBiMap<Integer, String> tokens = ImmutableBiMap.copyOf(tokenDefProvider.getTokenDefMap());
	ImmutableBiMap<String,Integer> inverseTokens = tokens.inverse();
	assertTrue("'\n'", inverseTokens.containsKey("'\n'"));
	assertTrue("'\r'", inverseTokens.containsKey("'\r'"));
	assertTrue("RULE_ID", inverseTokens.containsKey("RULE_ID"));
	assertTrue("RULE_ANY_OTHER", inverseTokens.containsKey("RULE_ANY_OTHER"));
	assertTrue("RULE_WS", inverseTokens.containsKey("RULE_WS"));
}
 
Example #16
Source File: TenantSerializer.java    From vespa with Apache License 2.0 5 votes vote down vote up
private BiMap<PublicKey, Principal> developerKeysFromSlime(Inspector array) {
    ImmutableBiMap.Builder<PublicKey, Principal> keys = ImmutableBiMap.builder();
    array.traverse((ArrayTraverser) (__, keyObject) ->
            keys.put(KeyUtils.fromPemEncodedPublicKey(keyObject.field("key").asString()),
                     new SimplePrincipal(keyObject.field("user").asString())));

    return keys.build();
}
 
Example #17
Source File: BiMapPropertiesTest.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
@Test
public void testMutate() {
  BiMapPropertyType value = new BiMapPropertyType.Builder()
      .putNumbers(1, "one")
      .putNumbers(2, "two")
      .mutateNumbers(numbers -> numbers.replaceAll((i, s) -> s.toUpperCase() + " (" + i + ")"))
      .build();
  assertEquals(ImmutableBiMap.of(1, "ONE (1)", 2, "TWO (2)"), value.getNumbers());
}
 
Example #18
Source File: TreeModelEvaluator.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public BiMap<String, Node> load(TreeModel treeModel){
	ImmutableBiMap.Builder<String, Node> builder = new ImmutableBiMap.Builder<>();

	builder = collectNodes(treeModel.getNode(), new AtomicInteger(1), builder);

	return builder.build();
}
 
Example #19
Source File: TieredSFCIndexStrategy.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor used to create a Tiered Index Strategy.
 *
 * @param baseDefinitions the dimension definitions of the space filling curve
 * @param orderedSfcs the space filling curve used to create the strategy
 */
public TieredSFCIndexStrategy(
    final NumericDimensionDefinition[] baseDefinitions,
    final SpaceFillingCurve[] orderedSfcs,
    final ImmutableBiMap<Integer, Byte> orderedSfcIndexToTierId) {
  this(
      baseDefinitions,
      orderedSfcs,
      orderedSfcIndexToTierId,
      DEFAULT_MAX_ESTIMATED_DUPLICATE_IDS_PER_DIMENSION);
}
 
Example #20
Source File: BlazeIdeInterfaceState.java    From intellij with Apache License 2.0 5 votes vote down vote up
public static BlazeIdeInterfaceState fromProto(ProjectData.BlazeIdeInterfaceState proto) {
  ImmutableMap<String, TargetKey> targets =
      ProtoWrapper.map(
          proto.getFileToTargetMap(), ArtifactState::migrateOldKeyFormat, TargetKey::fromProto);
  ImmutableMap.Builder<String, ArtifactState> artifacts = ImmutableMap.builder();
  for (LocalFileOrOutputArtifact output : proto.getIdeInfoFilesList()) {
    ArtifactState state = ArtifactStateProtoConverter.fromProto(output);
    if (state == null) {
      continue;
    }
    artifacts.put(state.getKey(), state);
  }
  return new BlazeIdeInterfaceState(artifacts.build(), ImmutableBiMap.copyOf(targets));
}
 
Example #21
Source File: BuilderSingularGuavaMaps.java    From EasyMPermission with MIT License 5 votes vote down vote up
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public BuilderSingularGuavaMaps<K, V> build() {
	com.google.common.collect.ImmutableMap<K, V> battleaxes = this.battleaxes == null ? com.google.common.collect.ImmutableMap.<K, V>of() : this.battleaxes.build();
	com.google.common.collect.ImmutableSortedMap<Integer, V> vertices = this.vertices == null ? com.google.common.collect.ImmutableSortedMap.<Integer, V>of() : this.vertices.build();
	com.google.common.collect.ImmutableBiMap<java.lang.Object, java.lang.Object> rawMap = this.rawMap == null ? com.google.common.collect.ImmutableBiMap.<java.lang.Object, java.lang.Object>of() : this.rawMap.build();
	return new BuilderSingularGuavaMaps<K, V>(battleaxes, vertices, rawMap);
}
 
Example #22
Source File: OptionsField.java    From cuba with Apache License 2.0 5 votes vote down vote up
/**
 * Sets options from the passed map and automatically applies option caption provider based on map keys.
 *
 * @param map options
 * @see ListOptions#of(Object, Object[])
 */
default void setOptionsMap(Map<String, I> map) {
    checkNotNullArgument(map);

    BiMap<String, I> biMap = ImmutableBiMap.copyOf(map);

    setOptions(new MapOptions<>(map));
    setOptionCaptionProvider(v -> biMap.inverse().get(v));
}
 
Example #23
Source File: ListTldsAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Override
public ImmutableBiMap<String, String> getFieldAliases() {
  return ImmutableBiMap.of(
      "TLD", "tldStr",
      "dns", "dnsPaused",
      "escrow", "escrowEnabled");
}
 
Example #24
Source File: CModuleContent.java    From binnavi with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new content object.
 *
 * @param module The module the content belongs to.
 * @param provider Synchronizes the content with the database.
 * @param listeners Listeners that are notified about changes in the module.
 * @param callgraph Native Call graph of the module.
 * @param functions The functions of the module.
 * @param nativeCallgraph Native Call graph of the module.
 * @param nativeFlowgraphs The native Flow graph views of the module.
 * @param customViews The user-created non-native views of the module.
 * @param viewFunctionMap Address => Function map for fast lookup of functions by address.
 * @param traces List of traces that were recorded for this module.
 */
public CModuleContent(final INaviModule module, final SQLProvider provider,
    final ListenerProvider<IModuleListener> listeners, final CCallgraph callgraph,
    final List<INaviFunction> functions, final ICallgraphView nativeCallgraph,
    final ImmutableList<IFlowgraphView> nativeFlowgraphs, final List<INaviView> customViews,
    final ImmutableBiMap<INaviView, INaviFunction> viewFunctionMap,
    final List<TraceList> traces, final SectionContainer sections,
    final TypeInstanceContainer instanceContainer) {

  Preconditions.checkNotNull(module, "IE02176: Module argument can not be null");
  Preconditions.checkNotNull(provider, "IE02177: Provider argument can not be null");
  Preconditions.checkNotNull(listeners, "IE02178: Listeners argument can not be null");
  Preconditions.checkNotNull(callgraph, "IE02184: Call graph argument can not be null");
  Preconditions.checkNotNull(functions, "IE02185: Functions argument can not be null");
  Preconditions.checkNotNull(
      nativeCallgraph, "IE02204: Native Call graph argument can not be null");
  Preconditions.checkNotNull(
      nativeFlowgraphs, "IE02205: Native Flowgraphs argument can not be null");
  Preconditions.checkNotNull(customViews, "IE02206: Custom Views argument can not be null");
  Preconditions.checkNotNull(
      viewFunctionMap, "IE02207: View Function Map argument can not be null");
  Preconditions.checkNotNull(traces, "IE02208: Traces argument can not be null");
  this.sections = Preconditions.checkNotNull(sections);
  this.instanceContainer = Preconditions.checkNotNull(instanceContainer);
  m_traces = new CTraceContainer(module, traces, provider);
  m_viewContainer = new CViewContainer(
      module, nativeCallgraph, nativeFlowgraphs, customViews, viewFunctionMap, listeners,
      provider);

  m_callgraph = callgraph;
  m_functions = new CFunctionContainer(module, functions);
}
 
Example #25
Source File: BiMapPropertyTest.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
@Test
public void testJacksonInteroperability() {
  // See also https://github.com/google/FreeBuilder/issues/68
  assumeTrue(keys.isSerializableAsMapKey());
  behaviorTester
      .with(SourceBuilder.forTesting()
          .addLine("package com.example;")
          .addLine("import " + JsonProperty.class.getName() + ";")
          .addLine("@%s", FreeBuilder.class)
          .addLine("@%s(builder = DataType.Builder.class)", JsonDeserialize.class)
          .addLine("public interface DataType {")
          .addLine("  @JsonProperty(\"stuff\") %s<%s, %s> %s;",
              ImmutableBiMap.class, keys.type(), values.type(), convention.get())
          .addLine("")
          .addLine("  class Builder extends DataType_Builder {}")
          .addLine("}"))
      .with(testBuilder()
          .addLine("DataType value = new DataType.Builder()")
          .addLine("    .putItems(%s, %s)", keys.example(0), values.example(0))
          .addLine("    .putItems(%s, %s)", keys.example(1), values.example(1))
          .addLine("    .build();")
          .addLine("%1$s mapper = new %1$s()", ObjectMapper.class)
          .addLine("    .registerModule(new %s());", GuavaModule.class)
          .addLine("String json = mapper.writeValueAsString(value);")
          .addLine("DataType clone = mapper.readValue(json, DataType.class);")
          .addLine("assertThat(clone.%s).isEqualTo(%s);",
              convention.get(), exampleMap(0, 0, 1, 1))
          .build())
      .runTest();
}
 
Example #26
Source File: ApiKeyEncryptionTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void createRawToEncryptedKeyMap() {
    // The following map has been pre-computed using "test_cluster" as the cluster name
    _rawToEncryptedKeyMap = ImmutableBiMap.<String, String>builder()
            .put("key-0", "UmInSDEtplM3CRWwdEYs4A/K/JXbvgwxzjvIujtj5u00fEr02GazYhSDU/a8psxDv9izuhsLllOgRJYqSVpJSw")
            .put("key-1", "6vZNCZtWgFu0Kc//drkUDLvXh6UBFbofRh2wiCi5c08uHiHx8dKkTp2d53hA4k7+2msznOEuhvth4gaVpK/AJw")
            .put("key-2", "e8QVbTrXAfI4GyMn/cc1hNh98XLDX2P6PrTZaHU6FU3tYk93dHo+a2zPhaCYdVCNScRDwylC2yiNh6euPqfj5w")
            .put("key-3", "QVRET2/mqrXY3w/6BK4kFLocgSxahBOekeCrj/cx6D8YAZ1Fno/rtev6mX1HCUtutii7LyXl+fvYE5JMJj17UQ")
            .put("key-4", "co8sivg9e+WID5uH4+06rqCXrV80aALfLufHK/xDIa1QoUPsVKNeERPSWtX0WEmEEWrKwASxlWfepLRWdH3Obg")
            .build();
}
 
Example #27
Source File: MockModuleContent.java    From binnavi with Apache License 2.0 5 votes vote down vote up
public MockModuleContent(final INaviModule module, final SQLProvider provider,
    final ListenerProvider<IModuleListener> mListeners, final List<INaviView> views,
    final List<INaviFunction> functions) {

  m_module = module;
  m_listeners = mListeners;
  m_provider = provider;
  m_traces = new CTraceContainer(module, new FilledList<TraceList>(), provider);
  m_nativeCallgraphView = new MockView(m_provider);
  final List<INaviView> customViews = new ArrayList<INaviView>();
  if (views != null) {
    customViews.addAll(views);
  }
  final FilledList<INaviFunction> customfunctions = new FilledList<INaviFunction>();
  if (functions != null) {
    customfunctions.addAll(functions);
  }

  m_viewContainer = new CViewContainer(module, m_nativeCallgraphView,
      new ImmutableList.Builder<IFlowgraphView>().build(), customViews,
      new ImmutableBiMap.Builder<INaviView, INaviFunction>().build(), m_listeners, provider);
  m_functionContainer = new CFunctionContainer(module, customfunctions);

  try {
    sections = new SectionContainer(new SectionContainerBackend(m_provider, module));
    instances = new TypeInstanceContainer(
        new TypeInstanceContainerBackend(m_provider, module, module.getTypeManager(), sections),
        provider);
  } catch (final CouldntLoadDataException e) {
    e.printStackTrace();
  }
}
 
Example #28
Source File: TieredSFCIndexFactory.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * @param baseDefinitions an array of Numeric Dimension Definitions
 * @param maxBitsPerDimension the max cardinality for the Index Strategy
 * @param sfcType the type of space filling curve (e.g. Hilbert)
 * @param numIndices the number of tiers of the Index Strategy
 * @return an Index Strategy object with a specified number of tiers
 */
public static TieredSFCIndexStrategy createEqualIntervalPrecisionTieredStrategy(
    final NumericDimensionDefinition[] baseDefinitions,
    final int[] maxBitsPerDimension,
    final SFCType sfcType,
    final int numIndices) {
  // Subtracting one from the number tiers prevents an extra tier. If
  // we decide to create a catch-all, then we can ignore the subtraction.
  final SpaceFillingCurve[] spaceFillingCurves = new SpaceFillingCurve[numIndices];
  final ImmutableBiMap.Builder<Integer, Byte> sfcIndexToTier = ImmutableBiMap.builder();
  for (int sfcIndex = 0; sfcIndex < numIndices; sfcIndex++) {
    final SFCDimensionDefinition[] sfcDimensions =
        new SFCDimensionDefinition[baseDefinitions.length];
    int maxBitsOfPrecision = Integer.MIN_VALUE;
    for (int d = 0; d < baseDefinitions.length; d++) {
      int bitsOfPrecision;
      if (numIndices == 1) {
        bitsOfPrecision = maxBitsPerDimension[d];
      } else {
        final double bitPrecisionIncrement = ((double) maxBitsPerDimension[d] / (numIndices - 1));
        bitsOfPrecision = (int) (bitPrecisionIncrement * sfcIndex);
      }
      maxBitsOfPrecision = Math.max(bitsOfPrecision, maxBitsOfPrecision);
      sfcDimensions[d] = new SFCDimensionDefinition(baseDefinitions[d], bitsOfPrecision);
    }
    sfcIndexToTier.put(sfcIndex, (byte) maxBitsOfPrecision);
    spaceFillingCurves[sfcIndex] = SFCFactory.createSpaceFillingCurve(sfcDimensions, sfcType);
  }

  return new TieredSFCIndexStrategy(baseDefinitions, spaceFillingCurves, sfcIndexToTier.build());
}
 
Example #29
Source File: AccessibilityCheckResultBaseUtils.java    From Accessibility-Test-Framework-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Takes a list of {@code AccessibilityCheckResult}s and returns a list with only results obtained
 * from the given {@code AccessibilityCheck}. If a BiMap of class aliases is provided, the
 * returned value will also include results obtained from the check class paired with the given
 * class in the BiMap.
 */
static <T extends AccessibilityCheckResult> List<T> getResultsForCheck(
    Iterable<T> results,
    Class<? extends AccessibilityCheck> checkClass,
    @Nullable ImmutableBiMap<?, ?> aliases) {
  List<T> resultsForCheck = new ArrayList<T>();
  for (T result : results) {
    Class<? extends AccessibilityCheck> resultCheckClass = result.getSourceCheckClass();
    Object alias = getAlias(resultCheckClass, aliases);
    if (checkClass.equals(resultCheckClass) || checkClass.equals(alias)) {
      resultsForCheck.add(result);
    }
  }
  return resultsForCheck;
}
 
Example #30
Source File: AccessibilityCheckResultBaseUtils.java    From Accessibility-Test-Framework-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@link Matcher} for an {@link AccessibilityCheckResult} whose source check class
 * matches the given matcher. If a BiMap of class aliases is provided, it can also match a class
 * paired with the source check class in the BiMap.
 *
 * <p>Note: Do not use {@link Matchers#is} for a {@link Class}, as the deprecated form will match
 * only objects of that class instead of the class object itself. Use {@link Matchers#equalTo}
 * instead.
 *
 * @param classMatcher a {@code Matcher} for a {@code Class<? extends AccessibilityCheck>}. Note:
 *     strict typing not enforced for Java 7 compatibility
 * @return a {@code Matcher} for a {@code AccessibilityCheckResult}
 */
static Matcher<AccessibilityCheckResult> matchesChecks(
    final Matcher<?> classMatcher, final @Nullable ImmutableBiMap<?, ?> aliases) {
  return new TypeSafeMemberMatcher<AccessibilityCheckResult>("source check", classMatcher) {
    @Override
    public boolean matchesSafely(AccessibilityCheckResult result) {
      Class<? extends AccessibilityCheck> checkClass = result.getSourceCheckClass();
      if (classMatcher.matches(checkClass)) {
        return true;
      }
      Object alias = getAlias(checkClass, aliases);
      return (alias != null) && classMatcher.matches(alias);
    }
  };
}