Example usage for com.google.common.collect HashBiMap create

List of usage examples for com.google.common.collect HashBiMap create

Introduction

In this page you can find the example usage for com.google.common.collect HashBiMap create.

Prototype

public static <K, V> HashBiMap<K, V> create() 

Source Link

Document

Returns a new, empty HashBiMap with the default initial capacity (16).

Usage

From source file:org.onos.yangtools.sal.binding.generator.util.BindingRuntimeContext.java

private BiMap<String, String> getEnumMapping(final Entry<GeneratedType, Object> typeWithSchema) {
    final TypeDefinition<?> typeDef = (TypeDefinition<?>) typeWithSchema.getValue();

    final EnumerationType enumType;
    if (typeDef instanceof ExtendedType) {
        enumType = (EnumerationType) ((ExtendedType) typeDef).getBaseType();
    } else {/*from  w w  w . j  a v a 2  s .c  o  m*/
        Preconditions.checkArgument(typeDef instanceof EnumerationType);
        enumType = (EnumerationType) typeDef;
    }

    final HashBiMap<String, String> mappedEnums = HashBiMap.create();

    for (final EnumTypeDefinition.EnumPair enumPair : enumType.getValues()) {
        mappedEnums.put(enumPair.getName(), BindingMapping.getClassName(enumPair.getName()));
    }

    // TODO cache these maps for future use
    return mappedEnums;
}

From source file:org.apache.druid.indexing.common.task.CompactionTask.java

private static DimensionsSpec createDimensionsSpec(List<Pair<QueryableIndex, DataSegment>> queryableIndices) {
    final BiMap<String, Integer> uniqueDims = HashBiMap.create();
    final Map<String, DimensionSchema> dimensionSchemaMap = new HashMap<>();

    // Here, we try to retain the order of dimensions as they were specified since the order of dimensions may be
    // optimized for performance.
    // Dimensions are extracted from the recent segments to olders because recent segments are likely to be queried more
    // frequently, and thus the performance should be optimized for recent ones rather than old ones.

    // timelineSegments are sorted in order of interval, but we do a sanity check here.
    final Comparator<Interval> intervalComparator = Comparators.intervalsByStartThenEnd();
    for (int i = 0; i < queryableIndices.size() - 1; i++) {
        final Interval shouldBeSmaller = queryableIndices.get(i).lhs.getDataInterval();
        final Interval shouldBeLarger = queryableIndices.get(i + 1).lhs.getDataInterval();
        Preconditions.checkState(intervalComparator.compare(shouldBeSmaller, shouldBeLarger) <= 0,
                "QueryableIndexes are not sorted! Interval[%s] of segment[%s] is laster than interval[%s] of segment[%s]",
                shouldBeSmaller, queryableIndices.get(i).rhs.getIdentifier(), shouldBeLarger,
                queryableIndices.get(i + 1).rhs.getIdentifier());
    }/*  w  ww  .j  a  v  a  2 s  . c  o m*/

    int index = 0;
    for (Pair<QueryableIndex, DataSegment> pair : Lists.reverse(queryableIndices)) {
        final QueryableIndex queryableIndex = pair.lhs;
        final Map<String, DimensionHandler> dimensionHandlerMap = queryableIndex.getDimensionHandlers();

        for (String dimension : queryableIndex.getAvailableDimensions()) {
            final ColumnHolder columnHolder = Preconditions.checkNotNull(
                    queryableIndex.getColumnHolder(dimension), "Cannot find column for dimension[%s]",
                    dimension);

            if (!uniqueDims.containsKey(dimension)) {
                final DimensionHandler dimensionHandler = Preconditions.checkNotNull(
                        dimensionHandlerMap.get(dimension), "Cannot find dimensionHandler for dimension[%s]",
                        dimension);

                uniqueDims.put(dimension, index++);
                dimensionSchemaMap.put(dimension,
                        createDimensionSchema(columnHolder.getCapabilities().getType(), dimension,
                                dimensionHandler.getMultivalueHandling(),
                                columnHolder.getCapabilities().hasBitmapIndexes()));
            }
        }
    }

    final BiMap<Integer, String> orderedDims = uniqueDims.inverse();
    final List<DimensionSchema> dimensionSchemas = IntStream.range(0, orderedDims.size()).mapToObj(i -> {
        final String dimName = orderedDims.get(i);
        return Preconditions.checkNotNull(dimensionSchemaMap.get(dimName),
                "Cannot find dimension[%s] from dimensionSchemaMap", dimName);
    }).collect(Collectors.toList());

    return new DimensionsSpec(dimensionSchemas, null, null);
}

