Java Code Examples for java.util.Collections#singletonMap()

The following examples show how to use java.util.Collections#singletonMap() . 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: MessageConverter_1_0_to_v0_10Test.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void testAmqpValueWithMapContainingNonFieldTableCompliantEntries() throws Exception
{
    final AmqpValue amqpValue = new AmqpValue(Collections.<Object, Object>singletonMap(13, 42));
    Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection());

    try
    {
        _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
        fail("expected exception not thrown.");
    }
    catch (MessageConversionException e)
    {
        // pass
    }
}
 
Example 2
Source File: JwtAuthenticationProviderTest.java    From auth0-spring-security-api with MIT License 6 votes vote down vote up
@Test
public void shouldFailToAuthenticateUsingJWKIfAudienceClaimDoesNotMatch() throws Exception {
    Jwk jwk = mock(Jwk.class);
    JwkProvider jwkProvider = mock(JwkProvider.class);

    KeyPair keyPair = RSAKeyPair();
    when(jwkProvider.get(eq("key-id"))).thenReturn(jwk);
    when(jwk.getPublicKey()).thenReturn(keyPair.getPublic());
    JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience");
    Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
    String token = JWT.create()
            .withAudience("some-audience")
            .withIssuer("test-issuer")
            .withHeader(keyIdHeader)
            .sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate()));

    Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);

    exception.expect(BadCredentialsException.class);
    exception.expectMessage("Not a valid token");
    exception.expectCause(Matchers.<Throwable>instanceOf(InvalidClaimException.class));
    provider.authenticate(authentication);
}
 
Example 3
Source File: BindingTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void get() throws Exception
{
    Map<String, String> arguments = Collections.singletonMap(AMQPFilterTypes.JMS_SELECTOR.getValue(), "1<2");
    Map<String, Object> bindOperationArguments = new HashMap<>();
    bindOperationArguments.put("destination", "myqueue");
    bindOperationArguments.put("bindingKey", "foo");
    bindOperationArguments.put("arguments", arguments);
    getHelper().submitRequest("exchange/amq.direct/bind",
                              "POST",
                              bindOperationArguments,
                              SC_OK);
    List<Map<String, Object>> bindings = getHelper().getJsonAsList("/api/v6.1/binding/amq.direct/myqueue/foo");
    assertThat(bindings, is(notNullValue()));
    assertThat(bindings.size(), is(equalTo(1)));

    Map<String, Object> binding = bindings.get(0);
    assertThat(binding, is(notNullValue()));
    assertThat(binding.get("name"), is(equalTo("foo")));
    assertThat(binding.get("queue"), is(equalTo("myqueue")));
    assertThat(binding.get("arguments"), is(notNullValue()));

    Object args = binding.get("arguments");
    assertThat(args, is(instanceOf(Map.class)));
    assertThat(args, is(equalTo(arguments)));
}
 
Example 4
Source File: LanguageApiImpl.java    From yandex-translate-api with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Nonnull
@Override
public Languages all(@Nullable final String ui) {
    final Map<String, Object> data = ui == null ? null : Collections.singletonMap(ATTR_UI, ui);
    final LanguagesInfo languagesInfo = callMethod(ImmutableLanguagesInfo.class, METHOD_GET_LANGS, data);

    return LanguagesConverter.INSTANCE.convert(languagesInfo);
}
 
Example 5
Source File: TestRuntimeEstimators.java    From hadoop with Apache License 2.0 5 votes vote down vote up
MyAppContext(int numberMaps, int numberReduces) {
  myApplicationID = ApplicationId.newInstance(clock.getTime(), 1);

  myAppAttemptID = ApplicationAttemptId.newInstance(myApplicationID, 0);
  myJobID = recordFactory.newRecordInstance(JobId.class);
  myJobID.setAppId(myApplicationID);

  Job myJob
      = new MyJobImpl(myJobID, numberMaps, numberReduces);

  allJobs = Collections.singletonMap(myJobID, myJob);
}
 
