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:com.hyphenated.card.controller.GameController.java

/**
 * Create a new game based on the parameters from the URL Request
 * <br /><br />/*  w w  w .ja va2 s. c  om*/
 * The standard URL Request to the path /create with two parameters, like:
 * pokerserverurl.com/create?gameName=MyPokerGame&gameStructure=TWO_HR_SEVENPPL
 * <br /><br />
 * Use the Spring to leverage the Enum type conversions. Return JSON response
 * with one value, gameId.
 * @param gameName Name to identify this game
 * @param gameStructure Type of the game that will be played
 * @return {"gameId":xxxx}.  The Java Method returns the Map<String,Long> which is converted
 * by Spring to the JSON object.
 */
@RequestMapping(value = "/create")
public @ResponseBody Map<String, Long> createGame(@RequestParam String gameName,
        @RequestParam CommonTournamentFormats gameStructure) {
    Game game = new Game();
    game.setName(gameName);
    game.setGameType(GameType.TOURNAMENT); //Until Cash games are supported
    GameStructure gs = new GameStructure();
    gs.setBlindLength(gameStructure.getTimeInMinutes());
    gs.setBlindLevels(gameStructure.getBlindLevels());
    gs.setStartingChips(gameStructure.getStartingChips());
    game.setGameStructure(gs);
    game = gameService.saveGame(game);

    return Collections.singletonMap("gameId", game.getId());
}

From source file:com.smartitengineering.cms.spi.impl.content.RubyGeneratorTest.java

@Test
public void testRubyRepGeneration() throws IOException {
    TypeRepresentationGenerator generator = new RubyRepresentationGenerator();
    final RepresentationTemplate template = mockery.mock(RepresentationTemplate.class);
    WorkspaceAPIImpl impl = new WorkspaceAPIImpl() {

        @Override/* ww w.  j  a  v a 2  s  .c  o m*/
        public RepresentationTemplate getRepresentationTemplate(WorkspaceId id, String name) {
            return template;
        }
    };
    impl.setRepresentationGenerators(Collections.singletonMap(TemplateType.RUBY, generator));
    RepresentationProvider provider = new RepresentationProviderImpl();
    final WorkspaceAPI api = impl;
    registerBeanFactory(api);
    final Content content = mockery.mock(Content.class);
    final Field field = mockery.mock(Field.class);
    final FieldValue value = mockery.mock(FieldValue.class);
    final ContentType type = mockery.mock(ContentType.class);
    final Map<String, RepresentationDef> reps = mockery.mock(Map.class, "repMap");
    final RepresentationDef def = mockery.mock(RepresentationDef.class);
    final Map<String, Field> fieldMap = mockery.mock(Map.class);
    mockery.checking(new Expectations() {

        {
            exactly(1).of(template).getTemplateType();
            will(returnValue(TemplateType.RUBY));
            exactly(1).of(template).getTemplate();
            will(returnValue(IOUtils.toByteArray(
                    getClass().getClassLoader().getResourceAsStream("scripts/ruby/test-script.rb"))));
            exactly(1).of(template).getName();
            will(returnValue(REP_NAME));
            exactly(1).of(value).getValue();
            will(returnValue(CONTENT));
            exactly(1).of(field).getValue();
            will(returnValue(value));
            exactly(1).of(fieldMap).get(with(Expectations.<String>anything()));
            will(returnValue(field));
            exactly(1).of(content).getFields();
            will(returnValue(fieldMap));
            exactly(1).of(content).getContentDefinition();
            will(returnValue(type));
            final ContentId contentId = mockery.mock(ContentId.class);
            exactly(2).of(content).getContentId();
            will(returnValue(contentId));
            final WorkspaceId wId = mockery.mock(WorkspaceId.class);
            exactly(1).of(contentId).getWorkspaceId();
            will(returnValue(wId));
            exactly(2).of(type).getRepresentationDefs();
            will(returnValue(reps));
            exactly(2).of(reps).get(with(REP_NAME));
            will(returnValue(def));
            exactly(1).of(def).getParameters();
            will(returnValue(Collections.emptyMap()));
            exactly(1).of(def).getMIMEType();
            will(returnValue(GroovyGeneratorTest.MIME_TYPE));
            final ResourceUri rUri = mockery.mock(ResourceUri.class);
            exactly(1).of(def).getResourceUri();
            will(returnValue(rUri));
            exactly(1).of(rUri).getValue();
            will(returnValue("iUri"));
        }
    });
    Representation representation = provider.getRepresentation(REP_NAME, type, content);
    Assert.assertEquals(REP_NAME, representation.getName());
    Assert.assertEquals(CONTENT, StringUtils.newStringUtf8(representation.getRepresentation()));
    Assert.assertEquals(GroovyGeneratorTest.MIME_TYPE, representation.getMimeType());
}