From source file:org.apache.jackrabbit.oak.upgrade.RepositoryUpgrade.java

/**
 * Copies the full content from the source to the target repository.
 * <p>//from   w w  w  .j  a  va  2s.c  o m
 * The source repository <strong>must not be modified</strong> while
 * the copy operation is running to avoid an inconsistent copy.
 * <p>
 * Note that both the source and the target repository must be closed
 * during the copy operation as this method requires exclusive access
 * to the repositories.
 *
 * @param initializer optional extra repository initializer to use
 * @throws RepositoryException if the copy operation fails
 */
public void copy(RepositoryInitializer initializer) throws RepositoryException {
    RepositoryConfig config = source.getRepositoryConfig();
    logger.info("Copying repository content from {} to Oak", config.getHomeDir());
    try {
        NodeBuilder targetBuilder = target.getRoot().builder();
        final Root upgradeRoot = new UpgradeRoot(targetBuilder);

        String workspaceName = source.getRepositoryConfig().getDefaultWorkspaceName();
        SecurityProviderImpl security = new SecurityProviderImpl(mapSecurityConfig(config.getSecurityConfig()));

        if (skipInitialization) {
            logger.info("Skipping the repository initialization");
        } else {
            // init target repository first
            logger.info("Initializing initial repository content from {}", config.getHomeDir());
            new InitialContent().initialize(targetBuilder);
            if (initializer != null) {
                initializer.initialize(targetBuilder);
            }
            logger.debug("InitialContent completed from {}", config.getHomeDir());

            for (SecurityConfiguration sc : security.getConfigurations()) {
                RepositoryInitializer ri = sc.getRepositoryInitializer();
                ri.initialize(targetBuilder);
                logger.debug("Repository initializer '" + ri.getClass().getName() + "' completed",
                        config.getHomeDir());
            }
            for (SecurityConfiguration sc : security.getConfigurations()) {
                WorkspaceInitializer wi = sc.getWorkspaceInitializer();
                wi.initialize(targetBuilder, workspaceName);
                logger.debug("Workspace initializer '" + wi.getClass().getName() + "' completed",
                        config.getHomeDir());
            }
        }

        HashBiMap<String, String> uriToPrefix = HashBiMap.create();
        logger.info("Copying registered namespaces");
        copyNamespaces(targetBuilder, uriToPrefix);
        logger.debug("Namespace registration completed.");

        if (skipInitialization) {
            logger.info("Skipping registering node types and privileges");
        } else {
            logger.info("Copying registered node types");
            NodeTypeManager ntMgr = new ReadWriteNodeTypeManager() {
                @Override
                protected Tree getTypes() {
                    return upgradeRoot.getTree(NODE_TYPES_PATH);
                }

                @Nonnull
                @Override
                protected Root getWriteRoot() {
                    return upgradeRoot;
                }
            };
            copyNodeTypes(ntMgr, new ValueFactoryImpl(upgradeRoot, NamePathMapper.DEFAULT));
            logger.debug("Node type registration completed.");

            // migrate privileges
            logger.info("Copying registered privileges");
            PrivilegeConfiguration privilegeConfiguration = security
                    .getConfiguration(PrivilegeConfiguration.class);
            copyCustomPrivileges(
                    privilegeConfiguration.getPrivilegeManager(upgradeRoot, NamePathMapper.DEFAULT));
            logger.debug("Privilege registration completed.");

            // Triggers compilation of type information, which we need for
            // the type predicates used by the bulk  copy operations below.
            new TypeEditorProvider(false).getRootEditor(targetBuilder.getBaseState(),
                    targetBuilder.getNodeState(), targetBuilder, null);
        }

        final NodeState reportingSourceRoot = ReportingNodeState.wrap(
                JackrabbitNodeState.createRootNodeState(source, workspaceName, targetBuilder.getNodeState(),
                        uriToPrefix, copyBinariesByReference, skipOnError),
                new LoggingReporter(logger, "Migrating", 10000, -1));
        final NodeState sourceRoot;
        if (skipLongNames) {
            sourceRoot = NameFilteringNodeState.wrap(reportingSourceRoot);
        } else {
            sourceRoot = reportingSourceRoot;
        }

        final Stopwatch watch = Stopwatch.createStarted();

        logger.info("Copying workspace content");
        copyWorkspace(sourceRoot, targetBuilder, workspaceName);
        targetBuilder.getNodeState(); // on TarMK this does call triggers the actual copy
        logger.info("Upgrading workspace content completed in {}s ({})", watch.elapsed(TimeUnit.SECONDS),
                watch);

        if (!versionCopyConfiguration.skipOrphanedVersionsCopy()) {
            logger.info("Copying version storage");
            watch.reset().start();
            copyVersionStorage(sourceRoot, targetBuilder, versionCopyConfiguration);
            targetBuilder.getNodeState(); // on TarMK this does call triggers the actual copy
            logger.info("Version storage copied in {}s ({})", watch.elapsed(TimeUnit.SECONDS), watch);
        } else {
            logger.info("Skipping the version storage as the copyOrphanedVersions is set to false");
        }

        watch.reset().start();
        logger.info("Applying default commit hooks");
        // TODO: default hooks?
        List<CommitHook> hooks = newArrayList();

        UserConfiguration userConf = security.getConfiguration(UserConfiguration.class);
        String groupsPath = userConf.getParameters().getConfigValue(UserConstants.PARAM_GROUP_PATH,
                UserConstants.DEFAULT_GROUP_PATH);

        // hooks specific to the upgrade, need to run first
        hooks.add(new EditorHook(new CompositeEditorProvider(new RestrictionEditorProvider(),
                new GroupEditorProvider(groupsPath),
                // copy referenced version histories
                new VersionableEditor.Provider(sourceRoot, workspaceName, versionCopyConfiguration),
                new SameNameSiblingsEditor.Provider())));

        // this editor works on the VersionableEditor output, so it can't be
        // a part of the same EditorHook
        hooks.add(new EditorHook(new VersionablePropertiesEditor.Provider()));

        // security-related hooks
        for (SecurityConfiguration sc : security.getConfigurations()) {
            hooks.addAll(sc.getCommitHooks(workspaceName));
        }

        if (customCommitHooks != null) {
            hooks.addAll(customCommitHooks);
        }

        markIndexesToBeRebuilt(targetBuilder);

        // type validation, reference and indexing hooks
        hooks.add(new EditorHook(
                new CompositeEditorProvider(createTypeEditorProvider(), createIndexEditorProvider())));

        target.merge(targetBuilder, new LoggingCompositeHook(hooks, source, overrideEarlyShutdown()),
                CommitInfo.EMPTY);
        logger.info("Processing commit hooks completed in {}s ({})", watch.elapsed(TimeUnit.SECONDS), watch);
        logger.debug("Repository upgrade completed.");
    } catch (Exception e) {
        throw new RepositoryException("Failed to copy content", e);
    }
}