Example 6
Source File: VariableComparatorFunctionTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Test
public void testGreaterThanOrEquals() {

    Map<String, Object> variables = Collections.singletonMap("myVar", 100);
    VariableContainerWrapper variableContainer = new VariableContainerWrapper(variables);
    assertThat(executeExpression("${variables:greaterThanOrEquals(myVar, 50)}", variableContainer)).isEqualTo(true);
    assertThat(executeExpression("${variables:gte(myVar, 100)}", variableContainer)).isEqualTo(true);

    assertThat(executeExpression("${vars:greaterThanOrEquals(myVar, 150)}", variableContainer)).isEqualTo(false);
    assertThat(executeExpression("${vars:gte(myVar, 100)}", variableContainer)).isEqualTo(true);

    assertThat(executeExpression("${var:greaterThanOrEquals(myVar, 123)}", variableContainer)).isEqualTo(false);
    assertThat(executeExpression("${var:gte(myVar, 100)}", variableContainer)).isEqualTo(true);

    assertThat(executeExpression("${var:greaterThanOrEquals('myVar', 150)}", variableContainer)).isEqualTo(false);
    assertThat(executeExpression("${var:gte('myVar', 100)}", variableContainer)).isEqualTo(true);

    assertThat(executeExpression("${var:greaterThanOrEquals(\"myVar\", 123)}", variableContainer)).isEqualTo(false);
    assertThat(executeExpression("${var:gte(\"myVar\", 100)}", variableContainer)).isEqualTo(true);

    variableContainer = new VariableContainerWrapper(Collections.emptyMap());

    assertThat(executeExpression("${var:greaterThanOrEquals(myVar, 100)}", variableContainer)).isEqualTo(false);
    assertThat(executeExpression("${var:gte(myVar, 150)}", variableContainer)).isEqualTo(false);

    variables = new HashMap<>();
    variables.put("container", new VariableContainerWrapper(Collections.singletonMap("myVar", 100)));
    variables.put("myVar", 500);
    variableContainer = new VariableContainerWrapper(variables);

    assertThat(executeExpression("${var:greaterThanOrEquals(container, 'myVar', 123)}", variableContainer)).isEqualTo(false);
    assertThat(executeExpression("${var:gte(container, 'myVar', 100)}", variableContainer)).isEqualTo(true);

    variables = new HashMap<>();
    variables.put("container", new VariableContainerWrapper(Collections.emptyMap()));
    variableContainer = new VariableContainerWrapper(variables);

    assertThat(executeExpression("${var:greaterThanOrEquals(container, 'myVar', 123)}", variableContainer)).isEqualTo(false);
    assertThat(executeExpression("${var:gte(container, 'myVar', 123)}", variableContainer)).isEqualTo(false);
}
 
Example 7
Source File: ACLTest.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void groupOfGroup() {
  final Map<String, String[]> groups = ImmutableMap.<String, String[]>builder()
      .put("groupOfGroup", new String[]{"@group"})
      .put("group", new String[]{Bob.getUsername()})
      .build();
  final ACL acl = new ACL(groups, Collections.singletonMap("/", Collections.singletonMap("@groupOfGroup", "r")));

  Assert.assertTrue(acl.canRead(Bob, Constants.MASTER, "/"));
  Assert.assertFalse(acl.canRead(User.getAnonymous(), Constants.MASTER, "/"));
}
 
Example 8
Source File: Driver.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private Map<String, TypeAnnotation.Position> expectedOf(TADescription d) {
    String annoName = d.annotation();

    TypeAnnotation.Position p = new TypeAnnotation.Position();
    p.type = d.type();
    if (d.offset() != NOT_SET)
        p.offset = d.offset();
    if (d.lvarOffset().length != 0)
        p.lvarOffset = d.lvarOffset();
    if (d.lvarLength().length != 0)
        p.lvarLength = d.lvarLength();
    if (d.lvarIndex().length != 0)
        p.lvarIndex = d.lvarIndex();
    if (d.boundIndex() != NOT_SET)
        p.bound_index = d.boundIndex();
    if (d.paramIndex() != NOT_SET)
        p.parameter_index = d.paramIndex();
    if (d.typeIndex() != NOT_SET)
        p.type_index = d.typeIndex();
    if (d.exceptionIndex() != NOT_SET)
        p.exception_index = d.exceptionIndex();
    if (d.genericLocation().length != 0) {
        p.location = TypeAnnotation.Position.getTypePathFromBinary(wrapIntArray(d.genericLocation()));
    }

    return Collections.singletonMap(annoName, p);
}
 
Example 9
Source File: JobExecutionResultHandlerTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
	final TestingRestfulGateway testingRestfulGateway = TestingRestfulGateway.newBuilder().build();

	jobExecutionResultHandler = new JobExecutionResultHandler(
		() -> CompletableFuture.completedFuture(testingRestfulGateway),
		Time.seconds(10),
		Collections.emptyMap());

	testRequest = new HandlerRequest<>(
		EmptyRequestBody.getInstance(),
		new JobMessageParameters(),
		Collections.singletonMap("jobid", TEST_JOB_ID.toString()),
		Collections.emptyMap());
}
 
