类com.google.common.collect.ImmutableBiMap源码实例Demo

下面列出了怎么用com.google.common.collect.ImmutableBiMap的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: yangtools   文件: PrefixConverters.java
/**
 * 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());
}
 
源代码2 项目: jpmml-evaluator   文件: RuleSetModelEvaluator.java
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;
		}
 
源代码3 项目: ovsdb   文件: SouthboundMapper.java
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;
}
 
源代码4 项目: tac-kbp-eal   文件: QueryResponseFromERE.java
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();
}
 
源代码5 项目: geowave   文件: TieredSFCIndexFactory.java
/**
 * 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));
}
 
源代码6 项目: batfish   文件: BDDFiniteDomain.java
/** 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();
}
 
源代码7 项目: ovsdb   文件: SouthboundMapper.java
/**
 * 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);
        }
    }
}
 
源代码8 项目: auto   文件: AutoValueProcessor.java
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());
      });
}
 
源代码9 项目: buck   文件: ResourcesFilter.java
/**
 * 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();
}
 
源代码10 项目: buck   文件: ResourcesFilter.java
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);
        }
      });
}
 
/**
 * 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);
}
 
源代码12 项目: jpmml-evaluator   文件: NeuralNetworkEvaluator.java
@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();
}
 
源代码13 项目: presto   文件: EffectivePredicateExtractor.java
@Override
public Expression visitTableScan(TableScanNode node, Void context)
{
    Map<ColumnHandle, Symbol> assignments = ImmutableBiMap.copyOf(node.getAssignments()).inverse();

    TupleDomain<ColumnHandle> predicate = node.getEnforcedConstraint();
    if (useTableProperties) {
        predicate = metadata.getTableProperties(session, node.getTable()).getPredicate();
    }

    // TODO: replace with metadata.getTableProperties() when table layouts are fully removed
    return domainTranslator.toPredicate(predicate.simplify().transform(assignments::get));
}
 
源代码14 项目: bazel   文件: ClassName.java
/**
 * Returns a new instance of {@code ClassName} that is a shadowed built-in core type (e.g. {@code
 * java/time/MonthDay}) of the current desugar-mirrored core type, assuming {@code this} instance
 * is a desugar-mirrored core type.
 */
public final ClassName mirroredToShadowed() {
  ImmutableBiMap<String, String> verbatimTypeMappings =
      SHADOWED_TO_MIRRORED_TYPE_PREFIX_MAPPINGS.inverse();
  return verbatimTypeMappings.keySet().stream()
      .filter(this::hasPackagePrefix)
      .map(prefix -> replacePackagePrefix(prefix, verbatimTypeMappings.get(prefix)))
      .findAny()
      .orElse(this);
}
 
源代码15 项目: presto   文件: PropertyDerivations.java
@Override
public ActualProperties visitTableScan(TableScanNode node, List<ActualProperties> inputProperties)
{
    TableProperties layout = metadata.getTableProperties(session, node.getTable());
    Map<ColumnHandle, Symbol> assignments = ImmutableBiMap.copyOf(node.getAssignments()).inverse();

    ActualProperties.Builder properties = ActualProperties.builder();

    // Globally constant assignments
    Map<ColumnHandle, NullableValue> globalConstants = new HashMap<>();

    extractFixedValues(layout.getPredicate())
            .orElse(ImmutableMap.of())
            .entrySet().stream()
            .filter(entry -> !entry.getValue().isNull())
            .forEach(entry -> globalConstants.put(entry.getKey(), entry.getValue()));

    Map<Symbol, NullableValue> symbolConstants = globalConstants.entrySet().stream()
            .filter(entry -> assignments.containsKey(entry.getKey()))
            .collect(toMap(entry -> assignments.get(entry.getKey()), Map.Entry::getValue));
    properties.constants(symbolConstants);

    // Partitioning properties
    properties.global(deriveGlobalProperties(layout, assignments, globalConstants));

    // Append the global constants onto the local properties to maximize their translation potential
    List<LocalProperty<ColumnHandle>> constantAppendedLocalProperties = ImmutableList.<LocalProperty<ColumnHandle>>builder()
            .addAll(globalConstants.keySet().stream().map(ConstantProperty::new).iterator())
            .addAll(layout.getLocalProperties())
            .build();
    properties.local(LocalProperties.translate(constantAppendedLocalProperties, column -> Optional.ofNullable(assignments.get(column))));

    return properties.build();
}
 
