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

The following examples show how to use com.google.common.collect.ImmutableBiMap. 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 check out the related API usage on the sidebar.
Example 1
Source Project: yangtools   Source File: PrefixConverters.java    License: 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 2
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 3
Source Project: ovsdb   Source File: SouthboundMapper.java    License: 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 4
Source Project: tac-kbp-eal   Source File: QueryResponseFromERE.java    License: 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 Project: geowave   Source File: TieredSFCIndexFactory.java    License: 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 6
Source Project: batfish   Source File: BDDFiniteDomain.java    License: 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 7
Source Project: ovsdb   Source File: SouthboundMapper.java    License: 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 8
Source Project: auto   Source File: AutoValueProcessor.java    License: 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 9
Source Project: buck   Source File: ResourcesFilter.java    License: 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 10
Source Project: buck   Source File: ResourcesFilter.java    License: 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 11
/**
 * 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 12
@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 13
Source Project: presto   Source File: EffectivePredicateExtractor.java    License: Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 14
Source Project: bazel   Source File: ClassName.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 15
Source Project: presto   Source File: PropertyDerivations.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 16
Source Project: bazel   Source File: ImmutableBiMapCodecTest.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 17
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;
}
 
Example 18
@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))));
}
 
Example 19
Source Project: bazel   Source File: ResolvedToolchainContextTest.java    License: Apache License 2.0 5 votes vote down vote up
@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)));
}
 
Example 20
Source Project: buck   Source File: FilterResourcesStepTest.java    License: Apache License 2.0 5 votes vote down vote up
@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)));
}
 
Example 21
Source Project: spring-cloud-gray   Source File: UserResource.java    License: Apache License 2.0 5 votes vote down vote up
@PostMapping(value = "/logout")
public ApiRes<Map<String, String>> logout() {
    return ApiRes.<Map<String, String>>builder()
            .code("0")
            .data(ImmutableBiMap.of())
            .build();
}
 
Example 22
Source Project: helper   Source File: ImmutableCollectors.java    License: MIT License 5 votes vote down vote up
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
    );
}
 
Example 23
Source Project: atlas   Source File: HBaseStoreManager.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 24
Source Project: EasyMPermission   Source File: BuilderSingularGuavaMaps.java    License: MIT License 5 votes vote down vote up
@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;
}
 
Example 25
@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;
}
 
Example 26
@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;
}
 
Example 27
Source Project: geowave   Source File: TieredSFCIndexFactory.java    License: 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 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());
}
 
Example 28
Source Project: geowave   Source File: TieredSFCIndexStrategy.java    License: 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 29
@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;
}
 
Example 30
Source Project: incubator-atlas   Source File: ClassType.java    License: Apache License 2.0 5 votes vote down vote up
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());
}