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:ch.cyberduck.ui.cocoa.DuplicateFileController.java

/**
 * @param source      The original file to duplicate
 * @param destination The destination of the duplicated file
 *///from w w  w .j  ava 2 s  .  com
public void duplicate(final Path source, final Path destination) {
    this.duplicate(Collections.singletonMap(source, destination));
}

From source file:org.apache.niolex.config.ctrl.GroupController.java

@RequestMapping(value = "/{groupName:.+}/{key}", method = RequestMethod.GET)
public @ResponseBody Map<String, ? extends Object> findItem(@PathVariable String groupName,
        @PathVariable String key, Model model, HttpServletRequest req) {
    CenterConnector cc = ConnectorUtil.getConnector(req);
    String s = null;// ww  w . ja  v a 2 s  .  co  m
    try {
        s = cc.getItem(groupName, key);
    } catch (Exception e) {
        LOG.error("Error occured when get item.", e);
        s = ERR;
    }
    return Collections.singletonMap("msg", s);
}

From source file:com.espertech.esper.regression.client.TestAudit.java

public void testDocSample() {
    epService.getEPAdministrator().createEPL("create schema OrderEvent(price double)");

    String epl = "@Name('All-Order-Events') @Audit('stream,property') select price from OrderEvent";
    epService.getEPAdministrator().createEPL(epl).addListener(listener);

    if (EventRepresentationEnum.getEngineDefault(epService).isObjectArrayEvent()) {
        epService.getEPRuntime().sendEvent(new Object[] { 100d }, "OrderEvent");
    } else {/*from  w ww .j a  v a 2  s  . c  o  m*/
        epService.getEPRuntime().sendEvent(Collections.singletonMap("price", 100d), "OrderEvent");
    }
}

From source file:com.hyphenated.card.controller.PlayerController.java

/**
 * Have a new player join a game.//w w  w. jav a  2 s  . c  o m
 * @param gameId unique ID for the game to be joined
 * @param playerName player name
 * @return Map representing the JSON String of the new player's unique id.  The playerId will
 * be used for that player's actions in future requests.  Example: {"playerId":xxx}
 */
@RequestMapping("/join")
public @ResponseBody Map<String, String> joinGame(@RequestParam long gameId, @RequestParam String playerName) {
    Game game = gameService.getGameById(gameId, false);
    Player player = new Player();
    player.setName(playerName);
    player = gameService.addNewPlayerToGame(game, player);
    return Collections.singletonMap("playerId", player.getId());
}

From source file:com.mongodb.hadoop.examples.wordcount.split.WordCountSplitTest.java

