Tag Archives: jackson

Spring Boot: Web Application Properties and Default Values


These are Web application common properties that can be configured with any Spring Boot Web Application. These properties are already configured in Spring Boot with the given default value.

Note: In your application, You don’t need to add all these values in your application.proprties/application.yaml file. You just need to add only those values which you want to change/override.

See Also:

Embedded Server Configuration Properties

Spring Boot load these properties in ServerProperties

Name Default Value Description
server.address Network address for the server.
server.compression.enabled false To enable response compression.
server.compression.excluded-user-agents user-agents list to exclude from compression.
server.compression.mime-types Comma-separated MIME typesist that should be compressed. For instance `text/html,text/css,application/json`
server.compression.min-response-size Minimum response size for compression. For instance 2048
server.connection-timeout Connectors wait time (in MilliSeconds) for another HTTP request before closing the connection. If not set then take default as container-specific. If set as -1 for infinite time out.
server.context-parameters.* Servlet context init parameters. For example `server.context-parameters.a=alpha`
server.context-path Application Context path.
server.display-name application Display application name.
server.max-http-header-size 0 Maximum size in bytes for HTTP msg header.
server.max-http-post-size 0 Maximum size in bytes for HTTP post content.
server.error.include-stacktrace never When to include a “stacktrace” attribute.
server.error.path /error Path of navigate in case of the error.
server.error.whitelabel.enabled true Enable the default error page displayed in case of a server error.
server.jetty.acceptors Number of acceptor threads to use.
server.jetty.selectors Number of selector threads to use.
server.jsp-servlet.class-name org.apache.jasper.servlet.JspServlet The class name of the JSP servlet.
server.jsp-servlet.init-parameters.* Init parameters used to configure the JSP servlet.
server.jsp-servlet.registered true Whether or not the JSP servlet is registered.
server.port 8080 HTTP Server port.
server.server-header Server response header value (no header is sent if empty)
server.servlet-path / Path of the main dispatcher servlet.
server.use-forward-headers If X-Forwarded-* headers should be applied in HttpRequest.
server.session.cookie.comment Comment for the session cookie.
server.session.cookie.domain Domain for the session cookie.
server.session.cookie.http-only “HttpOnly” flag for the session cookie.
server.session.cookie.max-age Maximum age of the session cookie in seconds.
server.session.cookie.name Session cookie name.
server.session.cookie.path Path of the session cookie.
server.session.cookie.secure “Secure” flag for the session cookie.
server.session.persistent false Persist session data between restarts.
server.session.store-dir Directory used to store session data.
server.session.timeout Session timeout in seconds
server.session.tracking-modes Session tracking modes either one or more in “cookie”, “url”, “ssl”.
server.ssl.ciphers Supported SSL ciphers.
server.ssl.client-auth Set client authentication is “want” or “need”. Requires a trust store.
server.ssl.enabled Enable SSL support.
server.ssl.enabled-protocols Enabled SSL protocols.
server.ssl.key-alias Alias for identifies the key in the key store.
server.ssl.key-password Password for access the key in the key store.
server.ssl.key-store Path to the key store that holds the SSL certificate (jks file).
server.ssl.key-store-provider Provider for the key store.
server.ssl.key-store-type Type of the key store.
server.ssl.protocol TLS SSL protocol to use.
server.ssl.trust-store Trust store that holds SSL certificates.
server.ssl.trust-store-password Password used to access the trust store.
server.ssl.trust-store-provider Provider for the trust store.
server.ssl.trust-store-type Type of the trust store.
server.tomcat.accesslog.directory logs Directory in which log files are created. i.e tomcat base dir or absolute.
server.tomcat.accesslog.enabled false Enable access log.
server.tomcat.accesslog.pattern common Format pattern for access logs.
server.tomcat.accesslog.prefix access_log Log file name prefix.
server.tomcat.accesslog.rename-on-rotate false Defer inclusion of the date stamp in the file name as long as rotate time.
server.tomcat.accesslog.request-attributes-enabled false Set request attributes for IP address, ptotocol, port and Hostname.
server.tomcat.accesslog.suffix .log Log file name suffix.
server.tomcat.background-processor-delay 30 Delay between the invocation of backgroundProcess methods.(seconds)
server.tomcat.basedir Tomcat base directory. If not set then temporary directory will be used.
server.tomcat.internal-proxies 10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|\\
192\\.168\\.\\d{1,3}\\.\\d{1,3}|\\
169\\.254\\.\\d{1,3}\\.\\d{1,3}|\\
127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|\\
172\\.1[6-9]{1}\\.\\d{1,3}\\.\\d{1,3}|\\
172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|\\
172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}
regular expression matching trusted IP addresses.
server.tomcat.max-threads 0 Maximum amount of worker threads.
server.tomcat.min-spare-threads 0 Minimum amount of worker threads.
server.tomcat.port-header X-Forwarded-Port HTTP header name used to override the original port value.
server.tomcat.protocol-header Header value holds the incoming protocol, usually named “X-Forwarded-Proto”.
server.tomcat.protocol-header-https-value https Param Value in header that indicates that the incoming request uses SSL.
server.tomcat.remote-ip-header http header param from which the remote ip is extracted. For instance `X-FORWARDED-FOR`
server.tomcat.uri-encoding UTF-8 Character encoding to use to decode the URI.
server.undertow.accesslog.dir Undertow access log directory.
server.undertow.accesslog.enabled false Enable access log.
server.undertow.accesslog.pattern common Format pattern for access logs.
server.undertow.accesslog.prefix access_log. Log file name prefix.
server.undertow.accesslog.suffix log Log file name suffix.
server.undertow.buffer-size Each buffer size in bytes.
server.undertow.buffers-per-region Number of buffer for per region.
server.undertow.direct-buffers Allocate buffers space outside the Java heap.
server.undertow.io-threads Number of worker threads create for I/O.
server.undertow.worker-threads Number of worker threads.

Freemarker Properties

Spring Boot load these properties in FreeMarkerAutoConfiguration

Name Default Value Description
spring.freemarker.allow-request-override false HttpServletRequest attributes of same name are allowed to override controller generated model attributes.
spring.freemarker.allow-session-override false Enable HttpSession attributes of same name are allowed to override controller generated model attributes.
spring.freemarker.cache false Enable template caching
spring.freemarker.charset UTF-8 Template encoding.
spring.freemarker.check-template-location true Check that the templates location exists.
spring.freemarker.content-type text/html Content-Type value.
spring.freemarker.enabled true Enable MVC view resolution for this technology.
spring.freemarker.expose-request-attributes false Enable all request attributes should be added to the model prior to merging with the template.
spring.freemarker.expose-session-attributes false Enable all HttpSession attributes should be added with model prior to merging with the template.
spring.freemarker.expose-spring-macro-helpers true Enable expose a RequestContext for use by Spring’s macro library, under the name “springMacroRequestContext”.
spring.freemarker.prefer-file-system-access true Enable hot detection of template changes from file system.
spring.freemarker.prefix Prefix prepended with view names when building a URL.
spring.freemarker.request-context-attribute Name of the RequestContext attribute that will apply on all views.
spring.freemarker.settings.* Well-known FreeMarker keys that will passed to FreeMarker’s Configuration.
spring.freemarker.suffix Suffix appended with view names when building a URL.
spring.freemarker.template-loader-path classpath:/templates/ Comma-separated template paths.
spring.freemarker.view-names White list of view names.