Example 10
Source File: HardcodedClientStorageProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, ClientScopeModel> getClientScopes(boolean defaultScope, boolean filterByProtocol) {
    if (defaultScope) {
        ClientScopeModel rolesScope = KeycloakModelUtils.getClientScopeByName(realm, OIDCLoginProtocolFactory.ROLES_SCOPE);
        ClientScopeModel webOriginsScope = KeycloakModelUtils.getClientScopeByName(realm, OIDCLoginProtocolFactory.WEB_ORIGINS_SCOPE);
        return Arrays.asList(rolesScope, webOriginsScope)
                .stream()
                .collect(Collectors.toMap(ClientScopeModel::getName, clientScope -> clientScope));

    } else {
        ClientScopeModel offlineScope = KeycloakModelUtils.getClientScopeByName(realm, "offline_access");
        return Collections.singletonMap("offline_access", offlineScope);
    }
}
 
Example 11
Source File: JavaLoopTest.java    From jd-core with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testJdk170While() throws Exception {
    String internalClassName = "org/jd/core/test/While";
    InputStream is = this.getClass().getResourceAsStream("/zip/data-java-jdk-1.7.0.zip");
    Loader loader = new ZipLoader(is);
    Map<String, Object> configuration = Collections.singletonMap("realignLineNumbers", Boolean.TRUE);
    String source = decompile(loader, new PlainTextPrinter(), internalClassName, configuration);

    // Check decompiled source code
    assertTrue(source.matches(PatternMaker.make(":  15 */", "while (i-- > 0)")));
    assertTrue(source.matches(PatternMaker.make(":  23 */", "while (i < 10)")));
    assertTrue(source.matches(PatternMaker.make(":  42 */", "while (i0 > 20)")));
    assertTrue(source.matches(PatternMaker.make("/* 113:   0 */", "continue;")));
    assertTrue(source.matches(PatternMaker.make("/* 128:   0 */", "break;")));
    assertTrue(source.matches(PatternMaker.make("/* 158:   0 */", "while (true)")));
    assertTrue(source.matches(PatternMaker.make(": 232 */", "while (++i < 10)")));
    assertTrue(source.indexOf("while (i == 4 && i == 5 && i == 6)") != -1);
    assertTrue(source.indexOf("while ((i == 1 || (i == 5 && i == 6 && i == 7) || i == 8 || (i == 9 && i == 10 && i == 11)) && (i == 4 || i % 200 > 50) && (i > 3 || i > 4))") != -1);
    assertTrue(source.indexOf("while ((i == 1 && (i == 5 || i == 6 || i == 7) && i == 8 && (i == 9 || i == 10 || i == 11)) || (i == 4 && i % 200 > 50) || (i > 3 && i > 4))") != -1);
    assertFalse(source.matches(PatternMaker.make("[ 348:   0 */", "default:")));
    assertFalse(source.matches(PatternMaker.make("[ 350: 348 */", "continue;")));
    assertTrue(source.matches(PatternMaker.make("/* 404: 404 */", "System.out.println(\"a\");")));
    assertTrue(source.matches(PatternMaker.make("/* 431: 431 */", "System.out.println(\"a\");")));

    // Recompile decompiled source code and check errors
    assertTrue(CompilerUtil.compile("1.7", new JavaSourceFileObject(internalClassName, source)));
}
 
Example 12
Source File: TestObject.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void testMapObject_highway() {
  Map<String, Object> map = Collections.singletonMap("k", "v");
  Map<String, Object> result = intf.testMapObject(map);
  TestMgr.check("{k=v}", result);
  // This is a behavior change in 2.0.0, before 2.0.0 runtime type of RAW is HashMap
  TestMgr.check(LinkedHashMap.class, result.getClass());

  result = restTemplate.postForObject(prefix + "/mapObject", map, Map.class);
  TestMgr.check("{k=v}", result);
  TestMgr.check(LinkedHashMap.class, result.getClass());
}
 