From source file:com.example.app.support.address.AddressParser.java

/**
 * Setup String fill value bimap. That is, a bidirectional
 * map of Strings that we use to temporarily insert
 * fill values into the address so that the address parser
 * doesn't get confused.//  w  w  w. j a v  a2  s  .com
 *
 * @return mapping.
 */
private static HashBiMap<String, String> setupConstStringMap() {
    // bidi map to hold string to string mappings
    HashBiMap<String, String> constStrings = HashBiMap.create();

    // Replaces slashes with a temporary string replacement, since the addressparser doesn't get along with them
    constStrings.put("/", "21421161");

    // The address parser gets confused with TBD as an street number, so we replace it with a temporary number
    constStrings.put("TBD", "112521521");
    constStrings.put("Tbd", "4654231");
    constStrings.put("TBD", "9784261");

    // The address parser sometimes removes hashes
    constStrings.put("#", HASHCODE_VALUE);

    constStrings.put("Us Hwy", "Hwy Us28409182");
    constStrings.put("US HWY", "Hwy Us8123754741");
    return constStrings;
}

From source file:org.docx4j.openpackaging.parts.WordprocessingML.StyleDefinitionsPart.java

/**
 * Refresh the style name - ID bimaps, based on styles currently defined in this part.
 * @since 3.3.0//  ww  w.  j  a  v a  2 s . c o m
 */