源代码16 项目: bazel   文件: ImmutableBiMapCodecTest.java
@Test
public void smoke() throws Exception {
  new SerializationTester(
          ImmutableBiMap.of(),
          ImmutableBiMap.of("A", "//foo:A"),
          ImmutableBiMap.of("B", "//foo:B"))
      // Check for order.
      .setVerificationFunction(
          (VerificationFunction<ImmutableBiMap<?, ?>>)
              (deserialized, subject) -> {
                assertThat(deserialized).isEqualTo(subject);
                assertThat(deserialized).containsExactlyEntriesIn(subject).inOrder();
              })
      .runTests();
}
 
源代码17 项目: jpmml-evaluator   文件: EntityUtil.java
static
public <E extends Entity<?>> ImmutableBiMap.Builder<String, E> putAll(List<E> entities, AtomicInteger index, ImmutableBiMap.Builder<String, E> builder){

	for(E entity : entities){
		builder = put(entity, index, builder);
	}

	return builder;
}
 
源代码18 项目: yangtools   文件: BiMapYangNamespaceContextTest.java
@Test
public void testEquals() {
    assertTrue(context.equals(context));
    assertTrue(context.equals(new BiMapYangNamespaceContext(ImmutableBiMap.of("foo", FOO, "bar", BAR))));
    assertFalse(context.equals(null));
    assertFalse(context.equals(new BiMapYangNamespaceContext(ImmutableBiMap.of("foo", FOO))));
    assertFalse(context.equals(new BiMapYangNamespaceContext(ImmutableBiMap.of("bar", BAR))));
}
 
源代码19 项目: bazel   文件: ResolvedToolchainContextTest.java
@Test
public void load_notToolchain() throws Exception {
  scratch.file("foo/BUILD", "filegroup(name = 'not_a_toolchain')");

  ToolchainContextKey toolchainContextKey =
      ToolchainContextKey.key()
          .configurationKey(targetConfigKey)
          .requiredToolchainTypeLabels(testToolchainTypeLabel)
          .build();

  // Create a static UnloadedToolchainContext.
  UnloadedToolchainContext unloadedToolchainContext =
      UnloadedToolchainContextImpl.builder()
          .setKey(toolchainContextKey)
          .setExecutionPlatform(linuxPlatform)
          .setTargetPlatform(linuxPlatform)
          .setRequiredToolchainTypes(ImmutableSet.of(testToolchainType))
          .setRequestedLabelToToolchainType(
              ImmutableMap.of(testToolchainTypeLabel, testToolchainType))
          .setToolchainTypeToResolved(
              ImmutableBiMap.<ToolchainTypeInfo, Label>builder()
                  .put(testToolchainType, Label.parseAbsoluteUnchecked("//foo:not_a_toolchain"))
                  .build())
          .build();

  // Create the prerequisites, which is not actually a valid toolchain.
  ConfiguredTargetAndData toolchain =
      getConfiguredTargetAndData(
          Label.parseAbsoluteUnchecked("//foo:not_a_toolchain"), targetConfig);
  assertThrows(
      ToolchainException.class,
      () ->
          ResolvedToolchainContext.load(
              toolchain.getTarget().getPackage().getRepositoryMapping(),
              unloadedToolchainContext,
              "test",
              ImmutableList.of(toolchain)));
}
 
源代码20 项目: buck   文件: FilterResourcesStepTest.java
@Test
public void xmlDrawableResourcesFiltered() throws IOException, InterruptedException {
  ResourceFilters.Density targetDensity = ResourceFilters.Density.MDPI;
  ResourceFilters.Density excludedDensity = ResourceFilters.Density.LDPI;
  final String file = "somefile.xml";
  Path resDir = Paths.get("res");
  Path resOutDir = Paths.get("res-out");

  ProjectFilesystem filesystem = new FakeProjectFilesystem();
  filesystem.mkdirs(resDir);
  filesystem.createNewFile(
      resDir.resolve(String.format("drawable-%s", targetDensity)).resolve(file));
  filesystem.createNewFile(
      resDir.resolve(String.format("drawable-%s", excludedDensity)).resolve(file));

  FilterResourcesSteps filterResourcesSteps =
      new FilterResourcesSteps(
          filesystem,
          ImmutableBiMap.of(resDir, resOutDir),
          /* filterByDPI */ true,
          /* enableStringWhitelisting */ false,
          /* whitelistedStringDirs */ ImmutableSet.of(),
          /* locales */ ImmutableSet.of(),
          /* localizedStringFileName */ Optional.empty(),
          DefaultFilteredDirectoryCopier.getInstance(),
          ImmutableSet.of(targetDensity),
          FilterResourcesSteps.DefaultDrawableFinder.getInstance(),
          /* imageScaler */ null);
  filterResourcesSteps.getCopyStep().execute(null);
  filterResourcesSteps.getScaleStep().execute(null);

  assertThat(
      filesystem,
      ProjectFilesystemMatchers.pathExists(
          resOutDir.resolve(String.format("drawable-%s", targetDensity)).resolve(file)));
  assertThat(
      filesystem,
      ProjectFilesystemMatchers.pathDoesNotExist(
          resOutDir.resolve(String.format("drawable-%s", excludedDensity)).resolve(file)));
}
 
