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.grails.plugins.elasticsearch.mapping.ElasticSearchMappingFactory.java

public static Map<String, Object> getElasticMapping(SearchableClassMapping scm) {
    Map<String, Object> elasticTypeMappingProperties = new LinkedHashMap<String, Object>();

    if (!scm.isAll()) {
        // "_all" : {"enabled" : true}
        elasticTypeMappingProperties.put("_all", Collections.singletonMap("enabled", false));
    }/*from   ww w. j a  va 2 s. c  o  m*/

    // Map each domain properties in supported format, or object for complex type
    for (SearchableClassPropertyMapping scpm : scm.getPropertiesMapping()) {
        // Does it have custom mapping?
        String propType = scpm.getGrailsProperty().getTypePropertyName();
        Map<String, Object> propOptions = new LinkedHashMap<String, Object>();
        // Add the custom mapping (searchable static property in domain model)
        propOptions.putAll(scpm.getAttributes());
        if (!(SUPPORTED_FORMAT.contains(scpm.getGrailsProperty().getTypePropertyName()))) {
            // Handle embedded persistent collections, ie List<String> listOfThings
            if (scpm.getGrailsProperty().isBasicCollectionType()) {
                String basicType = ClassUtils.getShortName(scpm.getGrailsProperty().getReferencedPropertyType())
                        .toLowerCase(Locale.ENGLISH);
                if (SUPPORTED_FORMAT.contains(basicType)) {
                    propType = basicType;
                }
                // Handle arrays
            } else if (scpm.getGrailsProperty().getReferencedPropertyType().isArray()) {
                String basicType = ClassUtils
                        .getShortName(scpm.getGrailsProperty().getReferencedPropertyType().getComponentType())
                        .toLowerCase(Locale.ENGLISH);
                if (SUPPORTED_FORMAT.contains(basicType)) {
                    propType = basicType;
                }
            } else if (isDateType(scpm.getGrailsProperty().getReferencedPropertyType())) {
                propType = "date";
            } else if (GrailsClassUtils.isJdk5Enum(scpm.getGrailsProperty().getReferencedPropertyType())) {
                propType = "string";
            } else if (scpm.getConverter() != null) {
                // Use 'string' type for properties with custom converter.
                // Arrays are automatically resolved by ElasticSearch, so no worries.
                propType = "string";
            } else {
                propType = "object";
            }

            if (scpm.getReference() != null) {
                propType = "object"; // fixme: think about composite ids.
            } else if (scpm.isComponent()) {
                // Proceed with nested mapping.
                // todo limit depth to avoid endless recursion?
                propType = "object";
                //noinspection unchecked
                propOptions.putAll((Map<String, Object>) (getElasticMapping(scpm.getComponentPropertyMapping())
                        .values().iterator().next()));

            }

            // Once it is an object, we need to add id & class mappings, otherwise
            // ES will fail with NullPointer.
            if (scpm.isComponent() || scpm.getReference() != null) {
                @SuppressWarnings({ "unchecked" })
                Map<String, Object> props = (Map<String, Object>) propOptions.get("properties");
                if (props == null) {
                    props = new LinkedHashMap<String, Object>();
                    propOptions.put("properties", props);
                }
                props.put("id", defaultDescriptor("long", "not_analyzed", true));
                props.put("class", defaultDescriptor("string", "no", true));
                props.put("ref", defaultDescriptor("string", "no", true));
            }
        }
        propOptions.put("type", propType);
        // See http://www.elasticsearch.com/docs/elasticsearch/mapping/all_field/
        if (!propType.equals("object") && scm.isAll()) {
            // does it make sense to include objects into _all?
            if (scpm.shouldExcludeFromAll()) {
                propOptions.put("include_in_all", false);
            } else {
                propOptions.put("include_in_all", true);
            }
        }
        // todo only enable this through configuration...
        if (propType.equals("string") && scpm.isAnalyzed()) {
            propOptions.put("term_vector", "with_positions_offsets");
        }
        elasticTypeMappingProperties.put(scpm.getPropertyName(), propOptions);
    }

    Map<String, Object> mapping = new LinkedHashMap<String, Object>();
    mapping.put(scm.getElasticTypeName(), Collections.singletonMap("properties", elasticTypeMappingProperties));

    return mapping;
}

From source file:com.example.dao.SpringJpaWidgetDao.java

/**
 * {@inheritDoc}/*from  www  .  j  a va 2 s  .  c o m*/
 *
 * @see com.example.dao.WidgetDao#findById(long)
 */
