Java Code Examples for java.util.Map#of()

The following examples show how to use java.util.Map#of() . 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: FreeIpaV1ControllerTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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));
    });
}
 
Example 2
Source File: ModuleLayer.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * 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
}
 
Example 3
Source File: JsonUtilsTests.java    From gocd-git-path-material-plugin with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 4
Source File: CloudbreakFailedChecker.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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()));
    }
}
 
Example 5
Source File: WarehouseTest.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
@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());
}
 
Example 6
Source File: MapUtilsTest.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
@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)));
}
 
Example 7
Source File: TestPojoSetter.java    From gridgo with MIT License 5 votes vote down vote up
@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));
}
 
Example 8
Source File: ServitorShare.java    From L2jOrg with GNU General Public License v3.0 5 votes vote down vote up
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);
            }
        });
    }
}
 
Example 9
Source File: SingleQueryParameterUtilsTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 10
Source File: MongoDbStepsTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 11
Source File: BattleDisplay.java    From triplea with GNU General Public License v3.0 4 votes vote down vote up
/** 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);
      }
    }
  }
}
 
Example 12
Source File: SearchParamsMapper.java    From frameworkium-examples with Apache License 2.0 4 votes vote down vote up
public static Map<String, String> namesOfBooking(Booking booking) {
    return Map.of(
            "firstname", booking.firstname,
            "lastname", booking.lastname);
}
 
Example 13
Source File: FreeIpaClient.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
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();
}
 
Example 14
Source File: MapFactories.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void nullKeyDisallowed4() {
    Map<Integer, String> map = Map.of(0, "a", 1, "b", 2, "c", null, "d");
}
 
Example 15
Source File: UpgradeOptionsResponseFactoryTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private Map<String, String> createPackageVersions() {
    return Map.of(
            "cm", V_7_0_3,
            "stack", V_7_0_2);
}
 
Example 16
Source File: FreeIpaClient.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example 17
Source File: MapFactories.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@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);
}
 
Example 18
Source File: AuditEventToGrpcAuditEventConverterTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private Map<Class, AuditEventBuilderUpdater> createMockUtilizer(Class clazz) {
    return Map.of(clazz, mockAuditEventBuilderUpdater);
}
 
Example 19
Source File: Web.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 4 votes vote down vote up
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");
}
 
Example 20
Source File: CollectionFactoryMethods.java    From blog-tutorials with MIT License 3 votes vote down vote up
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
}