Example usage for java.util Collections singletonMap

List of usage examples for java.util Collections singletonMap

Introduction

In this page you can find the example usage for java.util Collections singletonMap.

Prototype

public static <K, V> Map<K, V> singletonMap(K key, V value) 

Source Link

Document

Returns an immutable map, mapping only the specified key to the specified value.

Usage

From source file:org.nebulae2us.stardust.example.controller.CommentController.java

@RequestMapping(value = "/comment", method = RequestMethod.GET)
public ModelAndView listComments() {

    List<Comment> comments = commentService.getComments(Immutables.emptyList(Filter.class));

    ModelAndView mav = new ModelAndView("listComments", Collections.singletonMap("comments", comments));

    return mav;/*from  www. ja  v  a  2 s .c  o m*/
}

From source file:edu.sampleu.travel.workflow.TravelAccountRulesEngineExecutor.java

@Override
public EngineResults execute(RouteContext routeContext, Engine engine) {
    Map<String, String> contextQualifiers = new HashMap<String, String>();
    contextQualifiers.put("namespaceCode", CONTEXT_NAMESPACE_CODE);
    contextQualifiers.put("name", CONTEXT_NAME);
    SelectionCriteria sectionCriteria = SelectionCriteria.createCriteria(null, contextQualifiers,
            Collections.singletonMap("Campus", "BL"));

    // extract facts from routeContext
    String docContent = routeContext.getDocument().getDocContent();

    String subsidizedPercentStr = getElementValue(docContent, "//newMaintainableObject//subsidizedPercent");
    String accountTypeCode = getElementValue(docContent,
            "//newMaintainableObject/dataObject/extension/accountTypeCode");
    String initiator = getElementValue(docContent, "//documentInitiator//principalId");

    Facts.Builder factsBuilder = Facts.Builder.create();

    if (StringUtils.isNotEmpty(subsidizedPercentStr)) {
        factsBuilder.addFact("Subsidized Percent", Double.valueOf(subsidizedPercentStr));
    }//  w  ww  . j a  v a 2s.  c om
    factsBuilder.addFact("Account Type Code", accountTypeCode);
    factsBuilder.addFact("Initiator Principal ID", initiator);

    return engine.execute(sectionCriteria, factsBuilder.build(), null);
}

From source file:alfio.manager.system.MailjetMailer.java

@Override
public void send(Event event, String to, List<String> cc, String subject, String text, Optional<String> html,
        Attachment... attachment) {/*from w w w .  j a  v a2  s .c o m*/
    String apiKeyPublic = configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(),
            event.getId(), ConfigurationKeys.MAILJET_APIKEY_PUBLIC));
    String apiKeyPrivate = configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(),
            event.getId(), ConfigurationKeys.MAILJET_APIKEY_PRIVATE));

    String fromEmail = configurationManager.getRequiredValue(
            Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAILJET_FROM));

    //https://dev.mailjet.com/guides/?shell#sending-with-attached-files
    Map<String, Object> mailPayload = new HashMap<>();

    List<Map<String, String>> recipients = new ArrayList<>();
    recipients.add(Collections.singletonMap("Email", to));
    if (cc != null && !cc.isEmpty()) {
        recipients.addAll(cc.stream().map(email -> Collections.singletonMap("Email", email))
                .collect(Collectors.toList()));
    }

    mailPayload.put("FromEmail", fromEmail);
    mailPayload.put("FromName", event.getDisplayName());
    mailPayload.put("Subject", subject);
    mailPayload.put("Text-part", text);
    html.ifPresent(h -> mailPayload.put("Html-part", h));
    mailPayload.put("Recipients", recipients);

    String replyTo = configurationManager.getStringConfigValue(
            Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAIL_REPLY_TO), "");
    if (StringUtils.isNotBlank(replyTo)) {
        mailPayload.put("Headers", Collections.singletonMap("Reply-To", replyTo));
    }

    if (attachment != null && attachment.length > 0) {
        mailPayload.put("Attachments",
                Arrays.stream(attachment).map(MailjetMailer::fromAttachment).collect(Collectors.toList()));
    }

    RequestBody body = RequestBody.create(MediaType.parse("application/json"), Json.GSON.toJson(mailPayload));
    Request request = new Request.Builder().url("https://api.mailjet.com/v3/send")
            .header("Authorization", Credentials.basic(apiKeyPublic, apiKeyPrivate)).post(body).build();
    try (Response resp = client.newCall(request).execute()) {
        if (!resp.isSuccessful()) {
            log.warn("sending email was not successful:" + resp);
        }
    } catch (IOException e) {
        log.warn("error while sending email", e);
    }

}

From source file:com.consol.citrus.admin.connector.WebSocketPushMessageListenerTest.java

@Test
public void testOnInboundMessage() throws Exception {
    Message inbound = new DefaultMessage("Hello Citrus!");

    reset(restTemplate, context);//from   w  ww  . j a v a2 s . c  om
    when(restTemplate.exchange(eq("http://localhost:8080/connector/message/inbound?processId=MySampleTest"),
            eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))).thenAnswer(invocation -> {
                HttpEntity request = (HttpEntity) invocation.getArguments()[2];

                Assert.assertEquals(request.getBody().toString(), inbound.toString());

                return ResponseEntity.ok().build();
            });

    when(context.getVariables())
            .thenReturn(Collections.singletonMap(Citrus.TEST_NAME_VARIABLE, "MySampleTest"));
    when(context.getVariable(Citrus.TEST_NAME_VARIABLE)).thenReturn("MySampleTest");

    pushMessageListener.onInboundMessage(inbound, context);
    verify(restTemplate).exchange(eq("http://localhost:8080/connector/message/inbound?processId=MySampleTest"),
            eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class));
}