Example 13
Source File: StatusService.java    From galeb with Apache License 2.0 5 votes vote down vote up
public Map<Long, Status> status(AbstractEntity entity) {
	if (entity instanceof Environment) {
		boolean exists = changesService.hasByEnvironmentId(entity.getId());
		return Collections.singletonMap(entity.getId(), exists ? Status.PENDING : Status.OK);
	}
	final Set<Environment> allEnvironments = entity.getAllEnvironments();
	if (allEnvironments == null || allEnvironments.isEmpty()) {
		if (!(entity instanceof Rule)) {
			LOGGER.error(entity.getClass().getSimpleName() + " ID " + entity.getId() + " is INCONSISTENT. allEnvironments is NULL or Empty");
		}
		return Collections.emptyMap();
    }
    final Boolean isQuarantine;
    if ((isQuarantine = entity.isQuarantine()) != null && isQuarantine) {
        return allEnvironments.stream().collect(Collectors.toMap(Environment::getId, e -> Status.DELETED));
    }
    if (entity instanceof Target && targetHasEnvUnregistered((Target) entity, allEnvironments)) {
        return allEnvironments.stream().collect(Collectors.toMap(Environment::getId, e -> Status.PENDING));
    }
    Set<Long> allEnvironmentsWithChanges = changesService.listEnvironmentIds(entity);
    Set<Long> allEnvironmentIdsEntity = allEnvironments.stream().map(Environment::getId).collect(Collectors.toSet());
    allEnvironmentIdsEntity.removeAll(allEnvironmentsWithChanges);

    Map<Long, Status> mapStatus = new HashMap<>();
    allEnvironmentIdsEntity.forEach(e -> mapStatus.put(e, Status.OK));
    allEnvironmentsWithChanges.forEach(e -> mapStatus.put(e, Status.PENDING));

    return mapStatus;
}
 
Example 14
Source File: RedirectViewTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void singleParamWithoutExposingModelAttributes() throws Exception {
	String url = "http://url.somewhere.com";
	Map<String, String> model = Collections.singletonMap("foo", "bar");

	TestRedirectView rv = new TestRedirectView(url, false, model);
	rv.setExposeModelAttributes(false);
	rv.render(model, request, response);

	assertEquals(url, this.response.getRedirectedUrl());
}
 
Example 15
Source File: QuotePreservingCookieJar.java    From td-ameritrade-client with Apache License 2.0 5 votes vote down vote up
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
    if (cookieHandler != null) {
        List<String> cookieStrings = new ArrayList<>();
        for (Cookie cookie : cookies) {
            cookieStrings.add(cookie.toString().replaceAll("; domain=", "; domain=."));
        }
        Map<String, List<String>> multimap = Collections.singletonMap("Set-Cookie", cookieStrings);
        try {
            cookieHandler.put(url.uri(), multimap);
        } catch (IOException e) {
            Platform.get().log(WARN, "Saving cookies failed for " + url.resolve("/..."), e);
        }
    }
}
 
Example 16
Source File: CronSchedulerImplTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test(timeout = 2000)
public void testAddRemoveScheduler() throws InterruptedException {
    Semaphore s = new Semaphore(0);
    CronJob cronJob = m -> s.release();
    Map<String, Object> map = Collections.singletonMap(CronJob.CRON, "* * * * * *");
    cronScheduler.addSchedule(cronJob, map);
    s.acquire();
    cronScheduler.removeSchedule(cronJob);
}
 
