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.apache.solr.client.solrj.impl.CloudSolrClientCacheTest.java

public void testCaching() throws Exception {
    String collName = "gettingstarted";
    Set<String> livenodes = new HashSet<>();
    Map<String, ClusterState.CollectionRef> refs = new HashMap<>();
    Map<String, DocCollection> colls = new HashMap<>();

    class Ref extends ClusterState.CollectionRef {
        private String c;

        public Ref(String c) {
            super(null);
            this.c = c;
        }/* w  w  w.  ja va2 s .  c om*/

        @Override
        public boolean isLazilyLoaded() {
            return true;
        }

        @Override
        public DocCollection get() {
            gets.incrementAndGet();
            return colls.get(c);
        }
    }
    Map<String, Function> responses = new HashMap<>();
    NamedList okResponse = new NamedList();
    okResponse.add("responseHeader", new NamedList<>(Collections.singletonMap("status", 0)));

    LBHttpSolrClient mockLbclient = getMockLbHttpSolrClient(responses);
    AtomicInteger lbhttpRequestCount = new AtomicInteger();
    try (CloudSolrClient cloudClient = new CloudSolrClientBuilder(getStateProvider(livenodes, refs))
            .withLBHttpSolrClient(mockLbclient).build()) {
        livenodes.addAll(ImmutableSet.of("192.168.1.108:7574_solr", "192.168.1.108:8983_solr"));
        ClusterState cs = ClusterState.load(1, coll1State.getBytes(UTF_8), Collections.emptySet(),
                "/collections/gettingstarted/state.json");
        refs.put(collName, new Ref(collName));
        colls.put(collName, cs.getCollectionOrNull(collName));
        responses.put("request", o -> {
            int i = lbhttpRequestCount.incrementAndGet();
            if (i == 1)
                return new ConnectException("TEST");
            if (i == 2)
                return new SocketException("TEST");
            if (i == 3)
                return new NoHttpResponseException("TEST");
            return okResponse;
        });
        UpdateRequest update = new UpdateRequest().add("id", "123", "desc", "Something 0");

        cloudClient.request(update, collName);
        assertEquals(2, refs.get(collName).getCount());
    }

}

From source file:com.whizzosoftware.hobson.twilio.TwilioSMSAction.java

@Override
public void executeAction(PropertyContainer pc) {
    logger.info("Sending to " + pc.getPropertyValue("phoneNumber") + ": " + pc.getPropertyValue("message"));

    try {//from  w ww . j  a va2 s. c om
        String auth = accountSid + ":" + authToken;
        StringBuilder data = new StringBuilder("To=")
                .append(URLEncoder.encode(pc.getStringPropertyValue("phoneNumber"), "UTF8")).append("&From=")
                .append(URLEncoder.encode(phoneNumber, "UTF8")).append("&Body=")
                .append(URLEncoder.encode(pc.getStringPropertyValue("message"), "UTF8"));

        plugin.sendHttpRequest(
                new URI("https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/Messages.json"),
                HttpRequest.Method.POST,
                Collections.singletonMap("Authorization",
                        "Basic " + Base64.encodeBase64String(auth.getBytes())),
                null, data.toString().getBytes(), null);
    } catch (Exception e) {
        logger.error("Error sending SMS", e);
    }
}

From source file:com.thoughtworks.go.remote.work.PluggableArtifactMetadataTest.java

@Test
public void shouldWriteMetadataFile() throws IOException {
    final PluggableArtifactMetadata pluggableArtifactMetadata = new PluggableArtifactMetadata();

    pluggableArtifactMetadata.addMetadata("cd.go.docker-registry", "centos",
            Collections.singletonMap("image", "centos"));
    pluggableArtifactMetadata.addMetadata("cd.go.docker-registry", "alpine",
            Collections.singletonMap("image", "alpine"));

    final File workingDirectory = tempFolder.newFolder("pluggable-metadata-folder");
    pluggableArtifactMetadata.write(workingDirectory);

    final File jsonFile = new File(workingDirectory.listFiles()[0], "cd.go.docker-registry.json");
    final String fileContent = FileUtils.readFileToString(jsonFile, StandardCharsets.UTF_8);

    assertThat(fileContent, is("{\"alpine\":{\"image\":\"alpine\"},\"centos\":{\"image\":\"centos\"}}"));
}