From source file:com.cprassoc.solr.auth.security.Sha256AuthenticationProvider.java

public void init(Map<String, Object> pluginConfig) {
    if (pluginConfig.get("realm") != null)
        this.realm = (String) pluginConfig.get("realm");
    else/*from ww  w  . jav  a 2  s  .  com*/
        this.realm = "solr";

    promptHeader = Collections
            .unmodifiableMap(Collections.singletonMap("WWW-Authenticate", "Basic realm=\"" + realm + "\""));
    credentials = new LinkedHashMap<>();
    Map<String, String> users = (Map<String, String>) pluginConfig.get("credentials");
    if (users == null) {
        log.debug("No users configured yet");
        return;
    }
    for (Map.Entry<String, String> e : users.entrySet()) {
        String v = e.getValue();
        if (v == null) {
            log.warn("user has no password " + e.getKey());
            continue;
        }
        credentials.put(e.getKey(), v);
    }

}

From source file:org.jboss.as.test.integration.logging.perdeploy.JBossLog4jXmlTestCase.java

@Test
public void logsTest() throws IOException {
    final String msg = "logTest: jboss-log4j message";
    final int statusCode = getResponse(msg, Collections.singletonMap("includeLevel", "true"));
    assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK);
    boolean trace = false;
    boolean fatal = false;
    String traceLine = msg + " - trace";
    String fatalLine = msg + " - fatal";
    try (final BufferedReader reader = Files.newBufferedReader(logFile, StandardCharsets.UTF_8)) {
        String line;//from   w w w  .j  a va 2 s.c  o m
        while ((line = reader.readLine()) != null) {
            if (line.contains(traceLine)) {
                trace = true;
            }
            if (line.contains(fatalLine)) {
                fatal = true;
            }
        }
    }
    Assert.assertTrue("Log file should contain line: " + traceLine, trace);
    Assert.assertTrue("Log file should contain line: " + fatalLine, fatal);
}

From source file:org.jboss.as.test.integration.logging.perdeploy.LoggingPropertiesTestCase.java

@Test
public void logsTest() throws IOException {
    final String msg = "logTest: logging.properties message";
    final int statusCode = getResponse(msg, Collections.singletonMap("includeLevel", "true"));
    assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK);
    boolean trace = false;
    boolean fatal = false;
    String traceLine = msg + " - trace";
    String fatalLine = msg + " - fatal";
    try (final BufferedReader reader = Files.newBufferedReader(logFile, StandardCharsets.UTF_8)) {
        String line;//  ww  w  . j  a va2s .co  m
        while ((line = reader.readLine()) != null) {
            if (line.contains(traceLine)) {
                trace = true;
            }
            if (line.contains(fatalLine)) {
                fatal = true;
            }
        }
    }
    Assert.assertTrue("Log file should contain line: " + traceLine, trace);
    Assert.assertTrue("Log file should contain line: " + fatalLine, fatal);
}

From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaControllerTests.java

@Test
public void testVanillaPrompts() throws Exception {
    controller.setDefaultTemplate(authorizationTemplate);
    setResponse(//from www.  j  a v  a 2 s.  c o  m
            Collections.<String, Object>singletonMap("prompts",
                    Collections.singletonMap("foo", new Prompt("foo", "text", "Foo").getDetails())),
            null, HttpStatus.OK);
    controller.prompts(request, headers, model, principal);
    assertTrue(model.containsKey("prompts"));
    @SuppressWarnings("rawtypes")
    Map map = (Map) model.get("prompts");
    assertTrue(map.containsKey("foo"));
}

From source file:com.vladmihalcea.HibernateCascadeLockComponentTest.java

@Test
public void test() {

    final Long parentId = cleanAndSaveParent();

    transactionTemplate.execute(new TransactionCallback<Void>() {
        @Override//from  w ww  .  j ava  2  s. c  o  m
        public Void doInTransaction(TransactionStatus transactionStatus) {
            Post post = entityManager.find(Post.class, parentId);
            entityManager.lock(post, LockModeType.PESSIMISTIC_WRITE, Collections
                    .singletonMap("javax.persistence.lock.scope", (Object) PessimisticLockScope.EXTENDED));
            return null;
        }
    });
}

From source file:org.cloudfoundry.identity.uaa.oauth.AccessControllerTests.java

@SuppressWarnings("unchecked")
@Test/*from w  w w.  j  a v  a2s.  com*/
public void testSchemePreserved() throws Exception {
    InMemoryClientDetailsService clientDetailsService = new InMemoryClientDetailsService();
    clientDetailsService.setClientDetailsStore(Collections.singletonMap("client", new BaseClientDetails()));
    controller.setClientDetailsService(clientDetailsService);
    controller.setApprovalStore(Mockito.mock(ApprovalStore.class));
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setScheme("https");
    request.addHeader("Host", "foo");
    ModelMap model = new ModelMap();
    model.put("authorizationRequest", new DefaultAuthorizationRequest("client", null));
    Authentication auth = UaaAuthenticationTestFactory.getAuthentication("foo@bar.com", "Foo Bar",
            "foo@bar.com");
    controller.confirm(model, request, auth, new SimpleSessionStatus());
    Map<String, Object> options = (Map<String, Object>) ((Map<String, Object>) model.get("options"))
            .get("confirm");
    assertEquals("https://foo/oauth/authorize", options.get("location"));
    assertEquals("/oauth/authorize", options.get("path"));
}