Groovy Template Properties

Spring Boot load these properties in GroovyTemplateAutoConfiguration

Name Default Value Description
spring.groovy.template.allow-request-override false HttpServletRequest attributes of same name are allowed to override controller generated model attributes.
spring.groovy.template.allow-session-override false HttpSession attributes of same name are allowed to override (hide) controller generated model attributes..
spring.groovy.template.cache Enable template caching.
spring.groovy.template.charset UTF-8 Template encoding.
spring.groovy.template.check-template-location true Check that the templates location exists.
spring.groovy.template.configuration.* See GroovyMarkupConfigurer
spring.groovy.template.content-type test/html Content-Type value.
spring.groovy.template.enabled true Enable MVC view resolution for this technology.
spring.groovy.template.expose-request-attributes false Enable All request attributes added with model prior to merging with the template.
spring.groovy.template.expose-session-attributes false Enable All HttpSession attributes added with model prior to merging with the template.
spring.groovy.template.expose-spring-macro-helpers true Enable expose a RequestContext for use by Spring’s macro library, under the name “springMacroRequestContext”.
spring.groovy.template.prefix Prefix prepended with view names when building a URL.
spring.groovy.template.request-context-attribute Name of the RequestContext attribute for all views.
spring.groovy.template.resource-loader-path classpath:/templates/ Template path.
spring.groovy.template.suffix .tpl Suffix appended with view names when building a URL.
spring.groovy.template.view-names White list of view names.

Spring HATEOAS Properties

Spring Boot load these properties in HateoasProperties

Name Default Value Description
spring.hateoas.use-hal-as-default-json-media-type true Enable application/hal+json mime type responses for requests that accept application/json.

HTTP Message Conversion Properties

Name Default Value Description
spring.http.converters.preferred-json-mapper jackson Preferred JSON mapper for HTTP message conversion. Specified “gson” in case jacson and gson both are on the classpath.

HTTP Encoding Properties

Spring Boot load these properties in HttpEncodingProperties class.

Name Default Value Description
spring.http.encoding.charset UTF-8 Charset of HTTP requests and responses. Added to the “Content-Type” header.
spring.http.encoding.enabled true Enable http encoding.
spring.http.encoding.force Force the encoding on HTTP requests and responses.
spring.http.encoding.force-request Force the encoding on HTTP requests. Defaults to true.
spring.http.encoding.force-response Force the encoding on HTTP responses.
spring.http.encoding.mapping Locale to Encoding mapping.

Multipart Properties

Spring Boot load these properties in MultipartProperties class.

Name Default Value Description
spring.http.multipart.enabled true Enable support of multi-part uploads.
spring.http.multipart.file-size-threshold 0 Threshold after which files will be written to disk.Suffixed “MB” or “KB”.
spring.http.multipart.location Intermediate location of uploaded files.
spring.http.multipart.max-file-size 1Mb Max file size. Suffixed “MB” or “KB”.
spring.http.multipart.max-request-size 10Mb Max request size. Suffixed “MB” or “KB”.
spring.http.multipart.resolve-lazily false Set to resolve the multipart request lazily when file or parameter access.

Jackson Properties

Spring Boot load these properties in JacksonProperties class.

Name Default Value Description
spring.jackson.date-format Date format or a fully-qualified date format class name. For example `yyyy-MM-dd HH:mm:ss`.
spring.jackson.default-property-inclusion Controls the properties inclusion during serialization.
spring.jackson.deserialization.* on/off features for Jackson that affect the way Java objects are deserialized.
spring.jackson.generator.* on/off features for Jackson generators.
spring.jackson.joda-date-time-format Joda date time strig format. If it is configured with a format string use it otherwise will use “date-format” as a fallback .
spring.jackson.locale Locale used for formatting.
spring.jackson.mapper.* on/off features of Jackson general features.
spring.jackson.parser.* on/off features for Jackson parsers.
spring.jackson.property-naming-strategy Set Jackson’s PropertyNamingStrategy type sub class as a fully-qualified class name.
spring.jackson.serialization.* on/off features of Jackson that affect the way Java objects are serialized.
spring.jackson.serialization-inclusion Controls the properties inclusion during serialization by configuring values in Jackson’s JsonInclude.Include enumeration.
spring.jackson.time-zone Time zone for date. For example `America/Los_Angeles`

Jersey Properties

Spring Boot load these properties in JerseyProperties class.

Name Default Value Description
spring.jersey.application-path base URI path for the application that override the value of “@ApplicationPath” if specified.
spring.jersey.filter.order 0 Jersey filter chain order.
spring.jersey.init.* Init parameters to pass to Jersey through servlet or filter.
spring.jersey.servlet.load-on-startup -1 Load on startup priority of the Jersey servlet.
spring.jersey.type servlet Jersey integration type.

Spring Mobile Device Views Properties

Spring Boot load these properties in DeviceDelegatingViewResolverAutoConfiguration class.

Name Default Value Description
spring.mobile.devicedelegatingviewresolver.enable-fallback false Enable support for fallback resolution.
spring.mobile.devicedelegatingviewresolver.enabled false Enable device view resolver.
spring.mobile.devicedelegatingviewresolver.mobile-prefix mobile/ Prefix prepended to view names of mobile devices.
spring.mobile.devicedelegatingviewresolver.mobile-suffix Suffix appended to view names of mobile devices.
spring.mobile.devicedelegatingviewresolver.normal-prefix Prefix prepended to view names of normal devices.
spring.mobile.devicedelegatingviewresolver.normal-suffix Suffix appended to view names of normal devices.
spring.mobile.devicedelegatingviewresolver.tablet-prefix tablet/ Prefix prepended to view names of tablet devices.
spring.mobile.devicedelegatingviewresolver.tablet-suffix Suffix appended to view names of tablet devices.

Spring Mobile Site Preference Properties

Spring Boot load these properties in SitePreferenceAutoConfiguration class.

Name Default Value Description
spring.mobile.sitepreference.enabled true Enable SitePreferenceHandler.

Mustache Templates Properties