Example 17
Source File: JavaLoopTest.java    From jd-core with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void testJdk170For() throws Exception {
    String internalClassName = "org/jd/core/test/For";
    InputStream is = this.getClass().getResourceAsStream("/zip/data-java-jdk-1.7.0.zip");
    Loader loader = new ZipLoader(is);
    Map<String, Object> configuration = Collections.singletonMap("realignLineNumbers", Boolean.TRUE);
    String source = decompile(loader, new PlainTextPrinter(), internalClassName, configuration);

    // Check decompiled source code
    assertTrue(source.matches(PatternMaker.make(":  20 */", "for (int i = 0; i < 10; i++)")));
    assertTrue(source.matches(PatternMaker.make(":  42 */", "int i = 0;")));
    assertTrue(source.matches(PatternMaker.make(":  44 */", "for (; i < 10; i++)")));
    assertTrue(source.matches(PatternMaker.make(":  54 */", "for (; i < 10; i++)")));
    assertTrue(source.matches(PatternMaker.make(":  64 */", "for (int i = 0;; i++)")));
    assertTrue(source.matches(PatternMaker.make(":  72 */", "for (;; i++)")));
    assertTrue(source.matches(PatternMaker.make(":  80 */", "for (int i = 0; i < 10;)")));
    assertTrue(source.matches(PatternMaker.make(":  88 */", "while (i < 10)")));
    assertTrue(source.matches(PatternMaker.make(":  96 */", "int i = 0;")));
    assertTrue(source.matches(PatternMaker.make("/* 104:   0 */", "while (true)")));
    assertTrue(source.matches(PatternMaker.make(": 112 */", "for (int i = 0, j = i, size = 10; i < size; j += ++i)")));
    assertTrue(source.matches(PatternMaker.make(": 122 */", "int i = 0, j = i, size = 10;")));
    assertTrue(source.matches(PatternMaker.make(": 123 */", "for (; i < size;")));
    assertTrue(source.matches(PatternMaker.make(": 124 */", "j += ++i)")));
    assertTrue(source.matches(PatternMaker.make(": 134 */", "int i = 0;")));
    assertTrue(source.matches(PatternMaker.make(": 135 */", "int j = i;")));
    assertTrue(source.matches(PatternMaker.make(": 136 */", "int size = 10;")));
    assertTrue(source.matches(PatternMaker.make(": 137 */", "for (; i < size;")));
    assertTrue(source.matches(PatternMaker.make(": 138 */", "i++,")));
    assertTrue(source.matches(PatternMaker.make(": 139 */", "j += i)")));
    assertTrue(source.matches(PatternMaker.make(": 149 */", "int i = 0;")));
    assertTrue(source.matches(PatternMaker.make(": 151 */", "int j = i;")));
    assertTrue(source.matches(PatternMaker.make(": 153 */", "int size = 10;")));
    assertTrue(source.matches(PatternMaker.make(": 155 */", "for (; i < size;")));
    assertTrue(source.matches(PatternMaker.make(": 157 */", "i++,")));
    assertTrue(source.matches(PatternMaker.make(": 159 */", "j += i)")));
    assertTrue(source.matches(PatternMaker.make(": 169 */", "for (int i = 0; i < 10; i++);")));
    assertTrue(source.matches(PatternMaker.make(": 177 */", "for (; i < 10; i++);")));
    assertTrue(source.matches(PatternMaker.make(": 185 */", "for (int i = 0;; i++);")));
    assertTrue(source.matches(PatternMaker.make("/* 190:   0 */", "while (true)")));
    assertTrue(source.matches(PatternMaker.make(": 191 */", "i++;")));
    assertTrue(source.matches(PatternMaker.make(": 197 */", "for (int i = 0; i < 10;);")));
    assertTrue(source.matches(PatternMaker.make(": 203 */", "for (int[] i = { 0 }; i.length < 10;);")));
    assertTrue(source.matches(PatternMaker.make(": 209 */", "for (int i = 0, j = i, k = i; i < 10;);")));
    assertTrue(source.matches(PatternMaker.make(": 215 */", "for (int[] i = { 0 }, j = i, k = j; i.length < 10;);")));
    assertTrue(source.matches(PatternMaker.make(": 221 */", "for (int i = 0, j[] = { 1 }; i < 10;);")));
    assertTrue(source.matches(PatternMaker.make(": 227 */", "while (i < 10);")));
    assertTrue(source.matches(PatternMaker.make(": 233 */", "int i = 0;")));
    assertTrue(source.matches(PatternMaker.make("/* 234:   0 */", "while (true);")));
    assertTrue(source.matches(PatternMaker.make(": 245 */", "for (int i = 0, j = i, size = 10; i < size; j += ++i);")));
    assertTrue(source.matches(PatternMaker.make("/* 253:   0 */", "while (true) {")));
    assertTrue(source.matches(PatternMaker.make(": 264 */", "for (String s : list)")));
    assertTrue(source.matches(PatternMaker.make(": 310 */", "for (int j : new int[] { 4 })")));
    assertTrue(source.matches(PatternMaker.make(": 389 */", "for (String s : array)")));
    assertTrue(source.matches(PatternMaker.make(": 403 */", "for (String s : list)")));
    assertTrue(source.matches(PatternMaker.make(": 411 */", "Iterator<Class<?>> iterator = Arrays.<Class<?>>asList(getClass().getInterfaces()).iterator()")));

    assertTrue(source.indexOf("/* 524: 524 */") != -1);

    // Recompile decompiled source code and check errors
    assertTrue(CompilerUtil.compile("1.7", new JavaSourceFileObject(internalClassName, source)));
}
 
Example 18
Source File: PeopleController.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@GetMapping("/{name}")
ModelAndView showPersonForm(@PathVariable("name") PersonEntity person) {

	return new ModelAndView("personForm", Collections.singletonMap("person", person));
}
 
Example 19
Source File: java_util_Collections_SingletonMap.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
protected Map<String, String> getObject() {
    return Collections.singletonMap("key", "value");
}
 
Example 20
Source File: CayenneExpMergerTest.java    From agrest with Apache License 2.0 4 votes vote down vote up
@Test(expected = AgException.class)
public void testMerge_Params_InvalidPath() {
    CayenneExp exp = new CayenneExp("invalid/path=$b", Collections.singletonMap("b", false));
    merger.merge(entity, exp);
}