From source file:de.interactive_instruments.etf.testdriver.te.TeTestTask.java

@Override
protected void doRun() throws Exception {
    final DocumentBuilderFactory domFactory = XmlUtils.newDocumentBuilderFactoryInstance();
    domFactory.setNamespaceAware(true);//from   w w w .  j a  v  a 2  s . co m
    final DocumentBuilder builder = domFactory.newDocumentBuilder();

    final String endpoint = this.testTaskDto.getTestObject().getResourceByName("serviceEndpoint").toString();

    // TEAM engine can not escape characters other than '&' in the parameter values...
    // Try to build an URI without escaping other characters.
    URI apiUri;
    String wfsUrl;
    try {
        wfsUrl = UriUtils.ensureUrlEncodedOnce(endpoint);
        final String apiUrl = testTaskDto.getExecutableTestSuite().getRemoteResource().toString() + "run?wfs="
                + wfsUrl;
        apiUri = new URI(apiUrl);
    } catch (URISyntaxException syntaxException) {
        // great, try again with an escaped URL. Maybe this is supported in future TE versions...
        final String apiUriFallback = UriUtils.withQueryParameters(
                testTaskDto.getExecutableTestSuite().getRemoteResource().toString() + "run",
                Collections.singletonMap("wfs", endpoint));
        getLogger().error(
                "Team Engine does not support full escaping of URLs. "
                        + "The invocation of the following URL might fail with HTTP error code 404: {} .",
                apiUriFallback);
        wfsUrl = endpoint;
        apiUri = new URI(apiUriFallback);
    }

    getLogger().info(
            "Invoking TEAM Engine remotely. This may take a while. " + "Progress messages are not supported.");
    final String timeoutStr = TimeUtils.milisAsMinsSeconds(timeout);
    getLogger().info("Timeout is set to: " + timeoutStr);
    ((TeTestTaskProgress) progress).stepCompleted();

    final Document result;
    try {
        // application/xml = TestNG
        result = builder.parse(UriUtils.openStream(apiUri, credentials, timeout, "application/xml"));
    } catch (UriUtils.ConnectionException e) {
        getLogger().info("OGC TEAM Engine returned an error.");

        final String htmlErrorMessage = e.getErrorMessage();
        String errorMessage = null;
        if (htmlErrorMessage != null) {
            try {
                final org.jsoup.nodes.Document doc = Jsoup.parse(htmlErrorMessage);
                if (doc != null) {
                    final Elements errors = doc.select("body p");
                    if (errors != null) {
                        final StringBuilder errorMessageBuilder = new StringBuilder();
                        for (final org.jsoup.nodes.Element error : errors) {
                            errorMessageBuilder.append(error.text()).append(SUtils.ENDL);
                        }
                        errorMessage = errorMessageBuilder.toString();
                    }
                }
            } catch (Exception ign) {
                ExcUtils.suppress(ign);
            }
        }
        if (errorMessage != null) {
            getLogger().error("Error message: {}", errorMessage);
            reportError(
                    "OGC TEAM Engine returned HTTP status code: "
                            + String.valueOf(e.getResponseMessage() + ". Message: " + errorMessage),
                    htmlErrorMessage.getBytes(), "text/html");
        } else {
            getLogger().error("Response message: " + e.getResponseMessage());
            reportError("OGC TEAM Engine returned an error: " + String.valueOf(e.getResponseMessage()), null,
                    null);
        }
        throw e;
    } catch (final SocketTimeoutException e) {
        getLogger().info("The OGC TEAM Engine is taking too long to respond.");
        getLogger().info("Checking availability...");
        if (UriUtils.exists(new URI(testTaskDto.getExecutableTestSuite().getRemoteResource().toString()),
                credentials)) {
            getLogger().info("...[OK]. The OGC TEAM Engine is available. "
                    + "You may need to ask the system administrator to "
                    + "increase the OGC TEAM Engine test driver timeout.");
        } else {
            getLogger().info("...[FAILED]. The OGC TEAM Engine is not available. "
                    + "Try re-running the test after a few minutes.");
        }
        reportError("OGC TEAM Engine is taking too long to respond. " + "Timeout after " + timeoutStr + ".",
                null, null);
        throw e;
    }

    getLogger().info("Results received.");
    ((TeTestTaskProgress) progress).stepCompleted();

    if (typeLoader.updateEtsFromResult(testTaskDto.getExecutableTestSuite(), result)) {
        getLogger().info("Internal ETS model updated.");
    }

    parseTestNgResult(result);
    ((TeTestTaskProgress) progress).stepCompleted();
}

