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

The following examples show how to use com.google.common.collect.BiMap. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: usergrid   Source File: ManagementServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> getOrganizationData( OrganizationInfo organization ) throws Exception {

    Map<String, Object> jsonOrganization = new HashMap<>();
    jsonOrganization.putAll( JsonUtils.toJsonMap( organization ) );

    BiMap<UUID, String> applications = getApplicationsForOrganization( organization.getUuid() );
    jsonOrganization.put( "applications", applications.inverse() );

    List<UserInfo> users = getAdminUsersForOrganization( organization.getUuid() );
    Map<String, Object> jsonUsers = new HashMap<>();
    for ( UserInfo u : users ) {
        jsonUsers.put( u.getUsername(), u );
    }
    jsonOrganization.put( "users", jsonUsers );

    return jsonOrganization;
}
 
Example 2
public static void preInit() {
        if(ModConfig.enableAdditionalNodeTypes) {
            try {
                ItemBlock item = (ItemBlock) Item.getItemFromBlock(ConfigBlocks.blockAiry);

                item.field_150939_a = RegisteredBlocks.blockNode;

                //Hacky way
                FMLControlledNamespacedRegistry<Block> registry = GameData.getBlockRegistry();
                registry.underlyingIntegerMap.field_148749_a.put(RegisteredBlocks.blockNode, Block.getIdFromBlock(ConfigBlocks.blockAiry));
                registry.underlyingIntegerMap.field_148748_b.set(Block.getIdFromBlock(ConfigBlocks.blockAiry), RegisteredBlocks.blockNode);
                ((BiMap)registry.field_148758_b).forcePut(RegisteredBlocks.blockNode, registry.field_148758_b.get(ConfigBlocks.blockAiry));

                registry.underlyingIntegerMap.field_148749_a.remove(ConfigBlocks.blockAiry);

                ConfigBlocks.blockAiry = RegisteredBlocks.blockNode;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
}
 
Example 3
Source Project: Bats   Source File: AbstractMaterializedViewRule.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * It swaps the table references and then the column references of the input
 * expressions using the table mapping and the equivalence classes.
 */
private static NodeLineage generateSwapTableColumnReferencesLineage(RexBuilder rexBuilder, RelMetadataQuery mq,
        RelNode node, BiMap<RelTableRef, RelTableRef> tableMapping, EquivalenceClasses ec,
        List<RexNode> nodeExprs) {
    final Map<RexNode, Integer> exprsLineage = new HashMap<>();
    final Map<RexNode, Integer> exprsLineageLosslessCasts = new HashMap<>();
    for (int i = 0; i < nodeExprs.size(); i++) {
        final Set<RexNode> s = mq.getExpressionLineage(node, nodeExprs.get(i));
        if (s == null) {
            // Next expression
            continue;
        }
        // We only support project - filter - join, thus it should map to
        // a single expression
        assert s.size() == 1;
        // Rewrite expr. First we swap the table references following the table
        // mapping, then we take first element from the corresponding equivalence class
        final RexNode e = RexUtil.swapTableColumnReferences(rexBuilder, s.iterator().next(), tableMapping,
                ec.getEquivalenceClassesMap());
        exprsLineage.put(e, i);
        if (RexUtil.isLosslessCast(e)) {
            exprsLineageLosslessCasts.put(((RexCall) e).getOperands().get(0), i);
        }
    }
    return new NodeLineage(exprsLineage, exprsLineageLosslessCasts);
}
 
Example 4
/**
 * For every TouchDelegate with a rectangular hit region, record the region on the delegatee's
 * ViewHierarchyElement using {@link ViewHierarchyElement#addTouchDelegateBounds(Rect)}
 */
@RequiresApi(Build.VERSION_CODES.Q)
private void resolveTouchDelegateRelationshipsAmongInfos(
    BiMap<Long, AccessibilityNodeInfo> originMap) {
  for (Map.Entry<Long, AccessibilityNodeInfo> entry : originMap.entrySet()) {
    TouchDelegateInfo delegateInfo = entry.getValue().getTouchDelegateInfo();
    if (delegateInfo != null) {
      for (int i = 0; i < delegateInfo.getRegionCount(); ++i) {
        Region hitRegion = delegateInfo.getRegionAt(i);
        if ((hitRegion != null) && hitRegion.isRect()) {
          AccessibilityNodeInfo delegateeNode = delegateInfo.getTargetForRegion(hitRegion);
          ViewHierarchyElement delegatee =
              (delegateeNode != null) ? findElementByNodeInfo(delegateeNode, originMap) : null;
          if (delegatee != null) {
            android.graphics.Rect hitRect = hitRegion.getBounds();
            delegatee.addTouchDelegateBounds(
                new Rect(hitRect.left, hitRect.top, hitRect.right, hitRect.bottom));
          }
        }
      }
    }
  }
}
 
Example 5
Source Project: calcite   Source File: MaterializedViewRule.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * First, the method takes the node expressions {@code nodeExprs} and swaps the table
 * and column references using the table mapping and the equivalence classes.
 * If {@code swapTableColumn} is true, it swaps the table reference and then the column reference,
 * otherwise it swaps the column reference and then the table reference.
 *
 * <p>Then, the method will rewrite the input expression {@code exprToRewrite}, replacing the
 * {@link RexTableInputRef} by references to the positions in {@code nodeExprs}.
 *
 * <p>The method will return the rewritten expression. If any of the expressions in the input
 * expression cannot be mapped, it will return null.
 */
protected RexNode rewriteExpression(
    RexBuilder rexBuilder,
    RelMetadataQuery mq,
    RelNode targetNode,
    RelNode node,
    List<RexNode> nodeExprs,
    BiMap<RelTableRef, RelTableRef> tableMapping,
    EquivalenceClasses ec,
    boolean swapTableColumn,
    RexNode exprToRewrite) {
  List<RexNode> rewrittenExprs = rewriteExpressions(rexBuilder, mq, targetNode, node, nodeExprs,
      tableMapping, ec, swapTableColumn, ImmutableList.of(exprToRewrite));
  if (rewrittenExprs == null) {
    return null;
  }
  assert rewrittenExprs.size() == 1;
  return rewrittenExprs.get(0);
}
 
Example 6
Source Project: levelup-java-examples   Source File: ReverseMapLookup.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void flip_map_entries_with_guava() {

	BiMap<String, String> stateCodeToDescription = HashBiMap.create();

	stateCodeToDescription.put("WI", "Wisconsin");
	stateCodeToDescription.put("MN", "Minnesota");
	stateCodeToDescription.put("FL", "Florida");
	stateCodeToDescription.put("IA", "Iowa");
	stateCodeToDescription.put("OH", "Ohio");

	BiMap<String, String> descriptionToStateCode = stateCodeToDescription
			.inverse();

	logger.info(descriptionToStateCode);

	assertEquals("WI", descriptionToStateCode.get("Wisconsin"));
}
 
Example 7
Source Project: securify   Source File: AbstractDecompiler.java    License: Apache License 2.0 6 votes vote down vote up
protected static BiMap<Integer, String> findTags(final PrintStream log, List<Integer> jumpDestinations) {
	// print tags (jumpdests)
	log.println();
	log.println("Tags:");
	/* Map bytecode offsets to tags/labels and vice versa. */
	BiMap<Integer, String> tags = HashBiMap.create();
	{
		for (int i = 0; i < jumpDestinations.size(); i++) {
			Integer bytecodeOffset = jumpDestinations.get(i);
			String tagLabel = "tag_" + (i + 1);
			tags.put(bytecodeOffset, tagLabel);
			log.println(tagLabel + " @" + HexPrinter.toHex(bytecodeOffset));
		}
		// add virtual tags (error and exit)
		tags.put(ControlFlowDetector.DEST_ERROR, "ERROR");
		tags.put(ControlFlowDetector.DEST_EXIT, "EXIT");
	}
	return tags;
}
 
Example 8
/**
 * For every View in {@code originMap} that has a labelFor value, set labeledBy on the
 * ViewHierarchyElementAndroid that represents the View with the referenced View ID.
 */
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void resolveLabelForRelationshipsAmongViews(
    Context context, BiMap<Long, View> originMap) {
  for (Map.Entry<Long, View> entry : originMap.entrySet()) {
    int labeledViewId = entry.getValue().getLabelFor();
    if (labeledViewId != View.NO_ID) {
      ViewHierarchyElementAndroid labelElement = getViewById(entry.getKey());
      ViewHierarchyElementAndroid labeledElement = findElementByViewId(labeledViewId, originMap);
      if (labeledElement == null) {
        LogUtils.w(
            TAG, "View not found for labelFor = %1$s", resourceName(context, labeledViewId));
      } else {
        labeledElement.setLabeledBy(labelElement);
      }
    }
  }
}
 
Example 9
Source Project: api-mining   Source File: PAM.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Mine API call sequences using PAM
 *
 * @param arffFile
 *            API calls in ARF Format. Attributes are fqCaller and fqCalls
 *            as space separated string of API calls.
 */
public static void mineAPICallSequences(final String arffFile, final String outFile,
		final InferenceAlgorithm inferenceAlgorithm, final int maxStructureSteps, final int maxEMIterations,
		final File logFile) throws Exception {

	final File fout = new File(outFile);
	if (fout.getParentFile() != null)
		fout.getParentFile().mkdirs();

	System.out.print("  Creating temporary transaction DB... ");
	final File transactionDB = File.createTempFile("APICallDB", ".txt");
	final BiMap<String, Integer> dictionary = HashBiMap.create();
	generateTransactionDatabase(arffFile, dictionary, transactionDB);
	System.out.println("done.");

	System.out.print("  Mining interesting sequences... ");
	final Map<Sequence, Double> sequences = PAMCore.mineInterestingSequences(transactionDB, inferenceAlgorithm,
			maxStructureSteps, maxEMIterations, logFile);
	transactionDB.delete();
	System.out.println("done.");

	decodeInterestingSequences(sequences, dictionary, outFile);
}
 
Example 10
Source Project: nuls-v2   Source File: ObjectRef.java    License: MIT License 6 votes vote down vote up
public String getEncoded(BiMap<String, String> classNames) {
        StringBuilder sb = new StringBuilder();
//        Integer i = map.get(desc);
//        if (i == null) {
//            i = 0;
//        }
//        map.put(desc, i + 1);
        String s = desc;
        String s1 = classNames.inverse().get(s);
        if (s1 != null) {
            s = s1;
        }
        sb.append(ref).append(",").append(s);
        for (int dimension : dimensions) {
            sb.append(",").append(dimension);
        }
        return sb.toString();
    }
 
Example 11
Source Project: nuls-v2   Source File: JsonUtils.java    License: MIT License 6 votes vote down vote up
public static String encodeArray(Object value, Class<?> elementType, BiMap<String, String> classNames) {
    String json;
    if (elementType == ObjectRef.class) {
        int length = Array.getLength(value);
        String[] array = new String[length];
        for (int i = 0; i < length; i++) {
            ObjectRef objectRef = (ObjectRef) Array.get(value, i);
            if (objectRef != null) {
                array[i] = objectRef.getEncoded(classNames);
            }
        }
        json = toJson(array);
    } else {
        json = toJson(value);
    }
    return json;
}
 
Example 12
@Test
public void testInvalidTypeOfCorrespondingSchemaNode() throws Exception {
    final SchemaContext schemaContext = YangParserTestUtils.parseYangResources(DerivedFromXPathFunctionTest.class,
            "/yang-xpath-functions-test/derived-from-function/bar-invalid.yang");
    assertNotNull(schemaContext);

    final XPathSchemaContext jaxenSchemaContext = SCHEMA_CONTEXT_FACTORY.createContext(schemaContext);
    final XPathDocument jaxenDocument = jaxenSchemaContext.createDocument(buildMyContainerNode(ID_C2_IDENTITY));

    final BiMap<String, QNameModule> converterBiMap = HashBiMap.create();
    converterBiMap.put("bar-prefix", BAR_MODULE);

    final NormalizedNodeContextSupport normalizedNodeContextSupport = NormalizedNodeContextSupport.create(
            (JaxenDocument) jaxenDocument, Maps.asConverter(converterBiMap));

    final NormalizedNodeContext normalizedNodeContext = normalizedNodeContextSupport.createContext(
            buildPathToIdrefLeafNode());

    final Function derivedFromFunction = normalizedNodeContextSupport.getFunctionContext()
            .getFunction(null, null, "derived-from");

    assertFalse(getDerivedFromResult(derivedFromFunction, normalizedNodeContext, "some-identity"));
}
 
Example 13
@Test
public void testInvalidTypeOfCorrespondingSchemaNode() throws Exception {
    final SchemaContext schemaContext = YangParserTestUtils.parseYangResources(EnumValueXPathFunctionTest.class,
            "/yang-xpath-functions-test/enum-value-function/foo-invalid.yang");
    assertNotNull(schemaContext);

    final XPathSchemaContext jaxenSchemaContext = SCHEMA_CONTEXT_FACTORY.createContext(schemaContext);
    final XPathDocument jaxenDocument = jaxenSchemaContext.createDocument(buildMyContainerNode("major"));

    final BiMap<String, QNameModule> converterBiMap = HashBiMap.create();
    converterBiMap.put("foo-prefix", FOO_MODULE);

    final NormalizedNodeContextSupport normalizedNodeContextSupport = NormalizedNodeContextSupport.create(
            (JaxenDocument) jaxenDocument, Maps.asConverter(converterBiMap));

    final NormalizedNodeContext normalizedNodeContext = normalizedNodeContextSupport.createContext(
            buildPathToSeverityLeafNode("major"));

    final Function enumValueFunction = normalizedNodeContextSupport.getFunctionContext()
            .getFunction(null, null, "enum-value");
    final Double enumValueResult = (Double) enumValueFunction.call(normalizedNodeContext, ImmutableList.of());
    assertEquals(Double.NaN, enumValueResult, 0.001);
}
 
Example 14
@Test
public void testInvalidTypeOfCorrespondingSchemaNode() throws Exception {
    final Set<String> setOfBits = ImmutableSet.of("UP", "PROMISCUOUS");

    final SchemaContext schemaContext = YangParserTestUtils.parseYangResources(BitIsSetXPathFunctionTest.class,
            "/yang-xpath-functions-test/bit-is-set-function/foo-invalid.yang");
    assertNotNull(schemaContext);

    final XPathSchemaContext jaxenSchemaContext = SCHEMA_CONTEXT_FACTORY.createContext(schemaContext);
    final XPathDocument jaxenDocument = jaxenSchemaContext.createDocument(buildMyContainerNode(setOfBits));

    final BiMap<String, QNameModule> converterBiMap = HashBiMap.create();
    converterBiMap.put("foo-prefix", FOO_MODULE);

    final NormalizedNodeContextSupport normalizedNodeContextSupport = NormalizedNodeContextSupport.create(
            (JaxenDocument) jaxenDocument, Maps.asConverter(converterBiMap));

    final NormalizedNodeContext normalizedNodeContext = normalizedNodeContextSupport.createContext(
            buildPathToFlagsLeafNode(setOfBits));

    final Function bitIsSetFunction = normalizedNodeContextSupport.getFunctionContext()
            .getFunction(null, null, "bit-is-set");
    boolean bitIsSetResult = (boolean) bitIsSetFunction.call(normalizedNodeContext, ImmutableList.of("UP"));
    assertFalse(bitIsSetResult);
}
 
Example 15
Source Project: nuls   Source File: ObjectRef.java    License: MIT License 6 votes vote down vote up
public ObjectRef(String str, BiMap<String, String> classNames) {
    String[] parts = str.split(",");
    int[] dimensions = new int[parts.length - 2];
    for (int i = 0; i < dimensions.length; i++) {
        int dimension = Integer.valueOf(parts[i + 2]);
        dimensions[i] = dimension;
    }
    this.ref = parts[0];
    String s = parts[1];
    String s1 = classNames.get(s);
    if (s1 != null) {
        s = s1;
    }
    this.desc = s;
    this.dimensions = dimensions;
    this.variableType = VariableType.valueOf(this.desc);
}
 
Example 16
Source Project: usergrid   Source File: SubjectUtils.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings( "unchecked" )
public static BiMap<UUID, String> getApplications() {
    Subject currentUser = getSubject();
    if ( currentUser == null ) {
        return null;
    }
    if ( !currentUser.hasRole( ROLE_APPLICATION_ADMIN ) && !currentUser.hasRole( ROLE_APPLICATION_USER ) ) {
        return null;
    }
    Session session = currentUser.getSession();

    BiMap<UUID, String> applications = HashBiMap.create();
    Map map = (Map)session.getAttribute( "applications" );
    applications.putAll(map);
    return applications;
}
 
Example 17
Source Project: nexus-public   Source File: UpgradeManager.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Indexes each {@link Checkpoint} registered in the system.
 */
private BiMap<String, Checkpoint> indexCheckpoints(final List<Checkpoint> checkpoints,
                                                   final List<String> problems)
{
  Map<String, List<Checkpoint>> byName = checkpoints.stream()
      .collect(groupingBy(c -> c.getClass().isAnnotationPresent(Checkpoints.class)
          ? c.getClass().getAnnotation(Checkpoints.class).model() : null));

  if (byName.containsKey(null)) {
    byName.remove(null).stream()
        .map(c -> String.format("Checkpoint %s is not annotated with @Checkpoints", className(c)))
        .collect(toCollection(() -> problems));
  }

  byName.entrySet().stream()
      .filter(e -> e.getValue().size() > 1)
      .map(e -> String.format("Checkpoint of model: %s duplicated by classes: %s",
          e.getKey(), classNames(e.getValue())))
      .collect(toCollection(() -> problems));

  return byName.entrySet().stream()
      .collect(toImmutableBiMap(e -> e.getKey(), e -> e.getValue().get(0)));
}
 
Example 18
@Test
public void testInvalidNormalizedNodeValueType() throws Exception {
    final SchemaContext schemaContext = YangParserTestUtils.parseYangResources(EnumValueXPathFunctionTest.class,
            "/yang-xpath-functions-test/enum-value-function/foo.yang");
    assertNotNull(schemaContext);

    final XPathSchemaContext jaxenSchemaContext = SCHEMA_CONTEXT_FACTORY.createContext(schemaContext);
    final XPathDocument jaxenDocument = jaxenSchemaContext.createDocument(buildMyContainerNode(100));

    final BiMap<String, QNameModule> converterBiMap = HashBiMap.create();
    converterBiMap.put("foo-prefix", FOO_MODULE);

    final NormalizedNodeContextSupport normalizedNodeContextSupport = NormalizedNodeContextSupport.create(
            (JaxenDocument) jaxenDocument, Maps.asConverter(converterBiMap));

    final NormalizedNodeContext normalizedNodeContext = normalizedNodeContextSupport.createContext(
            buildPathToSeverityLeafNode(100));

    final Function enumValueFunction = normalizedNodeContextSupport.getFunctionContext()
            .getFunction(null, null, "enum-value");
    final Double enumValueResult = (Double) enumValueFunction.call(normalizedNodeContext, ImmutableList.of());
    assertEquals(Double.NaN, enumValueResult, 0.001);
}
 
Example 19
Source Project: incubator-pinot   Source File: SqlQueryBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public PreparedStatement createFindByParamsStatement(Connection connection,
    Class<? extends AbstractEntity> entityClass, Predicate predicate) throws Exception {
  String tableName =
      entityMappingHolder.tableToEntityNameMap.inverse().get(entityClass.getSimpleName());
  BiMap<String, String> entityNameToDBNameMapping =
      entityMappingHolder.columnMappingPerTable.get(tableName).inverse();
  StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM " + tableName);
  StringBuilder whereClause = new StringBuilder(" WHERE ");
  List<Pair<String, Object>> parametersList = new ArrayList<>();
  generateWhereClause(entityNameToDBNameMapping, predicate, parametersList, whereClause);
  sqlBuilder.append(whereClause.toString());
  LOG.debug("createFindByParamsStatement Query: {}", sqlBuilder);
  PreparedStatement prepareStatement = connection.prepareStatement(sqlBuilder.toString());
  int parameterIndex = 1;
  LinkedHashMap<String, ColumnInfo> columnInfoMap =
      entityMappingHolder.columnInfoPerTable.get(tableName);
  for (Pair<String, Object> pair : parametersList) {
    String dbFieldName = pair.getKey();
    ColumnInfo info = columnInfoMap.get(dbFieldName);
    Preconditions.checkNotNull(info, String.format("Found field '%s' but expected %s", dbFieldName, columnInfoMap.keySet()));
    prepareStatement.setObject(parameterIndex++, pair.getValue(), info.sqlType);
    LOG.debug("Setting {} to {}", pair.getKey(), pair.getValue());
  }
  return prepareStatement;
}
 
Example 20
Source Project: OpenModsLib   Source File: CommonRegistryCallbacks.java    License: MIT License 5 votes vote down vote up
public static <T, E extends IForgeRegistryEntry<E>> Integer mapObjectToId(IForgeRegistry<E> registry, T object) {
	final Map<T, E> objectToEntryMap = CommonRegistryCallbacks.getObjectToEntryMap(registry);
	final E entry = objectToEntryMap.get(object);

	final BiMap<E, Integer> entryIdMap = CommonRegistryCallbacks.getEntryIdMap(registry);
	return entryIdMap.get(entry);
}
 
Example 21
Source Project: calcite   Source File: MaterializedViewRule.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * It swaps the table references and then the column references of the input
 * expressions using the table mapping and the equivalence classes.
 */
protected NodeLineage generateSwapTableColumnReferencesLineage(
    RexBuilder rexBuilder,
    RelMetadataQuery mq,
    RelNode node,
    BiMap<RelTableRef, RelTableRef> tableMapping,
    EquivalenceClasses ec,
    List<RexNode> nodeExprs) {
  final Map<RexNode, Integer> exprsLineage = new HashMap<>();
  final Map<RexNode, Integer> exprsLineageLosslessCasts = new HashMap<>();
  for (int i = 0; i < nodeExprs.size(); i++) {
    final Set<RexNode> s = mq.getExpressionLineage(node, nodeExprs.get(i));
    if (s == null) {
      // Next expression
      continue;
    }
    // We only support project - filter - join, thus it should map to
    // a single expression
    assert s.size() == 1;
    // Rewrite expr. First we swap the table references following the table
    // mapping, then we take first element from the corresponding equivalence class
    final RexNode e = RexUtil.swapTableColumnReferences(rexBuilder,
        s.iterator().next(), tableMapping, ec.getEquivalenceClassesMap());
    exprsLineage.put(e, i);
    if (RexUtil.isLosslessCast(e)) {
      exprsLineageLosslessCasts.put(((RexCall) e).getOperands().get(0), i);
    }
  }
  return new NodeLineage(exprsLineage, exprsLineageLosslessCasts);
}
 
Example 22
Source Project: vespa   Source File: TenantSerializer.java    License: 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 23
@Test
public void testGetInstanceEndpoints()
    throws InvalidConfigException {
  Set<String> servers = _helixResourceManager.getAllInstancesForServerTenant(SERVER_TENANT_NAME);
  BiMap<String, String> endpoints = _helixResourceManager.getDataInstanceAdminEndpoints(servers);
  for (int i = 0; i < NUM_INSTANCES; i++) {
    Assert.assertTrue(endpoints.inverse().containsKey("localhost:" + (BASE_SERVER_ADMIN_PORT + i)));
  }
}
 
Example 24
Source Project: hadoop   Source File: ShellBasedIdMapping.java    License: Apache License 2.0 5 votes vote down vote up
synchronized private void loadFullGroupMap() throws IOException {
  BiMap<Integer, String> gMap = HashBiMap.create();

  if (OS.startsWith("Mac")) {
    updateMapInternal(gMap, "group", MAC_GET_ALL_GROUPS_CMD, "\\s+",
        staticMapping.gidMapping);
  } else {
    updateMapInternal(gMap, "group", GET_ALL_GROUPS_CMD, ":",
        staticMapping.gidMapping);
  }
  gidNameMap = gMap;
  lastUpdateTime = Time.monotonicNow();
}
 
Example 25
public static BiMap<Class<? extends Entity>, EntityRegistry.EntityRegistration> getEntityClassRegistrations() {
	try {
		return (BiMap<Class<? extends Entity>, EntityRegistry.EntityRegistration>) ENTITYREGISTRY_CLASSREGISTRATIONS.get(EntityRegistry.instance());
	} catch (IllegalArgumentException | IllegalAccessException ex) {
		return null;
	}
}
 
Example 26
Source Project: usergrid   Source File: SubjectUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Set<String> getOrganizationNames() {
    Subject currentUser = getSubject();
    if ( currentUser == null ) {
        return null;
    }
    if ( !currentUser.hasRole( ROLE_ORGANIZATION_ADMIN ) ) {
        return null;
    }
    BiMap<UUID, String> organizations = getOrganizations();
    if ( organizations == null ) {
        return null;
    }
    return organizations.inverse().keySet();
}
 
Example 27
Source Project: FreeBuilder   Source File: CheckedBiMap.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void addTo(SourceBuilder code) {
  code.addLine("")
      .addLine("private static class %s<K, V> extends %s<%s<K, V>> {",
          TYPE, AbstractSet.class, Map.Entry.class)
      .addLine("")
      .addLine("  private final %s<K, V> biMap;", BiMap.class)
      .addLine("  private final %s<%s<K, V>> set;", Set.class, Map.Entry.class)
      .addLine("  private final %s<K, V> forcePut;", BiConsumer.class)
      .addLine("")
      .addLine("  %s(%s<K, V> biMap, %s<K, V> forcePut) {", TYPE, BiMap.class, BiConsumer.class)
      .addLine("    this.biMap = biMap;")
      .addLine("    this.set = biMap.entrySet();")
      .addLine("    this.forcePut = forcePut;")
      .addLine("  }")
      .addLine("")
      .addLine("  @Override public int size() {")
      .addLine("    return set.size();")
      .addLine("  }")
      .addLine("")
      .addLine("  @Override public %s<%s<K, V>> iterator() {",
          Iterator.class, BiMap.Entry.class)
      .addLine("    return new %s<K, V>(biMap, set.iterator(), forcePut);",
          CheckedEntryIterator.TYPE)
      .addLine("  }")
      .addLine("")
      .addLine("  @Override public boolean contains(Object o) {")
      .addLine("    return set.contains(o);")
      .addLine("  }")
      .addLine("")
      .addLine("  @Override public boolean remove(Object o) {")
      .addLine("    return set.remove(o);")
      .addLine("  }")
      .addLine("")
      .addLine("  @Override public void clear() {")
      .addLine("    set.clear();")
      .addLine("  }")
      .addLine("}");
}
 
Example 28
Source Project: tutorials   Source File: GuavaBiMapUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void whenUsingEnumAsKeyInMap_replacesAlreadyPresent() {
    final BiMap<Operation, String> operationStringBiMap = EnumHashBiMap.create(Operation.class);

    operationStringBiMap.put(Operation.ADD, "Add");
    operationStringBiMap.put(Operation.SUBTRACT, "Subtract");
    operationStringBiMap.put(Operation.MULTIPLY, "Multiply");
    operationStringBiMap.put(Operation.DIVIDE, "Divide");

    assertEquals("Divide", operationStringBiMap.get(Operation.DIVIDE));
}
 
Example 29
Source Project: Quicksql   Source File: AbstractMaterializedViewRule.java    License: MIT License 5 votes vote down vote up
/**
 * Rewrites the query using the given view query.
 *
 * <p>The input node is a Scan on the view table and possibly a compensation Filter
 * on top. If a rewriting can be produced, we return that rewriting. If it cannot
 * be produced, we will return null.
 */
protected abstract RelNode rewriteView(RelBuilder relBuilder, RexBuilder rexBuilder,
    RexSimplify simplify, RelMetadataQuery mq, MatchModality matchModality,
    boolean unionRewriting, RelNode input,
    Project topProject, RelNode node,
    Project topViewProject, RelNode viewNode,
    BiMap<RelTableRef, RelTableRef> queryToViewTableMapping,
    EquivalenceClasses queryEC);
 
Example 30
Source Project: usergrid   Source File: SubjectUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static BiMap<UUID, String> getOrganizations() {
    Subject currentUser = getSubject();
    if ( !isOrganizationAdmin() ) {
        return null;
    }
    Session session = currentUser.getSession();
    BiMap<UUID, String> organizations = HashBiMap.create();
    Map map = (Map)session.getAttribute( "organizations" );
    organizations.putAll(map);
    return organizations;
}