com.google.common.collect.BiMap Java Examples

The following examples show how to use com.google.common.collect.BiMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ObjectRef.java    From nuls with 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 #2
Source File: EnumValueXPathFunctionTest.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
@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 #3
Source File: AbstractMaterializedViewRule.java    From Bats with 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
Source File: UpgradeManager.java    From nexus-public with 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 #5
Source File: SqlQueryBuilder.java    From incubator-pinot with 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 #6
Source File: ModSubstitutions.java    From Gadomancy with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #7
Source File: SubjectUtils.java    From usergrid with 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 #8
Source File: ManagementServiceImpl.java    From usergrid with 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 #9
Source File: AccessibilityHierarchyAndroid.java    From Accessibility-Test-Framework-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #10
Source File: MaterializedViewRule.java    From calcite with 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 #11
Source File: BitIsSetXPathFunctionTest.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
@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 #12
Source File: EnumValueXPathFunctionTest.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
@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 #13
Source File: ReverseMapLookup.java    From levelup-java-examples with 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 #14
Source File: DerivedFromXPathFunctionTest.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
@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 #15
Source File: JsonUtils.java    From nuls-v2 with 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 #16
Source File: ObjectRef.java    From nuls-v2 with 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 #17
Source File: PAM.java    From api-mining with 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 #18
Source File: AccessibilityHierarchyAndroid.java    From Accessibility-Test-Framework-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #19
Source File: AbstractDecompiler.java    From securify with 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 #20
Source File: TestShellBasedIdMapping.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test
public void testDuplicates() throws IOException {
  assumeTrue(!Shell.WINDOWS);
  String GET_ALL_USERS_CMD = "echo \"root:x:0:0:root:/root:/bin/bash\n"
      + "hdfs:x:11501:10787:Grid Distributed File System:/home/hdfs:/bin/bash\n"
      + "hdfs:x:11502:10788:Grid Distributed File System:/home/hdfs:/bin/bash\n"
      + "hdfs1:x:11501:10787:Grid Distributed File System:/home/hdfs:/bin/bash\n"
      + "hdfs2:x:11502:10787:Grid Distributed File System:/home/hdfs:/bin/bash\n"
      + "bin:x:2:2:bin:/bin:/bin/sh\n"
      + "bin:x:1:1:bin:/bin:/sbin/nologin\n"
      + "daemon:x:1:1:daemon:/usr/sbin:/bin/sh\n"
      + "daemon:x:2:2:daemon:/sbin:/sbin/nologin\""
      + " | cut -d: -f1,3";
  String GET_ALL_GROUPS_CMD = "echo \"hdfs:*:11501:hrt_hdfs\n"
      + "mapred:x:497\n"
      + "mapred2:x:497\n"
      + "mapred:x:498\n" 
      + "mapred3:x:498\"" 
      + " | cut -d: -f1,3";
  // Maps for id to name map
  BiMap<Integer, String> uMap = HashBiMap.create();
  BiMap<Integer, String> gMap = HashBiMap.create();

  ShellBasedIdMapping.updateMapInternal(uMap, "user", GET_ALL_USERS_CMD, ":",
      EMPTY_PASS_THROUGH_MAP);
  assertEquals(5, uMap.size());
  assertEquals("root", uMap.get(0));
  assertEquals("hdfs", uMap.get(11501));
  assertEquals("hdfs2",uMap.get(11502));
  assertEquals("bin", uMap.get(2));
  assertEquals("daemon", uMap.get(1));

  ShellBasedIdMapping.updateMapInternal(gMap, "group", GET_ALL_GROUPS_CMD, ":",
      EMPTY_PASS_THROUGH_MAP);
  assertTrue(gMap.size() == 3);
  assertEquals("hdfs",gMap.get(11501));
  assertEquals("mapred", gMap.get(497));
  assertEquals("mapred3", gMap.get(498));
}
 