public void refreshNameIdBiMaps() {

    styleIdToName = HashBiMap.create();
    for (Style s : this.getJaxbElement().getStyle()) {
        if (s.getName() == null || s.getName().getVal() == null) {
            log.info("style has no name!");
        } else if (s.getStyleId() == null || s.getStyleId().trim().length() == 0) {
            log.info("style has no id!");
        } else {
            styleIdToName.put(s.getStyleId(), s.getName().getVal());
        }
    }
    styleNameToId = styleIdToName.inverse();
}

From source file:edu.cuny.qc.speech.AuToBI.util.ClassifierUtils.java

/**
 * Converts a FeatureSet to a list of LibLinear Feature[] descriptions.
 *
 * @param feature_set the feature set to convert
 * @return a list of Feature[] descriptions.
 *//* w  w w. jav a2s. com*/
public static de.bwaldvogel.liblinear.Feature[][] convertFeatureSetToLibLinearFeatures(FeatureSet feature_set)
        throws AuToBIException {

    HashBiMap<Feature, Integer> feature_map = HashBiMap.create();
    int i = 1;
    for (Feature f : feature_set.getFeatures()) {
        feature_map.put(f, i);
        i++;
    }

    return convertFeatureSetToLibLinearFeatures(feature_set, feature_map);
}

From source file:org.jpmml.evaluator.GeneralRegressionModelEvaluator.java

static private BiMap<FieldName, Predictor> parsePredictorRegistry(PredictorList predictorList) {
    BiMap<FieldName, Predictor> result = HashBiMap.create();

    List<Predictor> predictors = predictorList.getPredictors();
    for (Predictor predictor : predictors) {
        result.put(predictor.getName(), predictor);
    }/*from   w w  w  . j  av a 2  s . c o  m*/

    return result;
}

From source file:net.exclaimindustries.geohashdroid.activities.KnownLocationsPicker.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // We've got a layout, so let's use the layout.
    setContentView(R.layout.known_locations);

    // Now, we'll need to get the list of KnownLocations right away so we
    // can put them on the map.  Well, I guess not RIGHT away.  We still
    // have to wait on the map callbacks, but still, let's fetch them now.
    mLocations = KnownLocation.getAllKnownLocations(this);

    // We need maps.
    mMarkerMap = HashBiMap.create();
    mCircleMap = HashBiMap.create();//from  w  w w.  j  a va2  s.  c  o  m

    // Prep a client (it'll get going during onStart)!
    mGoogleClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).addApi(LocationServices.API).build();

    // We need a Geocoder!  Well, not really; if we can't get one, remove
    // the search option.
    if (Geocoder.isPresent()) {
        mGeocoder = new Geocoder(this);

        // A valid Geocoder also means we can attach the click listener.
        final EditText input = (EditText) findViewById(R.id.search);
        final View go = findViewById(R.id.search_go);
        go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchForLocation(input.getText().toString());
            }
        });

        input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_GO) {
                    searchForLocation(v.getText().toString());
                    return true;
                }

                return false;
            }
        });

    } else {
        findViewById(R.id.search_box).setVisibility(View.GONE);
    }

    // Our friend the map needs to get ready, too.
    MapFragment mapFrag = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
    mapFrag.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;

            // I could swear you could do this in XML...
            UiSettings set = mMap.getUiSettings();

            // The My Location button has to go off, as the search bar sort
            // of takes up that space.
            set.setMyLocationButtonEnabled(false);

            // Also, get rid of the map toolbar.  That just doesn't make any
            // sense here if we've already got a search widget handy.
            set.setMapToolbarEnabled(false);

            // Get ready to listen for clicks!
            mMap.setOnMapLongClickListener(KnownLocationsPicker.this);
            mMap.setOnInfoWindowClickListener(KnownLocationsPicker.this);

            // Were we waiting on a long-tapped marker?
            if (mMapClickMarkerOptions != null) {
                // Well, then put the marker back on the map!
                mMapClickMarker = mMap.addMarker(mMapClickMarkerOptions);
                mActiveMarker = mMapClickMarker;
                mMapClickMarker.showInfoWindow();
            }

            // Activate My Location if permissions are right.
            if (checkLocationPermissions(0))
                permissionsGranted();

            // Same as CentralMap, we need to wait on both this AND the Maps
            // API to be ready.
            mMapIsReady = true;
            doReadyChecks();
        }
    });

    // Now, this only kicks in if stock pre-fetching is on.  If it isn't, we
    // ought to make sure the user knows this.
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (!prefs.getBoolean(GHDConstants.PREF_STOCK_ALARM, false)
            && !prefs.getBoolean(GHDConstants.PREF_STOP_BUGGING_ME_PREFETCH_WARNING, false)) {
        // Dialog!
        new AlertDialog.Builder(this).setMessage(R.string.known_locations_prefetch_is_off)
                .setNegativeButton(R.string.stop_reminding_me_label, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putBoolean(GHDConstants.PREF_STOP_BUGGING_ME_PREFETCH_WARNING, true);
                        editor.apply();

                        BackupManager bm = new BackupManager(KnownLocationsPicker.this);
                        bm.dataChanged();
                    }
                }).setNeutralButton(R.string.go_to_preference, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        Intent intent = new Intent(KnownLocationsPicker.this, PreferencesScreen.class);
                        intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
                                PreferencesScreen.OtherPreferenceFragment.class.getName());
                        intent.putExtra(PreferenceActivity.EXTRA_NO_HEADERS, true);
                        startActivity(intent);
                    }
                }).setPositiveButton(R.string.gotcha_label, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }
}