From source file:com.graphaware.server.CommunityTxParticipationIntegrationTest.java

@Test
public void moduleApiShouldParticipateInOpenTransaction() throws IOException {
    //First transaction over Cypher transactional rest endpoint, keep open:
    String response = httpClient.post(baseNeoUrl() + "/db/data/transaction",
            "{\n" + "  \"statements\" : [ {\n"
                    + "    \"statement\" : \"CREATE (p:Person {props}) RETURN id(p)\",\n"
                    + "    \"parameters\" : {\n" + "      \"props\" : {\n" + "        \"name\" : \"Michal\"\n"
                    + "      }\n" + "    }\n" + "  } ]\n" + "}",
            HttpStatus.SC_CREATED);//from   ww w.j av a  2s.com

    String commitUrl = new ObjectMapper().readTree(response).get("commit").asText();
    String txUrl = commitUrl.substring(0, commitUrl.length() - "commit".length());

    //Second transaction over Cypher transactional rest endpoint, keep open:
    httpClient.post(txUrl,
            "{\n" + "  \"statements\" : [ {\n"
                    + "    \"statement\" : \"CREATE (p:Person {props}) RETURN id(p)\",\n"
                    + "    \"parameters\" : {\n" + "      \"props\" : {\n" + "        \"name\" : \"Daniela\"\n"
                    + "      }\n" + "    }\n" + "  } ]\n" + "}",
            HttpStatus.SC_OK);

    //Third transaction over REST to an extension
    httpClient.post(baseUrl() + "/link/0/1", null, Collections.singletonMap("_GA_TX_ID", "1"),
            HttpStatus.SC_CREATED);

    //Commit transaction over transactional endpoint
    httpClient.post(commitUrl, HttpStatus.SC_OK);

    //todo re-enable when resttest is compatible again
    //        httpClient.post(baseUrl() + "/graphaware/resttest/assertSameGraph", "{\"cypher\": \"CREATE (m:Person {name:'Michal'})-[:TEST]->(d:Person {name:'Daniela'})\"}", HttpStatus.SC_OK);
}

From source file:org.elasticsearch.multi_node.GlobalCheckpointSyncActionIT.java

public void testGlobalCheckpointSyncActionRunsAsPrivilegedUser() throws Exception {
    // create the test-index index
    try (XContentBuilder builder = jsonBuilder()) {
        builder.startObject();//from   w w w .  java2 s  .c  o  m
        {
            builder.startObject("settings");
            {
                builder.field("index.number_of_shards", 1);
                builder.field("index.number_of_replicas", 1);
            }
            builder.endObject();
        }
        builder.endObject();
        final StringEntity entity = new StringEntity(Strings.toString(builder), ContentType.APPLICATION_JSON);
        client().performRequest("PUT", "test-index", Collections.emptyMap(), entity);
    }

    // wait for the replica to recover
    client().performRequest("GET", "/_cluster/health", Collections.singletonMap("wait_for_status", "green"));

    // index some documents
    final int numberOfDocuments = randomIntBetween(0, 128);
    for (int i = 0; i < numberOfDocuments; i++) {
        try (XContentBuilder builder = jsonBuilder()) {
            builder.startObject();
            {
                builder.field("foo", i);
            }
            builder.endObject();
            final StringEntity entity = new StringEntity(Strings.toString(builder),
                    ContentType.APPLICATION_JSON);
            client().performRequest("PUT", "/test-index/test-type/" + i, Collections.emptyMap(), entity);
        }
    }

    // we have to wait for the post-operation global checkpoint sync to propagate to the replica
    assertBusy(() -> {
        final Map<String, String> params = new HashMap<>(2);
        params.put("level", "shards");
        params.put("filter_path", "**.seq_no");
        final Response response = client().performRequest("GET", "/test-index/_stats", params);
        final ObjectPath path = ObjectPath.createFromResponse(response);
        // int looks funny here since global checkpoints are longs but the response parser does not know enough to treat them as long
        final int shard0GlobalCheckpoint = path
                .evaluate("indices.test-index.shards.0.0.seq_no.global_checkpoint");
        assertThat(shard0GlobalCheckpoint, equalTo(numberOfDocuments - 1));
        final int shard1GlobalCheckpoint = path
                .evaluate("indices.test-index.shards.0.1.seq_no.global_checkpoint");
        assertThat(shard1GlobalCheckpoint, equalTo(numberOfDocuments - 1));
    });
}

