java.util.Map#of ( )源码实例Demo

下面列出了java.util.Map#of ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Bytecoder   文件: ModuleLayer.java
/**
 * Creates a new module layer from the modules in the given configuration.
 */
private ModuleLayer(Configuration cf,
                    List<ModuleLayer> parents,
                    Function<String, ClassLoader> clf)
{
    this.cf = cf;
    this.parents = parents; // no need to do defensive copy

    Map<String, Module> map;
    if (parents.isEmpty()) {
        map = Map.of();
    } else {
        map = Module.defineModules(cf, clf, this);
    }
    this.nameToModule = map; // no need to do defensive copy
}
 
@Test
public void shouldReturnGitConfigWithShallowClone() throws IOException {
    final Map<String, Object> configurationMap = Map.of(
            "url", new ConfigurationItem("http://localhost.com"),
            "username", new ConfigurationItem("user"),
            "password", new ConfigurationItem("pass"),
            "shallow_clone", new ConfigurationItem("true")
    );

    GitConfig config = JsonUtils.toAgentGitConfig(mockApiRequestFor(configurationMap));

    assertThat(config.getUrl(), is("http://localhost.com"));
    assertThat(config.getUsername(), is("user"));
    assertThat(config.getPassword(), is("pass"));
    assertThat(config.getEffectiveBranch(), is("master"));
    assertThat(config.isRecursiveSubModuleUpdate(), is(true));
    assertThat(config.isShallowClone(), is(true));
}
 
源代码3 项目: cloudbreak   文件: CloudbreakFailedChecker.java
@Override
public void handleTimeout(T waitObject) {
    String name = waitObject.getName();
    try {
        StackStatusV4Response stackStatus = waitObject.getStackEndpoint().getStatusByName(waitObject.getWorkspaceId(), name);
        Map<String, Status> actualStatuses = Map.of("status", stackStatus.getStatus(), "clusterStatus", stackStatus.getClusterStatus());
        Map<String, String> actualStatusReasons = Map.of("stackStatusReason", stackStatus.getStatusReason(), "clusterStatusReason", stackStatus
                .getClusterStatusReason());
        throw new TestFailException(String.format("Wait operation timed out, '%s' cluster has not been failed. Cluster status: '%s' " +
                "statusReason: '%s'", name, actualStatuses, actualStatusReasons));
    } catch (Exception e) {
        LOGGER.error("Wait operation timed out, failed to get cluster status: {}", e.getMessage(), e);
        throw new TestFailException(String.format("Wait operation timed out, failed to get cluster status: %s",
                e.getMessage()));
    }
}
 
源代码4 项目: cloudbreak   文件: FreeIpaV1ControllerTest.java
@Test
void createRequestDomainPattern() {
    final Pattern domainPattern = Pattern.compile(FreeIpaServerBase.DOMAIN_MATCHER);
    Map<String, Boolean> domainTestSequences = Map.of(
            "domain", Boolean.FALSE,
            ".domain", Boolean.FALSE,
            "local.domain", Boolean.TRUE,
            "123.domain", Boolean.TRUE,
            "local-123.domain", Boolean.TRUE,
            "local-123.domain.com", Boolean.TRUE,
            "local.domain?", Boolean.FALSE
    );
    domainTestSequences.forEach((domain, expectation) -> {
        Matcher domainMatcher = domainPattern.matcher(domain);
        assertEquals(expectation, domainMatcher.matches(), String.format("testing %s", domain));
    });
}
 
@Test
void canPlaceCorrectOrder() throws Exception {
    // given
    Collection<Order> ordersBefore = warehouse.getOrders();
    int customerId = 12;
    var quantities = Map.of(2, 1);

    // when
    warehouse.addOrder(customerId, quantities);

    // then
    Collection<Order> ordersAfter = warehouse.getOrders();
    assertEquals(ordersBefore.size() + 1, ordersAfter.size());
}
 
源代码6 项目: vividus   文件: MongoDbStepsTests.java
@Test
public void testExecuteCommandNoConnection()
{
    MongoDbSteps steps = new MongoDbSteps(Map.of(), jsonUtils, context);
    Exception exception = assertThrows(IllegalStateException.class,
        () -> steps.executeCommand(COMMAND, LOCAL_KEY, LOCAL_KEY, Set.of(VariableScope.STORY), VARIABLE_KEY));
    assertEquals("Connection with key 'localKey' does not exist", exception.getMessage());
}
 