Spring Boot load these properties in MustacheAutoConfiguration class.

Name Default Value Description
spring.mustache.allow-request-override HttpServletRequest attributes with same name are allowed to override controller generated model attributes..
spring.mustache.allow-session-override HttpSession attributes with same name are allowed to override controller generated model attributes.
spring.mustache.cache Enable template caching.
spring.mustache.charset Template encoding.
spring.mustache.check-template-location Check that the templates location exists.
spring.mustache.content-type Content-Type value.
spring.mustache.enabled Enable MVC view resolution for this technology.
spring.mustache.expose-request-attributes All request attributes added to the model prior to merging with the template.
spring.mustache.expose-session-attributes All HttpSession attributes added to the model prior to merging with the template.
spring.mustache.expose-spring-macro-helpers Expose a RequestContext use Spring’s macro library, under the name “springMacroRequestContext”.
spring.mustache.prefix classpath:/templates/ Prefix to template names.
spring.mustache.request-context-attribute RequestContext attribute name for all views.
spring.mustache.suffix .html Suffix to template names.
spring.mustache.view-names White list of view names.

Spring MVC Properties

Spring Boot load these properties in WebMvcProperties class.

Name Default Value Description
spring.mvc.async.request-timeout Amount of time before asynchronous request handling times out.(in milliseconds)
spring.mvc.date-format Date format For example `dd/MM/yyyy`.
spring.mvc.dispatch-trace-request false Dispatch TRACE requests to the FrameworkServlet doService method.
spring.mvc.dispatch-options-request true Dispatch OPTIONS requests to the FrameworkServlet doService method.
spring.mvc.favicon.enabled true Enable resolution of favicon.ico.
spring.mvc.formcontent.putfilter.enabled true Enable Spring’s HttpPutFormContentFilter.
spring.mvc.ignore-default-model-on-redirect true Content of the “default” model need to ignored during redirect scenarios.
spring.mvc.locale Set Locale otherwise By default locale is overridden by the “Accept-Language” header.
spring.mvc.locale-resolver accept-header Define how locale should be resolved.
spring.mvc.log-resolved-exception false Enable warn logging, for exceptions resolved by a “HandlerExceptionResolver”.
spring.mvc.media-types.* Maps file extensions for content negotiation.
spring.mvc.message-codes-resolver-format Formatting strategy for message codes. For example `PREFIX_ERROR_CODE`.
spring.mvc.servlet.load-on-startup -1 Load on startup priority for Spring Web Services servlet.
spring.mvc.static-path-pattern /** Path pattern used for static resources.
spring.mvc.throw-exception-if-no-handler-found false If a “NoHandlerFoundException”, then throw if no Handler was found to process a request.
spring.mvc.view.prefix Prefix for Spring MVC view.
spring.mvc.view.suffix Suffux for Spring MVC view.

Spring Resources Handling Properties

Spring Boot load these properties in ResourceProperties class.

.

Name Default Value Description
spring.resources.add-mappings true Enable default resource handling.
spring.resources.cache-period Cache period (in seconds)for the resources served by the resource handler.
spring.resources.chain.cache true Enable caching in the Resource chain.
spring.resources.chain.enabled Enable the Spring Resource Handling chain. By default disabled as long as one strategy has been enabled.
spring.resources.chain.gzipped false Enable resolution of already gzipped resources.
spring.resources.chain.html-application-cache false Enable HTML5 application cache manifest rewriting.
spring.resources.chain.strategy.content.enabled false Enable the content for Version Strategy.
spring.resources.chain.strategy.content.paths /** Comma-separated list of patterns for Version Strategy.
spring.resources.chain.strategy.fixed.enabled false Enable the fixed Version Strategy.
spring.resources.chain.strategy.fixed.paths /** Comma-separated list of patterns for Version Strategy.
spring.resources.chain.strategy.fixed.version Version string for Version Strategy.
spring.resources.static-locations classpath:/META-INF/resources/, classpath:/resources/,
classpath:/static/,
classpath:/public/
Locations of static resources

Spring Session Properties

Spring Boot load these properties in SessionProperties class.

Name Default Value Description
spring.session.hazelcast.map-name spring:session:sessions Name of the map used to store sessions.
spring.session.jdbc.initializer.enabled If necessary, Create the required session tables on startup if necessary. Enabled automatically if the default a custom schema is configured or table name is set.
spring.session.jdbc.schema classpath:
org/springframework/
session/jdbc/
schema-@@platform
@@.sql
SQL file Path for initialize the database schema.
spring.session.jdbc.table-name SPRING_SESSION Name of database table used to store sessions.
spring.session.mongo.collection-name sessions Collection name used to store sessions.
spring.session.redis.flush-mode Flush mode for the Redis sessions.
spring.session.redis.namespace Namespace for keys used to store sessions.
spring.session.store-type Session store type.

Spring Social Properties

Spring Boot load these properties in SocialWebAutoConfiguration class.

Name Default Value Description
spring.social.auto-connection-views false Enable the connection status for supported providers.

Spring Social Facebook Properties

Spring Boot load these properties in FacebookAutoConfiguration class.

Name Default Value Description
spring.social.facebook.app-id Your Facebook App ID
spring.social.facebook.app-secret Your Facebook App Secret

Spring Social LinkedIn Properties

Spring Boot load these properties in LinkedInAutoConfiguration class.

Name Default Value Description
spring.social.linkedin.app-id Your LinkedIn App ID
spring.social.linkedin.app-secret Your LinkedIn App Secret

Spring Local Twitter Properties

Spring Boot load these properties in TwitterAutoConfiguration class.

Name Default Value Description
spring.social.twitter.app-id Your Twitter App ID
spring.social.twitter.app-secret Your Twitter App Secret

Thymeleaf Properties

Spring Boot load these properties in ThymeleafAutoConfiguration class.

Name Default Value Description
spring.thymeleaf.cache true Enable template caching.
spring.thymeleaf.check-template true Check that the template exists..
spring.thymeleaf.check-template-location true Check that the templates location.
spring.thymeleaf.content-type text/html Content-Type value.
spring.thymeleaf.enabled true Enable MVC Thymeleaf view resolution.
spring.thymeleaf.encoding UTF-8 Template encoding.
spring.thymeleaf.excluded-view-names Comma-separated list of view names that can excluded from resolution.
spring.thymeleaf.mode HTML5 Template mode to be applied to templates. Refer StandardTemplateModeHandlers.
spring.thymeleaf.prefix classpath:/templates/ Prefix prepended to view names for building a URL.
spring.thymeleaf.suffix .html Suffix appended to view names for building a URL.
spring.thymeleaf.template-resolver-order template resolver order in chain.
spring.thymeleaf.view-names Comma-separated list of view names.

Velocity Templates Properties

Spring Boot load these properties in VelocityAutoConfiguration class.

Name Default Value Description
spring.velocity.allow-request-override false HttpServletRequest attributes with same name are allowed to override controller generated model attributes.
spring.velocity.allow-session-override false HttpSession attributes with same name are allowed to override controller generated model attributes.
spring.velocity.cache Enable template caching.
spring.velocity.charset UTF-8 Template encoding.
spring.velocity.check-template-location true Check that the templates location exists.
spring.velocity.content-type text/html Content-Type value.
spring.velocity.date-tool-attribute Name of the DateTool helper object to expose in the Velocity context of the view.
spring.velocity.enabled true Enable MVC view resolution for this technology.
spring.velocity.expose-request-attributes false all request attributes should be added to the model prior to merging with the template.
spring.velocity.expose-session-attributes false all HttpSession attributes should be added to the model prior to merging with the template.
spring.velocity.expose-spring-macro-helpers true expose a RequestContext for use by Spring’s macro library, under the name “springMacroRequestContext”.
spring.velocity.number-tool-attribute Name of the NumberTool helper object to expose in the Velocity context of the view.
spring.velocity.prefer-file-system-access true Prefer file system access for template loading for hot detection of template changes.
spring.velocity.prefix Prefix prepended to view names for building a URL.
spring.velocity.properties.* Additional velocity properties.
spring.velocity.request-context-attribute Name of the RequestContext attribute for all views.
spring.velocity.resource-loader-path classpath:/templates/ Template path.
spring.velocity.suffix .vm Suffix appended to view names for building a URL.
spring.velocity.toolbox-config-location Velocity Toolbox config location. For instance `/WEB-INF/toolbox.xml`
spring.velocity.view-names White list of view names.

Spring Web Service Properties

Spring Boot load these properties in WebServicesProperties class.

Name Default Value Description
spring.webservices.path /services Path that serves as the base URI.
spring.webservices.servlet.init Servlet init parameters Spring for Sevices.
spring.webservices.servlet.load-on-startup -1 Load on startup priority for Spring Web Services servlet.

References

https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

JSON Parsers


JSON (JavaScript Object Notation) is most popular for NoSQL data storage, data exchange format between browsers and web servers and latest framework also use for communication over networks.

For Example :

  • All latest browsers natively support parse JSON data to java script to display over page.
  • REST Service support one of MediaType is JSON to exchange data between browsers or client application to servers where these REST Services are deploy.
  • Some latest framework like Elasticsearch, Logstash, Kibana, Kafka ,Filebeat etc. are used JSON for internal storage and data exchange over network between servers.

All these above cases, JSON data language independent feature provides communication compatibility between different type frameworks and servers. All these frameworks and servers implemented by one of computer language which provides JSON API’s by internally or consumed third party library for parsing and generation.

Here we will focus mainly on Java based JSON APIs which provide various choices for parsing and JSON generation on different cases from JAVA objects.

The Java Open Source Community developed some JSON APIs which offers more choices and flexibility to work with JSON. Here is list of some well-known JSON APIS:

  • Jackson
  • GSON
  • Boon
  • JSON.org

See also : Serialization and Deserialization of JSON to/from JAVA.

JACKSON

Jackson is most popular Java JSON APIs which provide several choices to work with JSON. It contains two different parsers:

  • JsonParser : This is pull parser, which parse one token at a time. These token generated by JsonGenerator.
  • JsonMapper : This parser is use convert customize JSON to/from JAVA object. It also parse data in tree model.

You can follow this link to more detail about Jackson JSON APIs : https://github.com/FasterXML/jackson

GSON

GSON provides flexible Java JSON API developed by Google. GSON APIs are able to work with arbitrary Java objects including pre-existing objects that you do not have source code. It also supports for handling complex objects with generics and deep inheritance. GSON is having three different parsers for JSON Java APIS:

  • Gson class : It can parse JSON into custom Java objects.
  • JsonReador : It’s pull JSON parser, which parse one token at a time.
  • JsonParser : It’s parser JSON into a tree structure of GSON specific Java Objects.

You can follow this link to more detail about GSON JSON APIs : https://github.com/google/gson

Boon

Boon is a standard JSON API in Groovy . It is similar to JACKSON but not only apecific for Java JSON API. It’s complete tool kit to working with data, file process and REST services etc. Boon contains the following Java JSON parsers:

  • ObjectMapper :This parser is use to parse JSON into custom objects and Java Maps.

You can follow this link to more detail about BOON JSON APIs : https://github.com/boonproject/boon

JSON.org

JSON.org provides the first JSON API developed for Java. It’s easy to use but not flexible and fast as compared to others  Java JSON open source APIs.

As I recommend if your application is too old and using this API then only go with it otherwise you can switch with others above Java JSON APIs.

You can follow this link to more detail about JSON.org JSON APIs : https://github.com/douglascrockford/JSON-java

Here, In my further posts for JSON I will focus on JACKSON and GSON because that are most known JSON APIs used by developers.

You would like to see

Follow below link to see more about JSON Tutorial and JSON issues Solutions:

[Solved] com.fasterxml.jackson.databind.exc. MismatchedInputException: Cannot deserialize instance of `XYZ` out of START_ARRAY token


MismatchedInpuException is base class for all JsonMappingExceptions. It occurred when input is not mapping with target definition or mismatch between as required for fulfilling the deserialization. This exception is used for some input problems, but in most cases, there should be more explicit subtypes to use.

Example of MismatchedInputException

Here MismatchedInpuException issue is happening because of type mismatch because passing JSON as an array of StudentDetail while deserialization is mapped for single StudentDetail object.

public class StudentDetail {
	private int rollNumber;
	private String firstName;
	private String lastName;

	//getter and setter of class
}
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJacksonExample2 {

	public static void main(String[] args) {
	    String json=" ["
	    				+ "{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}, "
	    				+ "{\"rollNumber\":22 , \"firstName\":\"Abhishek\" , \"lastName\":\"Garg\"}"
	    		+ "]";

	    System.out.println(json);
		try
		{
	    ObjectMapper mapper = new ObjectMapper();
		//issue is here
	    StudentDetail student= mapper.readValue(json, StudentDetail.class);
	    System.out.println(student);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

}

MismatchedInputException Stacktrace


 [{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta"}, {"rollNumber":22 , "firstName":"Abhishek" , "lastName":"Garg"}]
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.fiot.json.jackson.exceptions.StudentDetail` out of START_ARRAY token
 at [Source: (String)" [{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta"}, {"rollNumber":22 , "firstName":"Abhishek" , "lastName":"Garg"}]"; line: 1, column: 2]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1343)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1139)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1093)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromArray(BeanDeserializerBase.java:1461)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:185)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:161)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at com.fiot.json.jackson.exceptions.TestJacksonExample2.main(TestJacksonExample2.java:22)

Solutions

To resolve this issue, change the type from StudentDetail to as array StudentDetail[]

public static void main(String[] args) {
	    String json=" ["
	    				+ "{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}, "
	    				+ "{\"rollNumber\":22 , \"firstName\":\"Abhishek\" , \"lastName\":\"Garg\"}"
	    		+ "]";
	    System.out.println(json);
		try
		{
	    ObjectMapper mapper = new ObjectMapper();
		//Convereted to Type as array
	    StudentDetail[] students= mapper.readValue(json,  StudentDetail[].class );
	    System.out.println(students);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

References

https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/exc/MismatchedInputException.html

You would like to see

Follow below link to learn more on JSON and  JSON issues solutions:

How to retrieve key Information from JSON Data?


Jackson provide API’s to parse information based on Key  name.  It’s work like DOM parser and make tree of properties in JSON. Based on Path,Jackson retrieve this information for keys.

Pre-Requisite 

Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

  <dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.8.5</version>
  </dependency>
 

Example

In below example we have some sample JSON Data for Student and by Jackson API will try to retrieve keys information like rollNumber and phoneNumbers.

Sample DATA

{
"rollNumber" : 11,
"firstName" : "Saurabh",
"lastName" : "Gupta",
"permanent" : false,
"address" : {
"addressLine" : "Lake Union Hill Way",
"city" : "Atlanta",
"zipCode" : 50005
},
"phoneNumbers" : [ 2233445566, 3344556677 ],
"cities" : [ "Dallas", "San Antonio", "Irving" ],
"properties" : {
"play" : "Badminton",
"interst" : "Math",
"age" : "34 years"
}
}

Sample Code

package test.facingissesonit.json.jacson;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ReadJsonByKeyName {

	public static void main(String[] args) {
		try
		{
		byte[] jsonData = Files.readAllBytes(Paths.get("student_data2.txt"));

		ObjectMapper objectMapper = new ObjectMapper();

		//Jacson read JSON like DOM Parser and create tree of properties
		JsonNode rootNode = objectMapper.readTree(jsonData);

		JsonNode idNode = rootNode.path("rollNumber");
		System.out.println("rollNumber = "+idNode.asInt());

		JsonNode phoneNosNode = rootNode.path("phoneNumbers");
		Iterator<JsonNode> elements = phoneNosNode.elements();
		while(elements.hasNext()){
			JsonNode phone = elements.next();
			System.out.println("Phone No = "+phone.asLong());
		}
		}
		catch(JsonProcessingException ex)
		{
			ex.printStackTrace();
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
	}
}

Output

rollNumber = 11
Phone No = 2233445566
Phone No = 3344556677

More Sample Code

For more java and JDBC codes follow below links

How to create dynamic JSON by Java?


Jackson  provide Java api’s   to create JSON on runtime . These api’s can handle different type of data and objects.

Jacson API’s

Writing Root Object
JsonGenerator.writeStartObject();
JsonGenerator.writeEndObject();

Writing Sub Object
JsonGenerator.writeObjectFieldStart();
JsonGenerator.writeEndObject();

Writing Array
JsonGenerator.writeArrayFieldStart()
JsonGenerator.writeEndObject();

Writing Field Level
JsonGenerator.writeNumberField();
JsonGenerator.writeStringField();
JsonGenerator.writeBooleanField();

Pre-Requisite 

Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

  <dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.8.5</version>
  </dependency>
 

Example

In below example by Jacson API’s generating JSON on runtime and writing on file.

package test.facingissesonit.json.jacson;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;

public class JsonStreamWriteToFile {

	public static void main(String[] args) {
		Student student = sampleStudentObject();
		try {
			JsonGenerator jsonGenerator = new JsonFactory().createGenerator(new FileOutputStream("student_data.txt"));
			// for pretty formatted printing
			jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter());
			// start root from here
			jsonGenerator.writeStartObject();

			jsonGenerator.writeNumberField("rollNumber", student.getRollNumber());
			jsonGenerator.writeStringField("firstName", student.getFirstName());
			jsonGenerator.writeStringField("lastName", student.getLastName());
			jsonGenerator.writeBooleanField("permanent", student.isPermanent());

			jsonGenerator.writeObjectFieldStart("address"); // object writing
			jsonGenerator.writeStringField("addressLine", student.getAddress().getAddressLine());
			jsonGenerator.writeStringField("city", student.getAddress().getCity());
			jsonGenerator.writeNumberField("zipCode", student.getAddress().getZipCode());
			jsonGenerator.writeEndObject(); // address object completed

			jsonGenerator.writeArrayFieldStart("phoneNumbers");
			for (long num : student.getPhoneNumbers())
				jsonGenerator.writeNumber(num);
			jsonGenerator.writeEndArray();

			 // start array writing for cities
			jsonGenerator.writeArrayFieldStart("cities");
			for (String city : student.getCities())
				jsonGenerator.writeString(city);
			// closing cities array
			jsonGenerator.writeEndArray(); 

			jsonGenerator.writeObjectFieldStart("properties");
			Set<String> keySet = student.getProperties().keySet();
			for (String key : keySet) {
				String value = student.getProperties().get(key);
				jsonGenerator.writeStringField(key, value);
			}
			// End of  properties writing
			jsonGenerator.writeEndObject();
			//End root object writing
			jsonGenerator.writeEndObject(); 

			jsonGenerator.flush();
			jsonGenerator.close();

		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

	public static Student sampleStudentObject() {

		Student student = new Student();
		student.setRollNumber(11);
		student.setFirstName("Saurabh");
		student.setLastName("Gupta");
		student.setPhoneNumbers(new long[] { 2233445566L, 3344556677L });

		Address add = new Address();
		add.setAddressLine("Lake Union Hill Way");
		add.setCity("Atlanta");
		add.setState("GA");
		add.setZipCode(50005);
		student.setAddress(add);

		List<String> cities = new ArrayList<String>();
		cities.add("Dallas");
		cities.add("San Antonio");
		cities.add("Irving");
		student.setCities(cities);

		Map<String, String> props = new HashMap<String, String>();
		props.put("age", "34 years");
		props.put("interst", "Math");
		props.put("play", "Badminton");

		student.setProperties(props);

		return student;
	}
}

Model Object

Student and Address classes are required to execute these code

package test.facingissesonit.json.jacson;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Student {
	private int rollNumber;
	private String firstName;
	private String lastName;
	private boolean permanent;
	private Address address;
	private long[] phoneNumbers;
	private List<String> cities;
	private Map<String, String> properties;
	@Override
	public String toString()
	{
		StringBuffer sb=new StringBuffer();
		sb.append("==============Student Information================\n");
		sb.append("rollNumber=").append(rollNumber).append("\n");
		sb.append("firstName=").append(firstName).append("\n");
		sb.append("lastName=").append(lastName).append("\n");
		sb.append("permanent=").append(permanent).append("\n");
		sb.append("adress=").append(address).append("\n");
		sb.append("phoneNumbers=").append(Arrays.toString(phoneNumbers)).append("\n");
		sb.append("cities=").append(Arrays.toString(cities.toArray(new String[cities.size()]))).append("\n");
		sb.append("properties=").append(properties).append("\n");
		return sb.toString();
	}
	public int getRollNumber() {
		return rollNumber;
	}
	public void setRollNumber(int rollNumber) {
		this.rollNumber = rollNumber;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public boolean isPermanent() {
		return permanent;
	}
	public void setPermanent(boolean permanent) {
		this.permanent = permanent;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	public long[] getPhoneNumbers() {
		return phoneNumbers;
	}
	public void setPhoneNumbers(long[] phoneNumbers) {
		this.phoneNumbers = phoneNumbers;
	}
	public List<String> getCities() {
		return cities;
	}
	public void setCities(List<String> cities) {
		this.cities = cities;
	}
	public Map<String, String> getProperties() {
		return properties;
	}
	public void setProperties(Map<String, String> properties) {
		this.properties = properties;
	}

}

package test.facingissesonit.json.jacson;

public class Address {
private String addressLine;
private String city;
private String state;
private int zipCode;
@Override
public String toString()
{
	StringBuffer sb=new StringBuffer();
	sb.append("AddressLine=").append(addressLine).append("\n");
	sb.append("city=").append(city).append("\n");
	sb.append("state=").append(state).append("\n");
	sb.append("zipCode=").append(zipCode).append("\n");
	return sb.toString();
}
public String getAddressLine() {
	return addressLine;
}
public void setAddressLine(String addressLine) {
	this.addressLine = addressLine;
}
public String getCity() {
	return city;
}
public void setCity(String city) {
	this.city = city;
}
public String getState() {
	return state;
}
public void setState(String state) {
	this.state = state;
}
public int getZipCode() {
	return zipCode;
}
public void setZipCode(int zipCode) {
	this.zipCode = zipCode;
}
}

Output

Generated output on Student_data.txt file

{
  "rollNumber" : 11,
  "firstName" : "Saurabh",
  "lastName" : "Gupta",
  "permanent" : false,
  "address" : {
    "addressLine" : "Lake Union Hill Way",
    "city" : "Atlanta",
    "zipCode" : 50005
  },
  "phoneNumbers" : [ 2233445566, 3344556677 ],
  "cities" : [ "Dallas", "San Antonio", "Irving" ],
  "properties" : {
    "play" : "Badminton",
    "interst" : "Math",
    "age" : "34 years"
  }
}

More Sample Code

For more java and JDBC codes follow below links

How to Convert JSON data from file to ArrayList?


Jackson provide api’s  to convert JSON data to Collections Objects like Map, ArrayList etc.

In below example file student_data.txt having collections of students data in JSON form and through these Jacson API’s will convert JSON data to ArrayList java object.

Pre-Requisite 

Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

  <dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.8.5</version>
  </dependency>
 

Sample Data

 Add below content in  student_data.txt

[
{
  "rollNumber" : 11,
  "firstName" : "Saurabh",
  "lastName" : "Gupta",
  "permanent" : false,
  "address" : {
    "addressLine" : "Lake Union Hill Way",
    "city" : "Atlanta",
    "zipCode" : 50005
  },
  "phoneNumbers" : [ 2233445566, 3344556677 ],
  "cities" : [ "Dallas", "San Antonio", "Irving" ],
  "properties" : {
    "play" : "Badminton",
    "interst" : "Math",
    "age" : "34 years"
  }
},
{
  "rollNumber" : 11,
  "firstName" : "Gaurav",
  "lastName" : "Khaira",
  "permanent" : true,
  "address" : {
    "addressLine" : " 5770 Shiloh woods dr",
    "city" : "Cumming",
    "zipCode" : 50007
  },
  "phoneNumbers" : [ 2233445567, 3344556678 ],
  "cities" : [ "New York", "Austin", "Plano" ],
  "properties" : {
    "play" : "Baseball",
    "interst" : "Science",
    "age" : "36 years"
  }
}
]

Example 

package test.facingissesonit.json.jacson;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ConvertJsonToArrayList {

	public static void main(String[] args) {
		try
		{
		byte[] mapData = Files.readAllBytes(Paths.get("student_data.txt"));
		Student[] studentArr = null;

		ObjectMapper objectMapper = new ObjectMapper();
		studentArr = objectMapper.readValue(mapData, Student[].class);
		List<Student> studentList=Arrays.asList(studentArr);
		System.out.println("Student 1 \n"+studentList.get(0));
		System.out.println("Student 2 \n"+studentList.get(1));

		}
		catch(JsonMappingException ex)
		{
			ex.printStackTrace();
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
	}
}

Model Classes

Below Student and Address are required classes for execute this code.

package test.facingissesonit.json.jacson;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Student {
	private int rollNumber;
	private String firstName;
	private String lastName;
	private boolean permanent;
	private Address address;
	private long[] phoneNumbers;
	private List<String> cities;
	private Map<String, String> properties;
	@Override
	public String toString()
	{
		StringBuffer sb=new StringBuffer();
		sb.append("==============Student Information================\n");
		sb.append("rollNumber=").append(rollNumber).append("\n");
		sb.append("firstName=").append(firstName).append("\n");
		sb.append("lastName=").append(lastName).append("\n");
		sb.append("permanent=").append(permanent).append("\n");
		sb.append("adress=").append(address).append("\n");
		sb.append("phoneNumbers=").append(Arrays.toString(phoneNumbers)).append("\n");
		sb.append("cities=").append(Arrays.toString(cities.toArray(new String[cities.size()]))).append("\n");
		sb.append("properties=").append(properties).append("\n");
		return sb.toString();
	}
	public int getRollNumber() {
		return rollNumber;
	}
	public void setRollNumber(int rollNumber) {
		this.rollNumber = rollNumber;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public boolean isPermanent() {
		return permanent;
	}
	public void setPermanent(boolean permanent) {
		this.permanent = permanent;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	public long[] getPhoneNumbers() {
		return phoneNumbers;
	}
	public void setPhoneNumbers(long[] phoneNumbers) {
		this.phoneNumbers = phoneNumbers;
	}
	public List<String> getCities() {
		return cities;
	}
	public void setCities(List<String> cities) {
		this.cities = cities;
	}
	public Map<String, String> getProperties() {
		return properties;
	}
	public void setProperties(Map<String, String> properties) {
		this.properties = properties;
	}

}

package test.facingissesonit.json.jacson;

public class Address {
private String addressLine;
private String city;
private String state;
private int zipCode;
@Override
public String toString()
{
	StringBuffer sb=new StringBuffer();
	sb.append("AddressLine=").append(addressLine).append("\n");
	sb.append("city=").append(city).append("\n");
	sb.append("state=").append(state).append("\n");
	sb.append("zipCode=").append(zipCode).append("\n");
	return sb.toString();
}
public String getAddressLine() {
	return addressLine;
}
public void setAddressLine(String addressLine) {
	this.addressLine = addressLine;
}
public String getCity() {
	return city;
}
public void setCity(String city) {
	this.city = city;
}
public String getState() {
	return state;
}
public void setState(String state) {
	this.state = state;
}
public int getZipCode() {
	return zipCode;
}
public void setZipCode(int zipCode) {
	this.zipCode = zipCode;
}
}

Output

Below is console output generated by program which is from Java Object.

Student 1
==============Student Information================
rollNumber=11
firstName=Saurabh
lastName=Gupta
permanent=false
adress=AddressLine=Lake Union Hill Way
city=Atlanta
state=null
zipCode=50005

phoneNumbers=[2233445566, 3344556677]
cities=[Dallas, San Antonio, Irving]
properties={play=Badminton, interst=Math, age=34 years}

Student 2
==============Student Information================
rollNumber=11
firstName=Gaurav
lastName=Khaira
permanent=true
adress=AddressLine= 5770 Shiloh woods dr
city=Cumming
state=null
zipCode=50007

phoneNumbers=[2233445567, 3344556678]
cities=[New York, Austin, Plano]
properties={play=Baseball, interst=Science, age=36 years}

More Sample Code

For more java and JDBC codes follow below links

Elasticsearch REST JAVA Client to get Index Details List


Below is example to get Index Detail in Java Array by using Elasticsearch REST Java client. Here client will call endpoint  “/_cat/indices?format=json” to retrieve all detail of index list. It is same as we use GET by CURL

GET http://elasticsearchHost:9200/_cat/indices?format=json
 

Pre-requisite

  • Minimum requirement for Java 7 version required.
  • Add below dependency for Elasticsearch REST and JSON Mapping in your pom.xml or add in your class path.

Dependency

<!--Elasticsearch REST jar-->
<dependency>
			<groupId>org.elasticsearch.client</groupId>
			<artifactId>rest</artifactId>
			<version>5.1.2</version>
</dependency>
<!--Jackson jar for mapping json to Java -->
<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.8.5</version>
</dependency>

Sample Code

import java.io.IOException;
import java.util.Collections;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

import com.fasterxml.jackson.databind.ObjectMapper;

public class ElasticsearchRESTIndexClient {

	public static void main(String[] args) {
		IndexInfo []indexArr = null;
		RestClient client = null;
		try {
			client = openConnection();
			if (client != null) {
				// performRequest GET method will retrieve all index detail list
				// information from elastic server
				Response response = client.performRequest("GET", "/_cat/indices?format=json",
						Collections.singletonMap("pretty", "true"));
				// GetEntity api will return content of response in form of json
				// in Http Entity
				HttpEntity entity = response.getEntity();
				ObjectMapper jacksonObjectMapper = new ObjectMapper();
				// Map json response to Java object in IndexInfo Array
				// Cluster Info
				indexArr = jacksonObjectMapper.readValue(entity.getContent(), IndexInfo[].class);
				for(IndexInfo indexInfo:indexArr)
				{
				System.out.println(indexInfo);
			    }
			}

		} catch (Exception ex) {
			System.out.println("Exception found while getting cluster detail");
			ex.printStackTrace();
		} finally {
			closeConnnection(client);
		}

	}

	// Get Rest client connection
	private static RestClient openConnection() {
		RestClient client = null;
		try {
			final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
			credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("userid", "password"));
			client = RestClient.builder(new HttpHost("elasticHost", Integer.parseInt("9200")))
					.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
						// Customize connection as per requirement
						public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
							return httpClientBuilder
									// Credentials
									.setDefaultCredentialsProvider(credentialsProvider)
									// Proxy
									.setProxy(new HttpHost("proxyServer", 8080));

						}
					}).setMaxRetryTimeoutMillis(60000).build();

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return client;
	}

	// Close Open connection
	private static void closeConnnection(RestClient client) {
		if (client != null) {
			try {
				client.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

}

Index Info Object where JSON index detail will map

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class IndexInfo {
@JsonProperty(value = "health")
private String health;
@JsonProperty(value = "index")
private String indexName;
@JsonProperty(value = "status")
private String status;
@JsonProperty(value = "pri")
private int shards;
@JsonProperty(value = "rep")
private int replica;
@JsonProperty(value = "pri.store.size")
private String dataSize;
@JsonProperty(value = "store.size")
private String totalDataSize;
@JsonProperty(value = "docs.count")
private String documentCount;

@Override
public String toString()
{
	StringBuffer str=new StringBuffer(60);
	str.append("{\n");
	str.append("    \"").append("indexName").append("\":\"").append(indexName).append("\",\n");
	str.append("    \"").append("health").append("\":\"").append(health).append("\",\n");
	str.append("    \"").append("status").append("\":\"").append(status).append("\",\n");
	str.append("    \"").append("shards").append("\":\"").append(shards).append("\",\n");
	str.append("    \"").append("replica").append("\":\"").append(replica).append("\",\n");
	str.append("    \"").append("dataSize").append("\":\"").append(dataSize).append("\",\n");
	str.append("    \"").append("totalDataSize").append("\":\"").append(totalDataSize).append("\",\n");
	str.append("    \"").append("documentCount").append("\":\"").append(documentCount).append("\"\n");
	str.append("    \"");
	return str.toString();
}
public String getIndexName() {
	return indexName;
}
public void setIndexName(String indexName) {
	this.indexName = indexName;
}
public int getShards() {
	return shards;
}
public void setShards(int shards) {
	this.shards = shards;
}
public int getReplica() {
	return replica;
}
public void setReplica(int replica) {
	this.replica = replica;
}
public String getDataSize() {
	return dataSize;
}
public void setDataSize(String dataSize) {
	this.dataSize = dataSize;
}
public String getTotalDataSize() {
	return totalDataSize;
}
public void setTotalDataSize(String totalDataSize) {
	this.totalDataSize = totalDataSize;
}
public String getDocumentCount() {
	return documentCount;
}
public void setDocumentCount(String documentCount) {
	this.documentCount = documentCount;
}
public String getStatus() {
	return status;
}
public void setStatus(String status) {
	this.status = status;
}
public String getHealth() {
	return health;
}
public void setHealth(String health) {
	this.health = health;
}
}

Read More on Elasticsearch REST

Integration

Integrate Filebeat, Kafka, Logstash, Elasticsearch and Kibana

Elasticsearch REST JAVA Client for Cluster Detail


Below is example to get Cluster Detail in Java Object by using Elasticsearch REST Java client. Here client will call endpoint  “/_cluster/health” to retrieve all detail of index list. It is same as we use GET by CURL

GET http://elasticsearchHost:9200/_cluster/health

Pre-requisite

  • Minimum requirement for Java 7 version required.
  • Add below dependency for Elasticsearch REST and JSON Mapping in your pom.xml or add in your class path.

Dependency

<!--Elasticsearch REST jar-->
<dependency>
			<groupId>org.elasticsearch.client</groupId>
			<artifactId>rest</artifactId>
			<version>5.1.2</version>
</dependency>
<!--Jackson jar for mapping json to Java -->
<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.8.5</version>
</dependency>

Sample Code

import java.io.IOException;
import java.util.Collections;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

import com.fasterxml.jackson.databind.ObjectMapper;

public class ElasticsearchRESTClusterClient {

	public static void main(String[] args) {
		ClusterInfo clusterHealth = null;
		RestClient client = null;
		try {
			client = openConnection();
			if (client != null) {
				// performRequest GET method will retrieve all cluster health
				// information from elastic server
				Response response = client.performRequest("GET", "/_cluster/health",
						Collections.singletonMap("pretty", "true"));
				// GetEntity api will return content of response in form of json
				// in Http Entity
				HttpEntity entity = response.getEntity();
				ObjectMapper jacksonObjectMapper = new ObjectMapper();
				// Map json response to Java object in ClusterInfo
				// Cluster Info
				clusterHealth = jacksonObjectMapper.readValue(entity.getContent(), ClusterInfo.class);
				System.out.println(clusterHealth);
			}

		} catch (Exception ex) {
			System.out.println("Exception found while getting cluster detail");
			ex.printStackTrace();
		} finally {
			closeConnnection(client);
		}

	}

	// Get Rest client connection
	private static RestClient openConnection() {
		RestClient client = null;
		try {
			final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
			credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("userId", "password"));
			client = RestClient.builder(new HttpHost("elasticHost", Integer.parseInt("9200")))
					.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
						// Customize connection as per requirement
						public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
							return httpClientBuilder
									// Credentials
									.setDefaultCredentialsProvider(credentialsProvider)
									// Proxy
									.setProxy(new HttpHost("ProxyServer", 8080));

						}
					}).setMaxRetryTimeoutMillis(60000).build();

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return client;
	}

	// Close Open connection
	private static void closeConnnection(RestClient client) {
		if (client != null) {
			try {
				client.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

}

Cluster Info Java Object where retrieve json response will map.

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class ClusterInfo {

@JsonProperty(value = "cluster_name")
private String clusterName;
@JsonProperty(value = "status")
private String clusterStatus;
@JsonProperty(value = "active_primary_shards")
private int primaryActiveShards;
@JsonProperty(value = "active_shards")
private int activeShards;
@JsonProperty(value = "delayed_unassigned_shards")
private int delayedUnAssignedShards;
@JsonProperty(value = "unassigned_shards")
private int unAssignedShards;
@JsonProperty(value = "initializing_shards")
private int initializingShards;
@JsonProperty(value = "relocating_shards")
private int relocatingShards;
@JsonProperty(value = "number_of_nodes")
private int totalNodeCount;
@JsonProperty(value = "number_of_data_nodes")
private int dataNodeCount;

@Override
public String toString()
{
	StringBuffer str=new StringBuffer(60);
	str.append("{\n");
	str.append("    \"").append("clusterName").append("\":\"").append(clusterName).append("\",\n");
	str.append("    \"").append("clusterStatus").append("\":\"").append(clusterStatus).append("\",\n");
	str.append("    \"").append("primaryActiveShards").append("\":\"").append(primaryActiveShards).append("\",\n");
	str.append("    \"").append("activeShards").append("\":\"").append(activeShards).append("\",\n");
	str.append("    \"").append("delayedUnAssignedShards").append("\":\"").append(delayedUnAssignedShards).append("\",\n");
	str.append("    \"").append("unAssignedShards").append("\":\"").append(unAssignedShards).append("\",\n");
	str.append("    \"").append("initializingShards").append("\":\"").append(initializingShards).append("\",\n");
	str.append("    \"").append("relocatingShards").append("\":\"").append(relocatingShards).append("\",\n");
	str.append("    \"").append("totalNodeCount").append("\":\"").append(totalNodeCount).append("\",\n");
	str.append("    \"").append("dataNode").append("\":\"").append(dataNodeCount).append("\"");
	str.append("    \"");
	return str.toString();
}

public String getClusterName() {
	return clusterName;
}
public void setClusterName(String clusterName) {
	this.clusterName = clusterName;
}
public String getClusterStatus() {
	return clusterStatus;
}
public void setClusterStatus(String clusterStatus) {
	this.clusterStatus = clusterStatus;
}
public int getPrimaryActiveShards() {
	return primaryActiveShards;
}
public void setPrimaryActiveShards(int primaryActiveShards) {
	this.primaryActiveShards = primaryActiveShards;
}
public int getActiveShards() {
	return activeShards;
}
public void setActiveShards(int activeShards) {
	this.activeShards = activeShards;
}
public int getDelayedUnAssignedShards() {
	return delayedUnAssignedShards;
}
public void setDelayedUnAssignedShards(int delayedUnAssignedShards) {
	this.delayedUnAssignedShards = delayedUnAssignedShards;
}
public int getUnAssignedShards() {
	return unAssignedShards;
}
public void setUnAssignedShards(int unAssignedShards) {
	this.unAssignedShards = unAssignedShards;
}
public int getInitializingShards() {
	return initializingShards;
}
public void setInitializingShards(int initializingShards) {
	this.initializingShards = initializingShards;
}
public int getRelocatingShards() {
	return relocatingShards;
}
public void setRelocatingShards(int relocatingShards) {
	this.relocatingShards = relocatingShards;
}
public int getDataNodeCount() {
	return dataNodeCount;
}
public void setDataNodeCount(int dataNodeCount) {
	this.dataNodeCount = dataNodeCount;
}
public int getTotalNodeCount() {
	return totalNodeCount;
}
public void setTotalNodeCount(int totalNodeCount) {
	this.totalNodeCount = totalNodeCount;
}
}

Read More on Elasticsearch REST

Integration

Integrate Filebeat, Kafka, Logstash, Elasticsearch and Kibana