From source file:com.opentable.jaxrs.exceptions.TestArgumentExceptionMapping.java

@Test
public void testMappingInternalError() throws Exception {
    final Response response = client.target(baseUrl + "/message").request()
            .post(Entity.json(Collections.singletonMap("message", "die")));
    assertEquals(500, response.getStatus());
}

From source file:org.jboss.as.test.manualmode.logging.LoggingPreferencesTestCase.java

@Before
public void prepareContainer() throws Exception {
    // Start the container
    container.start();/*from w  w w.  ja v a2s .  c  o m*/

    if (profileLog == null) {
        profileLog = getAbsoluteLogFilePath(FILE_HANDLER_FILE_NAME);
        perDeployLog = getAbsoluteLogFilePath(PER_DEPLOY_FILE_NAME);
    }

    final CompositeOperationBuilder builder = CompositeOperationBuilder.create();
    // Create a new logging profile
    builder.addStep(Operations.createAddOperation(PROFILE_ADDRESS));

    // Add root logger to the profile
    builder.addStep(Operations.createAddOperation(ROOT_LOGGER_ADDRESS));

    // Add file handler to the profile
    ModelNode op = Operations.createAddOperation(FILE_HANDLER_ADDRESS);
    ModelNode file = new ModelNode();
    file.get(PATH).set(profileLog.normalize().toString());
    op.get(FILE).set(file);
    builder.addStep(op);

    executeOperation(builder.build());

    // Register file logger to root
    op = Operations.createOperation("add-handler", ROOT_LOGGER_ADDRESS);
    op.get(NAME).set(FILE_HANDLER_NAME);
    executeOperation(op);

    final JavaArchive archive = createDeployment(Collections.singletonMap("Logging-Profile", PROFILE_NAME))
            .addAsResource(LoggingPreferencesTestCase.class.getPackage(), "per-deploy-logging.properties",
                    "META-INF/logging.properties");
    deploy(archive);
}

From source file:ru.mystamps.web.dao.impl.JdbcCategoryDao.java

@Override
public long countCategoriesOfCollection(Integer collectionId) {
    return jdbcTemplate.queryForObject(countCategoriesOfCollectionSql,
            Collections.singletonMap("collection_id", collectionId), Long.class);
}

From source file:de.codecentric.boot.admin.services.ApplicationRegistratorTest.java

@SuppressWarnings("rawtypes")
@Test// w w  w .  java  2  s  .co m
public void register_multiple() {
    adminProps.setRegisterOnce(false);

    when(restTemplate.postForEntity(isA(String.class), isA(HttpEntity.class), eq(Map.class)))
            .thenReturn(new ResponseEntity<Map>(Collections.singletonMap("id", "-id-"), HttpStatus.CREATED));

    assertTrue(registrator.register());

    verify(restTemplate).postForEntity("http://sba:8080/api/applications",
            new HttpEntity<>(Application.create("AppName").withHealthUrl("http://localhost:8080/health")
                    .withManagementUrl("http://localhost:8080/mgmt").withServiceUrl("http://localhost:8080")
                    .build(), headers),
            Map.class);

    verify(restTemplate).postForEntity("http://sba2:8080/api/applications",
            new HttpEntity<>(Application.create("AppName").withHealthUrl("http://localhost:8080/health")
                    .withManagementUrl("http://localhost:8080/mgmt").withServiceUrl("http://localhost:8080")
                    .build(), headers),
            Map.class);
}