源代码7 项目: teku   文件: SingleQueryParameterUtilsTest.java
@Test
public void getParameterAsBLSSignature_shouldParseBytes96Data() {
  BLSSignature signature = new BLSSignature(Bytes.random(96));
  Map<String, List<String>> data = Map.of(KEY, List.of(signature.toHexString()));
  BLSSignature result = getParameterValueAsBLSSignature(data, KEY);
  assertEquals(signature, result);
}
 
源代码8 项目: L2jOrg   文件: ServitorShare.java
private ServitorShare(StatsSet params) {
    if(params.contains("type")) {
        sharedStats = Map.of(params.getEnum("type", Stat.class), params.getFloat("power") / 100);
    } else {
        sharedStats = new HashMap<>();
        params.getSet().forEach((key, value) -> {
            if(key.startsWith("stat")) {
                var set = (StatsSet) value;
                sharedStats.put(set.getEnum("type", Stat.class), set.getFloat("power") / 100);
            }
        });
    }
}
 
源代码9 项目: gridgo   文件: TestPojoSetter.java
@Test
public void testNestedList() {
    var nestedList = List.of(List.of("s1", "s2"), List.of("s3"));
    var src = Map.of("nestedList", nestedList);
    var obj = createPojo(src);
    assertEquals(2, obj.getNestedList().size());
    assertArrayEquals(new String[] {"s1", "s2"}, obj.getNestedList().get(0));
    assertArrayEquals(new String[] {"s3"}, obj.getNestedList().get(1));
}
 
源代码10 项目: Shadbot   文件: MapUtilsTest.java
@Test
public void testSort() {
    final Map<String, Integer> expected = Map.of("1", 1, "2", 2, "3", 3);
    final Map<String, Integer> unsorted = Map.of("2", 2, "1", 1, "3", 3);
    final Map<String, Integer> singleton = Map.of("3", 3);
    final Map<String, Integer> empty = new HashMap<>();
    assertEquals(expected, MapUtils.sort(unsorted, Comparator.comparingInt(Map.Entry::getValue)));
    assertEquals(empty, MapUtils.sort(empty, Comparator.comparingInt(Map.Entry::getValue)));
    assertEquals(singleton, MapUtils.sort(singleton, Comparator.comparingInt(Map.Entry::getValue)));
}
 
private Object handleProducts(Request req, Response res) throws WarehouseException {
    Map<String, Object> model = Map.of(
        "title", "Manage products",
        "products", warehouse.getProducts());
    return render(model, "templates/products.html.vm");
}
 