From source file:com.example.app.support.address.AddressParser.java

/**
 * Setup RegularExpression fill value bimap. That is, a bidirectional
 * map of regular expressions that we use to temporarily insert
 * fill values into the address so that the address parser
 * doesn't get confused./*from   w  w w  . ja  va 2s. co  m*/
 *
 * @return mapping.
 */
private static HashBiMap<String, String> formatRegexpStringMap() {
    // bidi map to hold string to regular expression mappings
    // Notice the parantheses around the part that we are temporarily replacing (group)
    // -- these normally do no include surrounding spaces
    HashBiMap<String, String> regexpStrings = HashBiMap.create();

    // remove letter number/number from this address as in "2533 G 3/8 Road"
    regexpStrings.put(" ([a-zA-Z] \\d[\\/-]\\d)", "regexpCode1");

    // remove interstate from this address as in "2880, I-70 Business Loop"
    regexpStrings.put(" ([iI]-\\d+) ", "regExpCode2");

    // remove periods from the middle of words / numbers
    regexpStrings.put("\\s?(\\s*#?\\w+(\\.\\w+)+)", "522597205");

    // remove commas from the middle of words / numbers
    regexpStrings.put("\\s?(\\s*#?\\w+(,\\w+)+)", "784561789");

    // "(Fp-f-1)- 68-1371 Kinzel Place"
    // remove dashes from the middle of words / numbers
    regexpStrings.put("\\s?((\\-?\\s*#?(\\w+\\-\\w*)|(\\w*\\-\\w+))+)", "189237654");

    //555 Rivergate Lane #B1-104
    //Wheeler Circle 314D-6

    /*
    "(Fp-f-1- 68-1371 Kinzel Place"
    "abc-abc abc-abc"
    "abc- abc-"
    "-abc -abc"*/
    return regexpStrings;
}

From source file:com.example.app.support.address.AddressParser.java

/**
 * Generates a bi-map of regular reg expressions that we don't want to escape
 *
 * @return mapping//from  w w  w  .  jav a 2s. c  o  m
 */
private static HashBiMap<String, String> formatdoNotEscapeRegexpStringMap() {
    HashBiMap<String, String> savedRegexpStrings = HashBiMap.create();

    // We don't want to escape dashes in zip codes
    savedRegexpStrings.put("(\\d{5}\\-\\d{4})", "zipCodeRegExp");

    return savedRegexpStrings;
}