@Override
public int run(String[] args) throws Exception {
    final Configuration conf = getConf();
    boolean useQuery = false;
    for (int i = 0; i < args.length; i++) {
        final String argi = args[i];
        if (argi.equals("--use-query"))
            useQuery = true;//from   ww w . j av a 2  s .  c o  m
        else {
            throw new IllegalArgumentException(argi);
        }
    }

    if (useQuery) {
        //NOTE: must do this BEFORE Job is created
        final MongoConfig mongo_conf = new MongoConfig(conf);
        com.mongodb.BasicDBObject query = new com.mongodb.BasicDBObject();
        query.put("num", new com.mongodb.BasicDBObject(Collections.singletonMap("$mod", new int[] { 2, 0 })));
        System.out.println(" --- setting query on num");
        mongo_conf.setQuery(query);
        System.out.println(" --- query is: " + mongo_conf.getQuery());
    }

    final com.mongodb.MongoURI outputUri = MongoConfigUtil.getOutputURI(conf);
    if (outputUri == null)
        throw new IllegalStateException("output uri is not set");
    if (MongoConfigUtil.getInputURI(conf) == null)
        throw new IllegalStateException("input uri is not set");
    final String outputCollectionName = outputUri.getCollection();

    final Job job = new Job(conf, "word count " + outputCollectionName);

    job.setJarByClass(WordCountSplitTest.class);

    job.setMapperClass(TokenizerMapper.class);

    job.setCombinerClass(IntSumReducer.class);
    job.setReducerClass(IntSumReducer.class);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);

    job.setInputFormatClass(MongoInputFormat.class);
    job.setOutputFormatClass(MongoOutputFormat.class);

    final long start = System.currentTimeMillis();
    System.out
            .println(" ----------------------- running test " + outputCollectionName + " --------------------");
    try {
        boolean result = job.waitForCompletion(true);
        System.out.println("job.waitForCompletion( true ) returned " + result);
    } catch (Exception e) {
        System.err.println("job.waitForCompletion( true ) threw Exception");
        e.printStackTrace();
        return 1;
    }
    final long end = System.currentTimeMillis();
    final float seconds = ((float) (end - start)) / 1000;
    java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
    nf.setMaximumFractionDigits(3);
    System.out.println("finished run in " + nf.format(seconds) + " seconds");

    com.mongodb.Mongo m = new com.mongodb.Mongo(outputUri);
    com.mongodb.DB db = m.getDB(outputUri.getDatabase());
    com.mongodb.DBCollection coll = db.getCollection(outputCollectionName);
    com.mongodb.BasicDBObject query = new com.mongodb.BasicDBObject();
    query.put("_id", "the");
    com.mongodb.DBCursor cur = coll.find(query);
    if (!cur.hasNext())
        System.out.println("FAILURE: could not find count of \'the\'");
    else
        System.out.println("'the' count: " + cur.next());

    return 0; //is the return value supposed to be the program exit code?

    //        if (! result)
    //           System.exit(  1 );
}

From source file:com.sun.socialsite.web.filters.ThreadContextFilter.java

/**
 * Release SocialSite persistence session at end of request processing.
 *///www  . ja va 2  s . c  om
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    log.debug("Entered ThreadContextFilter");

    SocialSite socialsite = Factory.getSocialSite();

    log.debug(String.format("url=%s decoder=%s st=%s", request.getRequestURL(), decoder,
            request.getParameter("st")));
    if ((decoder != null) && (request.getParameter("st") != null)) {
        Map<String, String> m = Collections.singletonMap(SecurityTokenDecoder.SECURITY_TOKEN_NAME,
                request.getParameter("st"));
        try {
            final SocialSiteToken token = (SocialSiteToken) (decoder.createToken(m));
            log.debug(String.format("url=%s token=%s", request.getRequestURL(), token));
            if ((token != null) && (!socialsite.getURLStrategy().equals(token.getURLStrategy()))) {
                Object overrider = new Object() {
                    public URLStrategy getURLStrategy() {
                        log.debug(String.format("url=%s token=%s urlstrategy=%s", request.getRequestURL(),
                                token, token.getURLStrategy()));
                        return token.getURLStrategy();
                    }
                };
                SocialSite ss = (SocialSite) (ProxyUtil.getOverrideProxy(socialsite, overrider));
                log.debug(String.format("url=%s ss=%s", request.getRequestURL(), ss));
                Factory.setThreadLocalSocialSite(
                        (SocialSite) (ProxyUtil.getOverrideProxy(socialsite, overrider)));
                log.debug(String.format("url=%s Factory.getSocialSite=%s", request.getRequestURL(),
                        Factory.getSocialSite()));
            }
        } catch (SecurityTokenException e) {
            log.error("Failed to get security token", e);
        }
    }

    try {
        chain.doFilter(request, response);
    } finally {
        log.debug("Releasing SocialSite Session");
        if (Factory.isBootstrapped()) {
            Factory.setThreadLocalSocialSite(null);
            Factory.getSocialSite().release();
        }
    }

    log.debug("Exiting ThreadContextFilter");
}

From source file:com.opentable.logging.KafkaAppenderTest.java