Example #21
Source File: GuavaBiMapUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenSameValueIsPresent_whenForcePut_completesSuccessfully() {
    final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();

    capitalCountryBiMap.put("New Delhi", "India");
    capitalCountryBiMap.put("Washingon, D.C.", "USA");
    capitalCountryBiMap.put("Moscow", "Russia");
    capitalCountryBiMap.forcePut("Trump", "USA");

    assertEquals("USA", capitalCountryBiMap.get("Trump"));
    assertEquals("Trump", capitalCountryBiMap.inverse().get("USA"));
}
 
Example #22
Source File: KeywordHelper.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private BiMap<CharSequence, String> createKeywordMap(Grammar grammar) {
	List<ParserRule> parserRules = GrammarUtil.allParserRules(grammar);
	List<EnumRule> enumRules = GrammarUtil.allEnumRules(grammar);
	Iterator<EObject> iter = Iterators.concat(
			EcoreUtil.<EObject>getAllContents(parserRules), EcoreUtil.<EObject>getAllContents(enumRules));
	Iterator<Keyword> filtered = Iterators.filter(iter, Keyword.class);
	Iterator<String> transformed = Iterators.transform(filtered, new Function<Keyword, String>() {
		@Override
		public String apply(Keyword from) {
			return from.getValue();
		}
	});
	TreeSet<String> treeSet = Sets.newTreeSet(new Comparator<String>() {
		@Override
		public int compare(String o1, String o2) {
			if (o1.length() == o2.length())
				return o1.compareTo(o2);
			return Integer.valueOf(o1.length()).compareTo(Integer.valueOf(o2.length()));
		}
	});
	Iterators.addAll(treeSet, transformed);
	BiMap<CharSequence, String> result = HashBiMap.create();
	for(String s: treeSet) {
		CharSequence key = createKey(s);
		String readableName = toAntlrTokenIdentifier(s);
		if (result.containsValue(readableName)) {
			int i = 1;
			String next = readableName + "_" + i;
			while(result.containsValue(next)) {
				i++;
				next = readableName + "_" + i;
			}
			readableName = next;
		}
		result.put(key, readableName);
	}
	return result;
}
 
Example #23
Source File: GqlInputConverter.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
private static BiMap<String, EnumDescriptor> getEnumMap(Iterable<EnumDescriptor> descriptors) {
  HashBiMap<String, EnumDescriptor> mapping = HashBiMap.create();
  for (EnumDescriptor enumDescriptor : descriptors) {
    mapping.put(ProtoToGql.getReferenceName(enumDescriptor), enumDescriptor);
  }
  return mapping;
}
 
Example #24
Source File: DMMDiff.java    From FastDMM with GNU General Public License v3.0 5 votes vote down vote up
public ExpandKeysDiff(DMM dmm, Map<Location, String> oldMap, Map<Location, String> newMap,
		BiMap<String, TileInstance> oldInstances, BiMap<String, TileInstance> newInstances,
		List<String> oldUnusedKeys, List<String> newUnusedKeys,
		int oldKeyLen, int newKeyLen) {
	super(dmm);
	this.oldMap = oldMap;
	this.newMap = newMap;
	this.oldInstances = oldInstances;
	this.newInstances = newInstances;
	this.oldKeyLen = oldKeyLen;
	this.newKeyLen = newKeyLen;
}
 
Example #25
Source File: OrganizationResource.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Path(RootResource.APPLICATION_ID_PATH)
public ApplicationResource getApplicationById( @PathParam("applicationId") String applicationIdStr )
        throws Exception {

    if ( "options".equalsIgnoreCase( request.getMethod() ) ) {
        throw new NoOpException();
    }

    UUID applicationId = UUID.fromString( applicationIdStr );
    if ( applicationId == null ) {
        return null;
    }

    OrganizationInfo org_info = management.getOrganizationByName( organizationName );
    UUID organizationId = null;
    if ( org_info != null ) {
        organizationId = org_info.getUuid();
    }
    if (organizationId == null) {
        return null;
    }

    // don't look up app if request is a PUT because a PUT can be used to restore a deleted app
    if ( httpServletRequest.getMethod().equalsIgnoreCase("PUT") ) {

        BiMap<UUID, String> apps = management.getApplicationsForOrganization(organizationId);
        if (apps.get(applicationId) == null) {
            return null;
        }
    }

    return appResourceFor( applicationId );
}
 