From source file:org.elasticsearch.xpack.test.rest.XPackRestTestHelper.java

/**
 * Waits for pending tasks to complete/*  www .j  a  va 2  s .  c o m*/
 */
public static void waitForPendingTasks(RestClient adminClient) throws Exception {
    ESTestCase.assertBusy(() -> {
        try {
            Response response = adminClient.performRequest("GET", "/_cat/tasks",
                    Collections.singletonMap("detailed", "true"));
            // Check to see if there are tasks still active. We exclude the
            // list tasks
            // actions tasks form this otherwise we will always fail
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                try (BufferedReader responseReader = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))) {
                    int activeTasks = 0;
                    String line;
                    StringBuilder tasksListString = new StringBuilder();
                    while ((line = responseReader.readLine()) != null) {
                        if (line.startsWith(ListTasksAction.NAME) == false) {
                            activeTasks++;
                            tasksListString.append(line);
                            tasksListString.append('\n');
                        }
                    }
                    assertEquals(activeTasks + " active tasks found:\n" + tasksListString, 0, activeTasks);
                }
            }
        } catch (IOException e) {
            throw new AssertionError("Error getting active tasks list", e);
        }
    });
}

From source file:de.tntinteractive.portalsammler.engine.MapReaderTest.java

@Test
public void testMultipleMaps() throws Exception {
    final String input = "test123\n" + " \n" + " \n" + ".\n" + "test456\n" + " \n" + " \n" + ".";
    final MapReader r = createReader(input);
    final Pair<String, Map<String, String>> p1 = r.readNext();
    assertEquals("test123", p1.getLeft());
    assertEquals(Collections.singletonMap("", ""), p1.getRight());
    final Pair<String, Map<String, String>> p2 = r.readNext();
    assertEquals("test456", p2.getLeft());
    assertEquals(Collections.singletonMap("", ""), p2.getRight());
    assertNull(r.readNext());//ww w . j  a  va 2  s.c  o m
}