From source file:com.smartitengineering.cms.spi.impl.content.PythonGeneratorTest.java

@Test
public void testPythonRepGeneration() throws IOException {
    TypeRepresentationGenerator generator = new PythonRepresentationGenerator();
    final RepresentationTemplate template = mockery.mock(RepresentationTemplate.class);
    WorkspaceAPIImpl impl = new WorkspaceAPIImpl() {

        @Override/*  ww  w .jav  a  2  s  .co  m*/
        public RepresentationTemplate getRepresentationTemplate(WorkspaceId id, String name) {
            return template;
        }
    };
    impl.setRepresentationGenerators(Collections.singletonMap(TemplateType.JASPER, generator));
    RepresentationProvider provider = new RepresentationProviderImpl();
    final WorkspaceAPI api = impl;
    registerBeanFactory(api);
    final Content content = mockery.mock(Content.class);
    final Field field = mockery.mock(Field.class);
    final FieldValue value = mockery.mock(FieldValue.class);
    final ContentType type = mockery.mock(ContentType.class);
    final Map<String, RepresentationDef> reps = mockery.mock(Map.class, "repMap");
    final RepresentationDef def = mockery.mock(RepresentationDef.class);
    mockery.checking(new Expectations() {

        {
            exactly(1).of(template).getTemplateType();
            will(returnValue(TemplateType.JASPER));
            exactly(1).of(template).getTemplate();
            will(returnValue(IOUtils.toByteArray(
                    getClass().getClassLoader().getResourceAsStream("scripts/python/test-script.py"))));
            exactly(1).of(value).getValue();
            will(returnValue(CONTENT));
            exactly(1).of(field).getValue();
            will(returnValue(value));
            exactly(1).of(content).getField(this.<String>with(Expectations.<String>anything()));
            will(returnValue(field));
            exactly(1).of(content).getContentDefinition();
            will(returnValue(type));
            final ContentId contentId = mockery.mock(ContentId.class);
            exactly(2).of(content).getContentId();
            will(returnValue(contentId));
            final WorkspaceId wId = mockery.mock(WorkspaceId.class);
            exactly(1).of(contentId).getWorkspaceId();
            will(returnValue(wId));
            exactly(2).of(type).getRepresentationDefs();
            will(returnValue(reps));
            exactly(2).of(reps).get(with(REP_NAME));
            will(returnValue(def));
            exactly(1).of(def).getParameters();
            will(returnValue(Collections.emptyMap()));
            exactly(1).of(def).getMIMEType();
            will(returnValue(GroovyGeneratorTest.MIME_TYPE));
            final ResourceUri rUri = mockery.mock(ResourceUri.class);
            exactly(1).of(def).getResourceUri();
            will(returnValue(rUri));
            exactly(1).of(rUri).getValue();
            will(returnValue("iUri"));
        }
    });
    Representation representation = provider.getRepresentation(REP_NAME, type, content);
    Assert.assertNotNull(representation);
    Assert.assertEquals(REP_NAME, representation.getName());
    Assert.assertEquals(CONTENT, StringUtils.newStringUtf8(representation.getRepresentation()));
    Assert.assertEquals(GroovyGeneratorTest.MIME_TYPE, representation.getMimeType());
    mockery.assertIsSatisfied();
}

From source file:net.openid.appauth.TokenResponseTest.java

@Test(expected = IllegalArgumentException.class)
public void testBuilder_setAdditionalParams_withBuiltInParam() {
    mMinimalBuilder.setAdditionalParameters(Collections.singletonMap(TokenRequest.PARAM_SCOPE, "scope"));
}