@Test(timeout = 10000)
public void testLog() throws Exception {
    AdminUtils.createTopic(kafka.getServer().zkClient(), "logs", 1, 1, new Properties());
    Thread.sleep(2000);//from   w w  w .  ja  va  2  s  .  co  m
    context.getLogger("test").info("Herro!");
    context.getLogger("womp").warn("flop", new Throwable());

    // Ensure we flush our buffers
    context.stop();

    final CommonLogFields log1, log2;

    ConsumerConnector consumer = createConsumer();

    final List<KafkaStream<byte[], byte[]>> streams = consumer
            .createMessageStreams(Collections.singletonMap("logs", 1)).get("logs");
    final KafkaStream<byte[], byte[]> stream = Iterables.getOnlyElement(streams);
    final ConsumerIterator<byte[], byte[]> iterator = stream.iterator();

    System.out.println("read 0");
    log1 = read(iterator.next().message());
    System.out.println("read 1");
    log2 = read(iterator.next().message());
    System.out.println("read 2");

    consumer.shutdown();

    assertEquals("Herro!", log1.getMessage());
    assertEquals("test", log1.getLogClass());
    assertEquals("INFO", log1.getSeverity());

    assertEquals("flop", log2.getMessage());
    assertEquals("womp", log2.getLogClass());
    assertEquals("WARN", log2.getSeverity());
}

From source file:org.apereo.services.persondir.support.AttributeBasedCacheKeyGeneratorTest.java

@Test
public void testCacheKeyGeneratorWithFactoryBean() {

    final IPersonAttributeDao personAttributeDao = applicationContext.getBean("personAttributeDao",
            IPersonAttributeDao.class);

    final MapCacheProviderFacade cacheProviderFacade = applicationContext.getBean("cacheProviderFacade",
            MapCacheProviderFacade.class);

    assertEquals(0, cacheProviderFacade.getCacheSize());
    assertEquals(0, cacheProviderFacade.getFlushCount());
    assertEquals(0, cacheProviderFacade.getHitCount());
    assertEquals(0, cacheProviderFacade.getMissCount());
    assertEquals(0, cacheProviderFacade.getPutCount());
    assertEquals(0, cacheProviderFacade.getRemoveCount());

    //Should be a miss
    personAttributeDao.getMultivaluedUserAttributes("edalquist");
    assertEquals(1, cacheProviderFacade.getCacheSize());
    assertEquals(0, cacheProviderFacade.getFlushCount());
    assertEquals(0, cacheProviderFacade.getHitCount());
    assertEquals(1, cacheProviderFacade.getMissCount());
    assertEquals(1, cacheProviderFacade.getPutCount());
    assertEquals(0, cacheProviderFacade.getRemoveCount());

    //Should be a hit
    personAttributeDao.getMultivaluedUserAttributes("edalquist");
    assertEquals(1, cacheProviderFacade.getCacheSize());
    assertEquals(0, cacheProviderFacade.getFlushCount());
    assertEquals(1, cacheProviderFacade.getHitCount());
    assertEquals(1, cacheProviderFacade.getMissCount());
    assertEquals(1, cacheProviderFacade.getPutCount());
    assertEquals(0, cacheProviderFacade.getRemoveCount());

    //Should be a hit
    personAttributeDao.getMultivaluedUserAttributes(
            Collections.singletonMap("userName", Collections.singletonList((Object) "edalquist")));
    assertEquals(1, cacheProviderFacade.getCacheSize());
    assertEquals(0, cacheProviderFacade.getFlushCount());
    assertEquals(2, cacheProviderFacade.getHitCount());
    assertEquals(1, cacheProviderFacade.getMissCount());
    assertEquals(1, cacheProviderFacade.getPutCount());
    assertEquals(0, cacheProviderFacade.getRemoveCount());

    //Should be a miss
    personAttributeDao.getUserAttributes("edalquist");
    assertEquals(2, cacheProviderFacade.getCacheSize());
    assertEquals(0, cacheProviderFacade.getFlushCount());
    assertEquals(2, cacheProviderFacade.getHitCount());
    assertEquals(2, cacheProviderFacade.getMissCount());
    assertEquals(2, cacheProviderFacade.getPutCount());
    assertEquals(0, cacheProviderFacade.getRemoveCount());

    //Should be a hit
    personAttributeDao.getUserAttributes("edalquist");
    assertEquals(2, cacheProviderFacade.getCacheSize());
    assertEquals(0, cacheProviderFacade.getFlushCount());
    assertEquals(3, cacheProviderFacade.getHitCount());
    assertEquals(2, cacheProviderFacade.getMissCount());
    assertEquals(2, cacheProviderFacade.getPutCount());
    assertEquals(0, cacheProviderFacade.getRemoveCount());

    //Should be a hit
    personAttributeDao.getUserAttributes(Collections.singletonMap("userName", (Object) "edalquist"));
    assertEquals(2, cacheProviderFacade.getCacheSize());
    assertEquals(0, cacheProviderFacade.getFlushCount());
    assertEquals(4, cacheProviderFacade.getHitCount());
    assertEquals(2, cacheProviderFacade.getMissCount());
    assertEquals(2, cacheProviderFacade.getPutCount());
    assertEquals(0, cacheProviderFacade.getRemoveCount());

    //Should miss
    personAttributeDao.getPossibleUserAttributeNames();
    assertEquals(3, cacheProviderFacade.getCacheSize());
    assertEquals(0, cacheProviderFacade.getFlushCount());
    assertEquals(4, cacheProviderFacade.getHitCount());
    assertEquals(3, cacheProviderFacade.getMissCount());
    assertEquals(3, cacheProviderFacade.getPutCount());
    assertEquals(0, cacheProviderFacade.getRemoveCount());

    //Should hit/* w  ww  . j  a  v  a  2s . c  o  m*/
    personAttributeDao.getPossibleUserAttributeNames();
    assertEquals(3, cacheProviderFacade.getCacheSize());
    assertEquals(0, cacheProviderFacade.getFlushCount());
    assertEquals(5, cacheProviderFacade.getHitCount());
    assertEquals(3, cacheProviderFacade.getMissCount());
    assertEquals(3, cacheProviderFacade.getPutCount());
    assertEquals(0, cacheProviderFacade.getRemoveCount());
}