From source file:com.clican.pluto.dataprocess.engine.processes.JdbcProcessor.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void process(ProcessorContext context) throws DataProcessException {
    // ????jdbcExecBean
    for (JdbcExecBean jdbcExecBean : jdbcExecBeanList) {
        String sql = jdbcExecBean.getSql().trim();
        // sql???
        if (StringUtils.isEmpty(sql)) {
            log.warn("The sql is null, we ignore it");
            return;
        }//from   w ww . ja  v  a 2  s.  c o  m
        boolean singleRow = jdbcExecBean.isSingleRow();
        Class<?> clazz = jdbcExecBean.getClazz();
        // select,insert,update,delete
        String command = sql.toLowerCase().substring(0, 6);
        // ?
        Object temp = jdbcExecBean.getParam(context);
        Map<String, Object> param;
        if (temp instanceof Map) {
            param = (Map<String, Object>) temp;
        } else if (StringUtils.isNotEmpty(jdbcExecBean.getParamName())) {
            param = Collections.singletonMap(jdbcExecBean.getParamName(), temp);
        } else {
            throw new DataProcessException("?");
        }
        if (command.equals("select")) {
            List<?> list;
            if (clazz == null) {
                list = jdbcTemplate.queryForList(sql, new MapAndNestedPropertySqlParameterSource(param));
            } else {
                if (clazz.isAssignableFrom(Date.class) || clazz.equals(Long.class)
                        || clazz.equals(Integer.class) || clazz.equals(Float.class)
                        || clazz.equals(Double.class) || clazz.equals(String.class)) {
                    list = jdbcTemplate.query(sql, new MapAndNestedPropertySqlParameterSource(param),
                            new SingleColumnRowMapper(clazz) {

                                protected Object getColumnValue(ResultSet rs, int index, Class requiredType)
                                        throws SQLException {
                                    Object obj = super.getColumnValue(rs, index, requiredType);
                                    if (obj instanceof Date) {
                                        return new Date(((Date) obj).getTime());
                                    } else {
                                        return obj;
                                    }
                                }

                                protected Object getColumnValue(ResultSet rs, int index) throws SQLException {
                                    Object obj = super.getColumnValue(rs, index);
                                    if (obj instanceof Date) {
                                        return new Date(((Date) obj).getTime());
                                    } else {
                                        return obj;
                                    }
                                }

                            });
                } else {
                    list = jdbcTemplate.query(sql, new MapAndNestedPropertySqlParameterSource(param),
                            new BeanPropertyRowMapper(clazz));
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("jdbc set attribute[" + jdbcExecBean.getResultName() + "],size=" + list.size());
            }
            if (singleRow) {
                if (list.size() == 0) {
                    context.setAttribute(jdbcExecBean.getResultName(), null);
                } else if (list.size() == 1) {
                    context.setAttribute(jdbcExecBean.getResultName(), list.get(0));
                } else {
                    throw new DataProcessException("???");
                }
            } else {
                context.setAttribute(jdbcExecBean.getResultName(), list);
            }
        } else if (command.equals("insert") || command.equals("update") || command.equals("delete")
                || command.equals("trunca")) {
            if (sql.contains(";")) {
                String updateSql = sql.split(";")[0];
                String insertSql = sql.split(";")[1];
                int row = jdbcTemplate.update(updateSql, param);
                if (row == 0) {
                    row = jdbcTemplate.update(insertSql, param);
                }
            } else {
                if (jdbcExecBean.isBatch() && temp instanceof List) {
                    List tempList = (List) temp;
                    SqlParameterSource[] sources = new SqlParameterSource[tempList.size()];
                    for (int i = 0; i < tempList.size(); i++) {
                        Object obj = tempList.get(i);
                        SqlParameterSource namedParameters;
                        if (obj instanceof Map) {
                            namedParameters = new MapAndNestedPropertySqlParameterSource((Map) obj);
                        } else {
                            namedParameters = new BeanPropertySqlParameterSource(obj);
                        }
                        sources[i] = namedParameters;
                    }
                    new SimpleJdbcTemplate(jdbcTemplate.getJdbcOperations()).batchUpdate(sql, sources);
                } else {
                    SqlParameterSource namedParameters;
                    if (param instanceof Map) {
                        namedParameters = new MapAndNestedPropertySqlParameterSource((Map) param);
                    } else {
                        namedParameters = new BeanPropertySqlParameterSource(param);
                    }
                    int row = jdbcTemplate.update(sql, namedParameters);
                    if (log.isDebugEnabled()) {
                        log.debug(command + "=" + row + " row");
                    }
                }
            }
        } else {
            throw new DataProcessException("sql");
        }
    }
}

From source file:com.netflix.spinnaker.orca.clouddriver.tasks.pipeline.MigratePipelineClustersTask.java

private List<Map> getSources(Map<String, Object> pipeline) {
    List<Map> stages = (List<Map>) pipeline.getOrDefault("stages", new ArrayList<>());
    return stages.stream().map(s -> {
        Optional<PipelineClusterExtractor> extractor = PipelineClusterExtractor.getExtractor(s, extractors);
        if (extractor.isPresent()) {
            return extractor.get().extractClusters(s).stream().map(c -> Collections.singletonMap("cluster", c))
                    .collect(Collectors.toList());
        }//from   ww  w  .  ja  v  a  2  s  .c  o m
        return new ArrayList<Map>();
    }).flatMap(Collection::stream).collect(Collectors.toList());
}

From source file:com.jwt.exceptions.GlobalExceptionHandler.java

private Map error(Object message) {
    return Collections.singletonMap("response", message);
}