Example #26
Source File: BiMapProperty.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
private static TypeMirror biMap(
    TypeMirror keyType,
    TypeMirror valueType,
    Elements elements,
    Types types) {
  TypeElement mapType = elements.getTypeElement(BiMap.class.getName());
  return types.getDeclaredType(mapType, keyType, valueType);
}
 
Example #27
Source File: BiMapMutateMethodTest.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
@Test
public void canUseCustomFunctionalInterface() {
  SourceBuilder customMutatorType = SourceBuilder.forTesting();
  for (String line : bimapPropertyType.toString().split("\n")) {
    if (line.contains("extends DataType_Builder")) {
      int insertIndex = line.indexOf('{') + 1;
      customMutatorType
          .addLine("%s", line.substring(0, insertIndex))
          .addLine("    public interface Mutator {")
          .addLine("      void mutate(%s<%s, %s> multiBiMap);",
              BiMap.class, keys.type(), values.type())
          .addLine("    }")
          .addLine("    @Override public Builder mutateItems(Mutator mutator) {")
          .addLine("      return super.mutateItems(mutator);")
          .addLine("    }")
          .addLine("%s", line.substring(insertIndex));
    } else {
      customMutatorType.addLine("%s", line);
    }
  }

  behaviorTester
      .with(customMutatorType)
      .with(testBuilder()
          .addLine("DataType value = new DataType.Builder()")
          .addLine("    .putItems(%s, %s)", keys.example(0), values.example(0))
          .addLine("    .mutateItems(items -> items.put(%s, %s))",
              keys.example(1), values.example(1))
          .addLine("    .build();")
          .addLine("assertThat(value.%s).isEqualTo(%s);",
              convention.get(), exampleBiMap(0, 0, 1, 1))
          .build())
      .runTest();
}
 
Example #28
Source File: MappingProviderSrg.java    From Mixin with MIT License 5 votes vote down vote up
@Override
public void read(final File input) throws IOException {
    // Locally scoped to avoid synthetic accessor
    final BiMap<String, String> packageMap = this.packageMap;
    final BiMap<String, String> classMap = this.classMap;
    final BiMap<MappingField, MappingField> fieldMap = this.fieldMap;
    final BiMap<MappingMethod, MappingMethod> methodMap = this.methodMap;

    Files.readLines(input, Charset.defaultCharset(), new LineProcessor<String>() {
        @Override
        public String getResult() {
            return null;
        }
        
        @Override
        public boolean processLine(String line) throws IOException {
            if (Strings.isNullOrEmpty(line) || line.startsWith("#")) {
                return true;
            }

            String type = line.substring(0, 2);
            String[] args = line.substring(4).split(" ");

            if (type.equals("PK")) {
                packageMap.forcePut(args[0], args[1]);
            } else if (type.equals("CL")) {
                classMap.forcePut(args[0], args[1]);
            } else if (type.equals("FD")) {
                fieldMap.forcePut(new MappingFieldSrg(args[0]).copy(), new MappingFieldSrg(args[1]).copy());
            } else if (type.equals("MD")) {
                methodMap.forcePut(new MappingMethod(args[0], args[1]), new MappingMethod(args[2], args[3]));
            } else {
                throw new MixinException("Invalid SRG file: " + input);
            }
            
            return true;
        }
    });
}
 
Example #29
Source File: ClusteringModelEvaluator.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public BiMap<String, Cluster> getEntityRegistry(){

	if(this.entityRegistry == null){
		this.entityRegistry = getValue(ClusteringModelEvaluator.entityCache);
	}

	return this.entityRegistry;
}
 
Example #30
Source File: CommonRegistryCallbacks.java    From OpenModsLib with 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);
}