源代码21 项目: spring-cloud-gray   文件: UserResource.java
@PostMapping(value = "/logout")
public ApiRes<Map<String, String>> logout() {
    return ApiRes.<Map<String, String>>builder()
            .code("0")
            .data(ImmutableBiMap.of())
            .build();
}
 
源代码22 项目: helper   文件: ImmutableCollectors.java
public static <T, K, V> Collector<T, ?, ImmutableBiMap<K, V>> toBiMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) {
    return Collector.of(
            ImmutableBiMap.Builder<K, V>::new,
            (builder, input) -> builder.put(keyMapper.apply(input), valueMapper.apply(input)),
            (l, r) -> l.putAll(r.build()),
            ImmutableBiMap.Builder::build
    );
}
 
源代码23 项目: atlas   文件: HBaseStoreManager.java
public static BiMap<String, String> createShortCfMap(Configuration config) {
    return ImmutableBiMap.<String, String>builder()
            .put(INDEXSTORE_NAME, "g")
            .put(INDEXSTORE_NAME + LOCK_STORE_SUFFIX, "h")
            .put(config.get(IDS_STORE_NAME), "i")
            .put(EDGESTORE_NAME, "e")
            .put(EDGESTORE_NAME + LOCK_STORE_SUFFIX, "f")
            .put(SYSTEM_PROPERTIES_STORE_NAME, "s")
            .put(SYSTEM_PROPERTIES_STORE_NAME + LOCK_STORE_SUFFIX, "t")
            .put(SYSTEM_MGMT_LOG_NAME, "m")
            .put(SYSTEM_TX_LOG_NAME, "l")
            .build();
}
 
源代码24 项目: EasyMPermission   文件: BuilderSingularGuavaMaps.java
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public BuilderSingularGuavaMapsBuilder<K, V> rawMap(final java.lang.Object rawMap$key, final java.lang.Object rawMap$value) {
	if (this.rawMap == null) this.rawMap = com.google.common.collect.ImmutableBiMap.builder();
	this.rawMap.put(rawMap$key, rawMap$value);
	return this;
}
 
@java.lang.SuppressWarnings("all")
SingularGuavaBiMap(final ImmutableBiMap rawTypes, final ImmutableBiMap<Integer, Float> integers, final ImmutableBiMap<A, B> generics, final ImmutableBiMap<? extends Number, ? extends String> extendsGenerics) {
  this.rawTypes = rawTypes;
  this.integers = integers;
  this.generics = generics;
  this.extendsGenerics = extendsGenerics;
}
 
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
SingularGuavaBiMap2(final ImmutableBiMap rawTypes, final ImmutableBiMap<Integer, Float> integers, final ImmutableBiMap<A, B> generics, final ImmutableBiMap<? extends Number, ? extends String> extendsGenerics) {
  this.rawTypes = rawTypes;
  this.integers = integers;
  this.generics = generics;
  this.extendsGenerics = extendsGenerics;
}
 
源代码27 项目: geowave   文件: TieredSFCIndexFactory.java
/**
 * @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 maxEstimatedDuplicatedIds the max number of duplicate SFC IDs
 * @return an Index Strategy object with a tier for every incremental cardinality between the
 *         lowest max bits of precision and 0
 */
public static TieredSFCIndexStrategy createFullIncrementalTieredStrategy(
    final NumericDimensionDefinition[] baseDefinitions,
    final int[] maxBitsPerDimension,
    final SFCType sfcType,
    final Long maxEstimatedDuplicatedIds) {
  if (maxBitsPerDimension.length == 0) {
    final ImmutableBiMap<Integer, Byte> emptyMap = ImmutableBiMap.of();
    return new TieredSFCIndexStrategy(baseDefinitions, new SpaceFillingCurve[] {}, emptyMap);
  }
  int numIndices = Integer.MAX_VALUE;
  for (final int element : maxBitsPerDimension) {
    numIndices = Math.min(numIndices, element + 1);
  }
  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++) {
      final int bitsOfPrecision = maxBitsPerDimension[d] - (numIndices - sfcIndex - 1);
      maxBitsOfPrecision = Math.max(bitsOfPrecision, maxBitsOfPrecision);
      sfcDimensions[d] = new SFCDimensionDefinition(baseDefinitions[d], bitsOfPrecision);
    }
    sfcIndexToTier.put(sfcIndex, (byte) maxBitsOfPrecision);

    spaceFillingCurves[sfcIndex] = SFCFactory.createSpaceFillingCurve(sfcDimensions, sfcType);
  }
  if ((maxEstimatedDuplicatedIds != null) && (maxEstimatedDuplicatedIds > 0)) {
    return new TieredSFCIndexStrategy(
        baseDefinitions,
        spaceFillingCurves,
        sfcIndexToTier.build(),
        maxEstimatedDuplicatedIds);
  }
  return new TieredSFCIndexStrategy(baseDefinitions, spaceFillingCurves, sfcIndexToTier.build());
}
 