源代码12 项目: triplea   文件: BattleDisplay.java
/** refresh the model from units. */
void refresh() {
  // TODO Soft set the maximum bonus to-hit plus 1 for 0 based count(+2 total currently)
  // Soft code the # of columns

  final List<List<TableData>> columns = new ArrayList<>(gameData.getDiceSides() + 1);
  for (int i = 0; i <= gameData.getDiceSides(); i++) {
    columns.add(i, new ArrayList<>());
  }
  final List<Unit> units = new ArrayList<>(this.units);
  DiceRoll.sortByStrength(units, !attack);
  final Map<Unit, TotalPowerAndTotalRolls> unitPowerAndRollsMap;
  final boolean isAirPreBattleOrPreRaid = battleType.isAirPreBattleOrPreRaid();
  if (isAirPreBattleOrPreRaid) {
    unitPowerAndRollsMap = Map.of();
  } else {
    gameData.acquireReadLock();
    try {
      unitPowerAndRollsMap =
          DiceRoll.getUnitPowerAndRollsForNormalBattles(
              units,
              new ArrayList<>(enemyBattleModel.getUnits()),
              units,
              !attack,
              gameData,
              location,
              territoryEffects,
              isAmphibious,
              amphibiousLandAttackers);
    } finally {
      gameData.releaseReadLock();
    }
  }
  final int diceSides = gameData.getDiceSides();
  final Collection<UnitCategory> unitCategories =
      UnitSeparator.categorize(units, null, false, false, false);
  for (final UnitCategory category : unitCategories) {
    int strength;
    final UnitAttachment attachment = UnitAttachment.get(category.getType());
    final int[] shift = new int[gameData.getDiceSides() + 1];
    for (final Unit current : category.getUnits()) {
      if (isAirPreBattleOrPreRaid) {
        if (attack) {
          strength = attachment.getAirAttack(category.getOwner());
        } else {
          strength = attachment.getAirDefense(category.getOwner());
        }
      } else {
        // normal battle
        strength = unitPowerAndRollsMap.get(current).getTotalPower();
      }
      strength = Math.min(Math.max(strength, 0), diceSides);
      shift[strength]++;
    }
    for (int i = 0; i <= gameData.getDiceSides(); i++) {
      if (shift[i] > 0) {
        columns
            .get(i)
            .add(
                new TableData(
                    category.getOwner(),
                    shift[i],
                    category.getType(),
                    category.hasDamageOrBombingUnitDamage(),
                    category.getDisabled(),
                    uiContext));
      }
    }
    // TODO Kev determine if we need to identify if the unit is hit/disabled
  }
  // find the number of rows
  // this will be the size of the largest column
  int rowCount = 1;
  for (final List<TableData> column : columns) {
    rowCount = Math.max(rowCount, column.size());
  }
  setNumRows(rowCount);
  for (int row = 0; row < rowCount; row++) {
    for (int column = 0; column < columns.size(); column++) {
      // if the column has that many items, add to the table, else add null
      if (columns.get(column).size() > row) {
        setValueAt(columns.get(column).get(row), row, column);
      } else {
        setValueAt(TableData.NULL, row, column);
      }
    }
  }
}
 
源代码13 项目: frameworkium-examples   文件: SearchParamsMapper.java
public static Map<String, String> namesOfBooking(Booking booking) {
    return Map.of(
            "firstname", booking.firstname,
            "lastname", booking.lastname);
}
 
源代码14 项目: cloudbreak   文件: FreeIpaClient.java
public Host showHost(String fqdn) throws FreeIpaClientException {
    List<Object> flags = List.of(fqdn);
    Map<String, Object> params = Map.of();
    return (Host) invoke("host_show", flags, params, Host.class).getResult();
}
 
源代码15 项目: openjdk-jdk9   文件: MapFactories.java
@Test(expectedExceptions=NullPointerException.class)
public void nullKeyDisallowed4() {
    Map<Integer, String> map = Map.of(0, "a", 1, "b", 2, "c", null, "d");
}
 
private Map<String, String> createPackageVersions() {
    return Map.of(
            "cm", V_7_0_3,
            "stack", V_7_0_2);
}
 
源代码17 项目: cloudbreak   文件: FreeIpaClient.java
public void allowServiceKeytabRetrieval(String canonicalPrincipal, String user) throws FreeIpaClientException {
    List<Object> flags = List.of(canonicalPrincipal);
    Map<String, Object> params = Map.of("user", user);
    invoke("service_allow_retrieve_keytab", flags, params, Service.class);
}
 
源代码18 项目: openjdk-jdk9   文件: MapFactories.java
@Test(expectedExceptions=NullPointerException.class)
public void nullValueDisallowed10() {
    Map<Integer, String> map = Map.of(0, "a", 1, "b", 2, "c", 3, "d", 4, "e",
                                      5, "f", 6, "g", 7, "h", 8, "i", 9, null);
}
 
private Map<Class, AuditEventBuilderUpdater> createMockUtilizer(Class clazz) {
    return Map.of(clazz, mockAuditEventBuilderUpdater);
}
 
源代码20 项目: blog-tutorials   文件: CollectionFactoryMethods.java
public static void main(String[] args) {
	final List<String> names = List.of("Mike", "Duke", "Paul");

	final Map<Integer, String> user = Map.of(1, "Mike", 2, "Duke");
	final Map<Integer, String> admins = Map.ofEntries(Map.entry(1, "Tom"), Map.entry(2, "Paul"));

	final Set<String> server = Set.of("WildFly", "Open Liberty", "Payara", "TomEE");

	// names.add("Tom"); throws java.lang.UnsupportedOperationException -> unmodifiable collection is created
}