@SuppressWarnings("unchecked")
public final Widget findById(final long id) {
    final Map<String, Long> params = Collections.singletonMap("id", id);
    final List<Widget> list = getJpaTemplate().findByNamedQueryAndNamedParams(Widget.FIND_BY_ID, params);
    if (list.size() > 0) {
        return list.get(0);
    }
    return null;
}

From source file:com.thoughtworks.go.apiv1.secretconfigs.representers.SecretConfigRepresenter.java

public static void toJSON(OutputWriter jsonWriter, SecretConfig secretConfig) {
    if (secretConfig == null)
        return;/* www .  ja va2 s .com*/
    jsonWriter
            .addLinks(
                    linksWriter -> linksWriter.addLink("self", Routes.SecretConfigsAPI.id(secretConfig.getId()))
                            .addAbsoluteLink("doc", Routes.SecretConfigsAPI.DOC)
                            .addLink("find", Routes.SecretConfigsAPI.find()))
            .add("id", secretConfig.getId()).add("plugin_id", secretConfig.getPluginId())
            .addIfNotNull("description", secretConfig.getDescription());

    if (secretConfig.hasErrors()) {
        Map<String, String> fieldMapping = Collections.singletonMap("pluginId", "plugin_id");
        jsonWriter.addChild("errors",
                errorWriter -> new ErrorGetter(fieldMapping).toJSON(errorWriter, secretConfig));
    }

    jsonWriter.addChildList("properties", listWriter -> {
        ConfigurationPropertyRepresenter.toJSON(listWriter, secretConfig.getConfiguration());
    });

    if (!CollectionUtils.isEmpty(secretConfig.getRules())) {
        jsonWriter.addChildList("rules",
                rulesWriter -> RulesRepresenter.toJSON(rulesWriter, secretConfig.getRules()));
    }
}

From source file:sample.mvc.AdminController.java

@RequestMapping("/admin")
public Map<String, String> admin() {
    return Collections.singletonMap("password", "#s1pGo #gottacatchemall");
}

From source file:example.helloworld.PropertySourceTests.java

/**
 * Write some data to Vault before Vault can be used as
 * {@link org.springframework.vault.annotation.VaultPropertySource}.
 *//*from  w  ww .  j  a  v  a2  s .  c o m*/
@BeforeClass
public static void beforeClass() {

    VaultOperations vaultOperations = new VaultTestConfiguration().vaultTemplate();
    vaultOperations.write("secret/myapp/configuration", Collections.singletonMap("configuration.key", "value"));
}

From source file:sample.jersey.RestEndpoint.java

@GET
@Path("hello")
@Produces(MediaType.APPLICATION_JSON)/*from  w  w w .j a  v a  2  s  .  co m*/
public Response hello() {
    return Response.ok(Collections.singletonMap("message", "Hello World!")).build();
}

From source file:com.as.sagma.ControladorServicios.java

@RequestMapping(value = "/usuarios-json", method = RequestMethod.GET, headers = { "Accept=application/json" })
public @ResponseBody String buscarUsuarios() throws Exception {
    Map<String, ArrayList<Usuario>> singletonMap = Collections.singletonMap("Usuarios",
            GenerarUsuarios.obtenerUsuario());

    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(singletonMap);

}

From source file:sample.web.velocity.WelcomeController.java

@RequestMapping(value = "/", method = RequestMethod.GET)
public String view(Map<String, Object> model) throws JsonProcessingException {
    final Bean bean = new Bean("hey", Collections.singleton("1"), Collections.singletonMap("sh", "<"));
    model.put("head", "Change me");
    model.put("bean", bean);
    return "welcome";
}

From source file:comsat.sample.actuator.log4j2.SampleController.java

@RequestMapping("/")
@ResponseBody/*w  ww . jav a 2  s . c o m*/
public Map<String, String> helloWorld() throws InterruptedException, SuspendExecution {
    return Collections.singletonMap("message", this.helloWorldService.getHelloMessage());
}

From source file:com.jelastic.campitos.ControladorUsuario.java

@RequestMapping(value = "/usuario", method = RequestMethod.GET, headers = { "Accept=Application/json" })
public @ResponseBody String buscarTodos() throws Exception {
    /*/*from ww w . j av  a 2  s. c om*/
          Hay que refactorizar lo siguiente
          */

    Map<String, ArrayList<Usuario>> singletonMap = Collections.singletonMap("usuarios",
            (ArrayList<Usuario>) servicioUsuario.obtenerTodos());
    ObjectMapper maper = new ObjectMapper();
    return maper.writeValueAsString(singletonMap);
}