源代码28 项目: geowave   文件: TieredSFCIndexStrategy.java
/**
 * 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);
}
 
@java.lang.SuppressWarnings("all")
protected SingularGuavaBiMap(final SingularGuavaBiMapBuilder<A, B, ?, ?> b) {
  com.google.common.collect.ImmutableBiMap<java.lang.Object, java.lang.Object> rawTypes = b.rawTypes == null ? com.google.common.collect.ImmutableBiMap.<java.lang.Object, java.lang.Object>of() : b.rawTypes.build();
  this.rawTypes = rawTypes;
  com.google.common.collect.ImmutableBiMap<Integer, Float> integers = b.integers == null ? com.google.common.collect.ImmutableBiMap.<Integer, Float>of() : b.integers.build();
  this.integers = integers;
  com.google.common.collect.ImmutableBiMap<A, B> generics = b.generics == null ? com.google.common.collect.ImmutableBiMap.<A, B>of() : b.generics.build();
  this.generics = generics;
  com.google.common.collect.ImmutableBiMap<Number, String> extendsGenerics = b.extendsGenerics == null ? com.google.common.collect.ImmutableBiMap.<Number, String>of() : b.extendsGenerics.build();
  this.extendsGenerics = extendsGenerics;
}
 
源代码30 项目: incubator-atlas   文件: ClassType.java
public ITypedReferenceableInstance createInstanceWithTraits(Id id, AtlasSystemAttributes systemAttributes, Referenceable r, String... traitNames)
throws AtlasException {

    ImmutableMap.Builder<String, ITypedStruct> b = new ImmutableBiMap.Builder<>();
    if (traitNames != null) {
        for (String t : traitNames) {
            TraitType tType = typeSystem.getDataType(TraitType.class, t);
            IStruct iTraitObject = r == null ? null : r.getTrait(t);
            ITypedStruct trait = iTraitObject == null ? tType.createInstance() :
                    tType.convert(iTraitObject, Multiplicity.REQUIRED);
            b.put(t, trait);
        }
    }

    return new ReferenceableInstance(id == null ? new Id(getName()) : id, getName(), systemAttributes, fieldMapping,
            new boolean[fieldMapping.fields.size()], new boolean[fieldMapping.fields.size()],
            fieldMapping.numBools == 0 ? null : new boolean[fieldMapping.numBools],
            fieldMapping.numBytes == 0 ? null : new byte[fieldMapping.numBytes],
            fieldMapping.numShorts == 0 ? null : new short[fieldMapping.numShorts],
            fieldMapping.numInts == 0 ? null : new int[fieldMapping.numInts],
            fieldMapping.numLongs == 0 ? null : new long[fieldMapping.numLongs],
            fieldMapping.numFloats == 0 ? null : new float[fieldMapping.numFloats],
            fieldMapping.numDoubles == 0 ? null : new double[fieldMapping.numDoubles],
            fieldMapping.numBigDecimals == 0 ? null : new BigDecimal[fieldMapping.numBigDecimals],
            fieldMapping.numBigInts == 0 ? null : new BigInteger[fieldMapping.numBigInts],
            fieldMapping.numDates == 0 ? null : new Date[fieldMapping.numDates],
            fieldMapping.numStrings == 0 ? null : new String[fieldMapping.numStrings],
            fieldMapping.numArrays == 0 ? null : new ImmutableList[fieldMapping.numArrays],
            fieldMapping.numMaps == 0 ? null : new ImmutableMap[fieldMapping.numMaps],
            fieldMapping.numStructs == 0 ? null : new StructInstance[fieldMapping.numStructs],
            fieldMapping.numReferenceables == 0 ? null : new ReferenceableInstance[fieldMapping.numReferenceables],
            fieldMapping.numReferenceables == 0 ? null : new Id[fieldMapping.numReferenceables], b.build());
}
 
 同包方法