From source file:org.suren.autotest.web.framework.selenium.action.SeleniumJqGridSequenceOperation.java

/**
 * @param absEle/*from w w w .j  a  v  a 2 s  .  c  o  m*/
 */
private Button buildOperationBut(AbstractElement absEle) {
    Map<String, String> map = Collections.singletonMap(absEle.getDataStr(OPER_BUT_BY),
            absEle.getDataStr(OPER_BUT_INFO));
    map.put("strategy", "priority");

    LocatorUtil.setLocator(map, operationBut);

    return operationBut;
}

From source file:org.commonjava.aprox.depgraph.rest.GraphController.java

public String errors(final String gav, final String workspaceId) throws AproxWorkflowException {
    final ViewParams params = new ViewParams(workspaceId);
    ProjectVersionRef ref = null;/*from  ww w.j a v a  2s.co  m*/
    try {
        if (gav != null) {
            ref = projectVersion(gav);
        }

        Map<ProjectVersionRef, String> errors;
        if (ref != null) {
            logger.debug("Retrieving project errors in graph: {}", ref);
            errors = Collections.singletonMap(ref, ops.getProjectError(ref, params));
        } else {
            logger.debug("Retrieving ALL project errors");
            errors = ops.getAllProjectErrors(params);
        }

        return errors == null ? null : serializer.writeValueAsString(errors);
    } catch (final CartoDataException e) {
        throw new AproxWorkflowException("Failed to lookup resolution errors for: {}. Reason: {}", e,
                ref == null ? "all projects" : ref, e.getMessage());
    } catch (final JsonProcessingException e) {
        throw new AproxWorkflowException("Failed to serialize to JSON. Reason: %s", e, e.getMessage());
    }

}