text,length,is_long_context,metric_val,label_metric
"[[cluster-nodes-stats]]
=== Nodes stats API
++++
Nodes stats
++++
Returns cluster nodes statistics.
[[cluster-nodes-stats-api-request]]
==== {api-request-title}
`GET /_nodes/stats` +
`GET /_nodes//stats` +
`GET/_nodes/stats/` +
`GET/_nodes//stats/` +
`GET /_nodes/stats//` +
`GET /_nodes//stats//`
[[cluster-nodes-stats-api-desc]]
==== {api-description-title}
You can use the cluster nodes stats API to retrieve statistics for nodes in a cluster.
All the nodes selective options are explained <>.
By default, all stats are returned. You can limit the returned information by
using metrics.
[[cluster-nodes-stats-api-path-params]]
==== {api-path-parms-title}
``::
(Optional, string) Limits the information returned to the specific metrics.
A comma-separated list of the following options:
+
--
`adaptive_selection`::
Statistics about <>.
`breaker`::
Statistics about the field data circuit breaker.
`discovery`::
Statistics about the discovery.
`fs`::
File system information, data path, free disk space, read/write
stats.
`http`::
HTTP connection information.
`indexing_pressure`::
Statistics about the node's indexing load and related rejections.
`indices`::
Indices stats about size, document count, indexing and deletion times,
search times, field cache size, merges and flushes.
`ingest`::
Statistics about ingest preprocessing.
`jvm`::
JVM stats, memory pool information, garbage collection, buffer
pools, number of loaded/unloaded classes.
`os`::
Operating system stats, load average, mem, swap.
`process`::
Process statistics, memory consumption, cpu usage, open
file descriptors.
`thread_pool`::
Statistics about each thread pool, including current size, queue and
rejected tasks.
`transport`::
Transport statistics about sent and received bytes in cluster
communication.
--
``::
(Optional, string) Limit the information returned for `indices` metric to
the specific index metrics. It can be used only if `indices` (or `all`)
metric is specified. Supported metrics are:
+
--
* `completion`
* `docs`
* `fielddata`
* `flush`
* `get`
* `indexing`
* `merge`
* `query_cache`
* `recovery`
* `refresh`
* `request_cache`
* `search`
* `segments`
* `store`
* `translog`
* `warmer`
--
include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=node-id]
[[cluster-nodes-stats-api-query-params]]
==== {api-query-parms-title}
include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=completion-fields]
include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=fielddata-fields]
include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=fields]
include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=groups]
include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=level]
`types`::
(Optional, string) A comma-separated list of document types for the
`indexing` index metric.
include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=timeoutparms]
include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=include-segment-file-sizes]
[role=""child_attributes""]
[[cluster-nodes-stats-api-response-body]]
==== {api-response-body-title}
`_nodes`::
(object)
Contains statistics about the number of nodes selected by the request.
+
.Properties of `_nodes`
[%collapsible%open]
====
`total`::
(integer)
Total number of nodes selected by the request.
`successful`::
(integer)
Number of nodes that responded successfully to the request.
`failed`::
(integer)
Number of nodes that rejected the request or failed to respond. If this value
is not `0`, a reason for the rejection or failure is included in the response.
====
`cluster_name`::
(string)
Name of the cluster. Based on the <> setting.
`nodes`::
(object)
Contains statistics for the nodes selected by the request.
+
.Properties of `nodes`
[%collapsible%open]
====
``::
(object)
Contains statistics for the node.
+
.Properties of ``
[%collapsible%open]
=====
`timestamp`::
(integer)
Time the node stats were collected for this response. Recorded in milliseconds
since the {wikipedia}/Unix_time[Unix Epoch].
`name`::
(string)
Human-readable identifier for the node. Based on the <> setting.
`transport_address`::
(string)
Host and port for the <>, used for internal
communication between nodes in a cluster.
`host`::
(string)
Network host for the node, based on the <> setting.
`ip`::
(string)
IP address and port for the node.
`roles`::
(array of strings)
Roles assigned to the node. See <>.
`attributes`::
(object)
Contains a list of attributes for the node.
[[cluster-nodes-stats-api-response-body-indices]]
`indices`::
(object)
Contains statistics about indices with shards assigned to the node.
+
.Properties of `indices`
[%collapsible%open]
======
`docs`::
(object)
Contains statistics about documents across all primary shards assigned to the
node.
+
.Properties of `docs`
[%collapsible%open]
=======
`count`::
(integer)
include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=docs-count]
`deleted`::
(integer)
include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=docs-deleted]
=======
`store`::
(object)
Contains statistics about the size of shards assigned to the node.
+
.Properties of `store`
[%collapsible%open]
=======
`size`::
(<>)
Total size of all shards assigned to the node.
`size_in_bytes`::
(integer)
Total size, in bytes, of all shards assigned to the node.
`reserved`::
(<>)
A prediction of how much larger the shard stores on this node will eventually
grow due to ongoing peer recoveries, restoring snapshots, and similar
activities. A value of `-1b` indicates that this is not available.
`reserved_in_bytes`::
(integer)
A prediction, in bytes, of how much larger the shard stores on this node will
eventually grow due to ongoing peer recoveries, restoring snapshots, and
similar activities. A value of `-1` indicates that this is not available.
=======
`indexing`::
(object)
Contains statistics about indexing operations for the node.
+
.Properties of `indexing`
[%collapsible%open]
=======
`index_total`::
(integer)
Total number of indexing operations.
`index_time`::
(<>)
Total time spent performing indexing operations.
`index_time_in_millis`::
(integer)
Total time in milliseconds
spent performing indexing operations.
`index_current`::
(integer)
Number of indexing operations currently running.
`index_failed`::
(integer)
Number of failed indexing operations.
`delete_total`::
(integer)
Total number of deletion operations.
`delete_time`::
(<>)
Time spent performing deletion operations.
`delete_time_in_millis`::
(integer)
Time in milliseconds
spent performing deletion operations.
`delete_current`::
(integer)
Number of deletion operations currently running.
`noop_update_total`::
(integer)
Total number of noop operations.
`is_throttled`::
(boolean)
Number of times
operations were throttled.
`throttle_time`::
(<>)
Total time spent throttling operations.
`throttle_time_in_millis`::
(integer)
Total time in milliseconds
spent throttling operations.
=======
`get`::
(object)
Contains statistics about get operations for the node.
+
.Properties of `get`
[%collapsible%open]
=======
`total`::
(integer)
Total number of get operations.
`getTime`::
(<>)
Time spent performing get operations.
`time_in_millis`::
(integer)
Time in milliseconds
spent performing get operations.
`exists_total`::
(integer)
Total number of successful get operations.
`exists_time`::
(<>)
Time spent performing successful get operations.
`exists_time_in_millis`::
(integer)
Time in milliseconds
spent performing successful get operations.
`missing_total`::
(integer)
Total number of failed get operations.
`missing_time`::
(<>)
Time spent performing failed get operations.
`missing_time_in_millis`::
(integer)
Time in milliseconds
spent performing failed get operations.
`current`::
(integer)
Number of get operations currently running.
=======
`search`::
(object)
Contains statistics about search operations for the node.
+
.Properties of `search`
[%collapsible%open]
=======
`open_contexts`::
(integer)
Number of open search contexts.
`query_total`::
(integer)
Total number of query operations.
`query_time`::
(<>)
Time spent performing query operations.
`query_time_in_millis`::
(integer)
Time in milliseconds
spent performing query operations.
`query_current`::
(integer)
Number of query operations currently running.
`fetch_total`::
(integer)
Total number of fetch operations.
`fetch_time`::
(<>)
Time spent performing fetch operations.
`fetch_time_in_millis`::
(integer)
Time in milliseconds
spent performing fetch operations.
`fetch_current`::
(integer)
Number of fetch operations currently running.
`scroll_total`::
(integer)
Total number of scroll operations.
`scroll_time`::
(<>)
Time spent performing scroll operations.
`scroll_time_in_millis`::
(integer)
Time in milliseconds
spent performing scroll operations.
`scroll_current`::
(integer)
Number of scroll operations currently running.
`suggest_total`::
(integer)
Total number of suggest operations.
`suggest_time`::
(<>)
Time spent performing suggest operations.
`suggest_time_in_millis`::
(integer)
Time in milliseconds
spent performing suggest operations.
`suggest_current`::
(integer)
Number of suggest operations currently running.
=======
`merges`::
(object)
Contains statistics about merge operations for the node.
+
.Properties of `merges`
[%collapsible%open]
=======
`current`::
(integer)
Number of merge operations currently running.
`current_docs`::
(integer)
Number of document merges currently running.
`current_size`::
(<>)
Memory used performing current document merges.
`current_size_in_bytes`::
(integer)
Memory, in bytes, used performing current document merges.
`total`::
(integer)
Total number of merge operations.
`total_time`::
(<>)
Total time spent performing merge operations.
`total_time_in_millis`::
(integer)
Total time in milliseconds
spent performing merge operations.
`total_docs`::
(integer)
Total number of merged documents.
`total_size`::
(<>)
Total size of document merges.
`total_size_in_bytes`::
(integer)
Total size of document merges in bytes.
`total_stopped_time`::
(<>)
Total time spent stopping merge operations.
`total_stopped_time_in_millis`::
(integer)
Total time in milliseconds
spent stopping merge operations.
`total_throttled_time`::
(<>)
Total time spent throttling merge operations.
`total_throttled_time_in_millis`::
(integer)
Total time in milliseconds
spent throttling merge operations.
`total_auto_throttle`::
(<>)
Size of automatically throttled merge operations.
`total_auto_throttle_in_bytes`::
(integer)
Size, in bytes, of automatically throttled merge operations.
=======
`refresh`::
(object)
Contains statistics about refresh operations for the node.
+
.Properties of `refresh`
[%collapsible%open]
=======
`total`::
(integer)
Total number of refresh operations.
`total_time`::
(<>)
Total time spent performing refresh operations.
`total_time_in_millis`::
(integer)
Total time in milliseconds
spent performing refresh operations.
`external_total`::
(integer)
Total number of external refresh operations.
`external_total_time`::
(<>)
Total time spent performing external operations.
`external_total_time_in_millis`::
(integer)
Total time in milliseconds
spent performing external operations.
`listeners`::
(integer)
Number of refresh listeners.
=======
`flush`::
(object)
Contains statistics about flush operations for the node.
+
.Properties of `flush`
[%collapsible%open]
=======
`total`::
(integer)
Number of flush operations.
`periodic`::
(integer)
Number of flush periodic operations.
`total_time`::
(<>)
Total time spent performing flush operations.
`total_time_in_millis`::
(integer)
Total time in milliseconds
spent performing flush operations.
=======
`warmer`::
(object)
Contains statistics about index warming operations for the node.
+
.Properties of `warmer`
[%collapsible%open]
=======
`current`::
(integer)
Number of active index warmers.
`total`::
(integer)
Total number of index warmers.
`total_time`::
(<>)
Total time spent performing index warming operations.
`total_time_in_millis`::
(integer)
Total time in milliseconds
spent performing index warming operations.
=======
`query_cache`::
(object)
Contains statistics about the query cache across all shards assigned to the
node.
+
.Properties of `query_cache`
[%collapsible%open]
=======
`memory_size`::
(<>)
Total amount of memory used for the query cache across all shards assigned to
the node.
`memory_size_in_bytes`::
(integer)
Total amount of memory, in bytes, used for the query cache across all shards
assigned to the node.
`total_count`::
(integer)
Total count of hits, misses, and cached queries
in the query cache.
`hit_count`::
(integer)
Number of query cache hits.
`miss_count`::
(integer)
Number of query cache misses.
`cache_size`::
(integer)
Size, in bytes, of the query cache.
`cache_count`::
(integer)
Count of queries
in the query cache.
`evictions`::
(integer)
Number of query cache evictions.
=======
`fielddata`::
(object)
Contains statistics about the field data cache across all shards
assigned to the node.
+
.Properties of `fielddata`
[%collapsible%open]
=======
`memory_size`::
(<>)
Total amount of memory used for the field data cache across all shards
assigned to the node.
`memory_size_in_bytes`::
(integer)
Total amount of memory, in bytes, used for the field data cache across all
shards assigned to the node.
`evictions`::
(integer)
Number of fielddata evictions.
=======
`completion`::
(object)
Contains statistics about completions across all shards assigned to the node.
+
.Properties of `completion`
[%collapsible%open]
=======
`size`::
(<>)
Total amount of memory used for completion across all shards assigned to
the node.
`size_in_bytes`::
(integer)
Total amount of memory, in bytes, used for completion across all shards assigned
to the node.
=======
`segments`::
(object)
Contains statistics about segments across all shards assigned to the node.
+
.Properties of `segments`
[%collapsible%open]
=======
`count`::
(integer)
Number of segments.
`memory`::
(<>)
Total amount of memory used for segments across all shards assigned to the
node.
`memory_in_bytes`::
(integer)
Total amount of memory, in bytes, used for segments across all shards assigned
to the node.
`terms_memory`::
(<>)
Total amount of memory used for terms across all shards assigned to the node.
`terms_memory_in_bytes`::
(integer)
Total amount of memory, in bytes, used for terms across all shards assigned to
the node.
`stored_fields_memory`::
(<>)
Total amount of memory used for stored fields across all shards assigned to
the node.
`stored_fields_memory_in_bytes`::
(integer)
Total amount of memory, in bytes, used for stored fields across all shards
assigned to the node.
`term_vectors_memory`::
(<>)
Total amount of memory used for term vectors across all shards assigned to
the node.
`term_vectors_memory_in_bytes`::
(integer)
Total amount of memory, in bytes, used for term vectors across all shards
assigned to the node.
`norms_memory`::
(<>)
Total amount of memory used for normalization factors across all shards assigned
to the node.
`norms_memory_in_bytes`::
(integer)
Total amount of memory, in bytes, used for normalization factors across all
shards assigned to the node.
`points_memory`::
(<>)
Total amount of memory used for points across all shards assigned to the node.
`points_memory_in_bytes`::
(integer)
Total amount of memory, in bytes, used for points across all shards assigned to
the node.
`doc_values_memory`::
(<>)
Total amount of memory used for doc values across all shards assigned to
the node.
`doc_values_memory_in_bytes`::
(integer)
Total amount of memory, in bytes, used for doc values across all shards assigned
to the node.
`index_writer_memory`::
(<>)
Total amount of memory used by all index writers across all shards assigned to
the node.
`index_writer_memory_in_bytes`::
(integer)
Total amount of memory, in bytes, used by all index writers across all shards
assigned to the node.
`version_map_memory`::
(<>)
Total amount of memory used by all version maps across all shards assigned to
the node.
`version_map_memory_in_bytes`::
(integer)
Total amount of memory, in bytes, used by all version maps across all shards
assigned to the node.
`fixed_bit_set`::
(<>)
Total amount of memory used by fixed bit sets across all shards assigned to
the node.
+
Fixed bit sets are used for nested object field types and
type filters for <> fields.
`fixed_bit_set_memory_in_bytes`::
(integer)
Total amount of memory, in bytes, used by fixed bit sets across all shards
assigned to the node.
+
Fixed bit sets are used for nested object field types and
type filters for <> fields.
`max_unsafe_auto_id_timestamp`::
(integer)
Time of the most recently retried indexing request. Recorded in milliseconds
since the {wikipedia}/Unix_time[Unix Epoch].
`file_sizes`::
(object)
Contains statistics about the size of the segment file.
+
.Properties of `file_sizes`
[%collapsible%open]
========
`size`::
(<>)
Size of the segment file.
`size_in_bytes`::
(integer)
Size, in bytes,
of the segment file.
`description`::
(string)
Description of the segment file.
========
=======
`translog`::
(object)
Contains statistics about transaction log operations for the node.
+
.Properties of `translog`
[%collapsible%open]
=======
`operations`::
(integer)
Number of transaction log operations.
`size`::
(<>)
Size of the transaction log.
`size_in_bytes`::
(integer)
Size, in bytes, of the transaction log.
`uncommitted_operations`::
(integer)
Number of uncommitted transaction log operations.
`uncommitted_size`::
(<>)
Size of uncommitted transaction log operations.
`uncommitted_size_in_bytes`::
(integer)
Size, in bytes, of uncommitted transaction log operations.
`earliest_last_modified_age`::
(integer)
Earliest last modified age
for the transaction log.
=======
`request_cache`::
(object)
Contains statistics about the request cache across all shards assigned to the
node.
+
.Properties of `request_cache`
[%collapsible%open]
=======
`memory_size`::
(<>)
Memory used by the request cache.
`memory_size_in_bytes`::
(integer)
Memory, in bytes, used by the request cache.
`evictions`::
(integer)
Number of request cache operations.
`hit_count`::
(integer)
Number of request cache hits.
`miss_count`::
(integer)
Number of request cache misses.
=======
`recovery`::
(object)
Contains statistics about recovery operations for the node.
+
.Properties of `recovery`
[%collapsible%open]
=======
`current_as_source`::
(integer)
Number of recoveries
that used an index shard as a source.
`current_as_target`::
(integer)
Number of recoveries
that used an index shard as a target.
`throttle_time`::
(<>)
Time by which recovery operations were delayed due to throttling.
`throttle_time_in_millis`::
(integer)
Time in milliseconds
recovery operations were delayed due to throttling.
=======
======
[[cluster-nodes-stats-api-response-body-os]]
`os`::
(object)
Contains statistics about the operating system for the node.
+
.Properties of `os`
[%collapsible%open]
======
`timestamp`::
(integer)
Last time the operating system statistics were refreshed. Recorded in
milliseconds since the {wikipedia}/Unix_time[Unix Epoch].
`cpu`::
(object)
Contains statistics about CPU usage for the node.
+
.Properties of `cpu`
[%collapsible%open]
=======
`percent`::
(integer)
Recent CPU usage for the whole system, or `-1` if not supported.
`load_average`::
(object)
Contains statistics about load averages on the system.
+
.Properties of `load_average`
[%collapsible%open]
========
`1m`::
(float)
One-minute load average on the system (field is not present if one-minute load
average is not available).
`5m`::
(float)
Five-minute load average on the system (field is not present if five-minute load
average is not available).
`15m`::
(float)
Fifteen-minute load average on the system (field is not present if
fifteen-minute load average is not available).
========
=======
`mem`::
(object)
Contains statistics about memory usage for the node.
+
.Properties of `mem`
[%collapsible%open]
=======
`total`::
(<>)
Total amount of physical memory.
`total_in_bytes`::
(integer)
Total amount of physical memory in bytes.
`free`::
(<>)
Amount of free physical memory.
`free_in_bytes`::
(integer)
Amount of free physical memory in bytes.
`used`::
(<>)
Amount of used physical memory.
`used_in_bytes`::
(integer)
Amount of used physical memory in bytes.
`free_percent`::
(integer)
Percentage of free memory.
`used_percent`::
(integer)
Percentage of used memory.
=======
`swap`::
(object)
Contains statistics about swap space for the node.
+
.Properties of `swap`
[%collapsible%open]
=======
`total`::
(<>)
Total amount of swap space.
`total_in_bytes`::
(integer)
Total amount of swap space in bytes.
`free`::
(<>)
Amount of free swap space.
`free_in_bytes`::
(integer)
Amount of free swap space in bytes.
`used`::
(<>)
Amount of used swap space.
`used_in_bytes`::
(integer)
Amount of used swap space in bytes.
=======
`cgroup` (Linux only)::
(object)
Contains cgroup statistics for the node.
+
NOTE: For the cgroup stats to be visible, cgroups must be compiled into the
kernel, the `cpu` and `cpuacct` cgroup subsystems must be configured and stats
must be readable from `/sys/fs/cgroup/cpu` and `/sys/fs/cgroup/cpuacct`.
+
.Properties of `cgroup`
[%collapsible%open]
=======
`cpuacct` (Linux only)::
(object)
Contains statistics about `cpuacct` control group for the node.
+
.Properties of `cpuacct`
[%collapsible%open]
========
`control_group` (Linux only)::
(string)
The `cpuacct` control group to which the {es} process belongs.
`usage_nanos` (Linux only)::
(integer)
The total CPU time (in nanoseconds) consumed by all tasks in the same cgroup
as the {es} process.
========
`cpu` (Linux only)::
(object)
Contains statistics about `cpu` control group for the node.
+
.Properties of `cpu`
[%collapsible%open]
========
`control_group` (Linux only)::
(string)
The `cpu` control group to which the {es} process belongs.
`cfs_period_micros` (Linux only)::
(integer)
The period of time (in microseconds) for how regularly all tasks in the same
cgroup as the {es} process should have their access to CPU resources
reallocated.
`cfs_quota_micros` (Linux only)::
(integer)
The total amount of time (in microseconds) for which all tasks in
the same cgroup as the {es} process can run during one period
`cfs_period_micros`.
`stat` (Linux only)::
(object)
Contains CPU statistics for the node.
+
.Properties of `stat`
[%collapsible%open]
=========
`number_of_elapsed_periods` (Linux only)::
(integer)
The number of reporting periods (as specified by
`cfs_period_micros`) that have elapsed.
`number_of_times_throttled` (Linux only)::
(integer)
The number of times all tasks in the same cgroup as the {es} process have
been throttled.
`time_throttled_nanos` (Linux only)::
(integer)
The total amount of time (in nanoseconds) for which all tasks in the same
cgroup as the {es} process have been throttled.
=========
========
`memory` (Linux only)::
(object)
Contains statistics about the `memory` control group for the node.
+
.Properties of `memory`
[%collapsible%open]
========
`control_group` (Linux only)::
(string)
The `memory` control group to which the {es} process belongs.
`limit_in_bytes` (Linux only)::
(string)
The maximum amount of user memory (including file cache) allowed for all
tasks in the same cgroup as the {es} process. This value can be too big to
store in a `long`, so is returned as a string so that the value returned can
exactly match what the underlying operating system interface returns. Any
value that is too large to parse into a `long` almost certainly means no
limit has been set for the cgroup.
`usage_in_bytes` (Linux only)::
(string)
The total current memory usage by processes in the cgroup (in bytes) by all
tasks in the same cgroup as the {es} process. This value is stored as a
string for consistency with `limit_in_bytes`.
========
=======
======
[[cluster-nodes-stats-api-response-body-process]]
`process`::
(object)
Contains process statistics for the node.
+
.Properties of `process`
[%collapsible%open]
======
`timestamp`::
(integer)
Last time the statistics were refreshed. Recorded in milliseconds
since the {wikipedia}/Unix_time[Unix Epoch].
`open_file_descriptors`::
(integer)
Number of opened file descriptors associated with the current or
`-1` if not supported.
`max_file_descriptors`::
(integer)
Maximum number of file descriptors allowed on the system, or `-1` if not
supported.
`cpu`::
(object)
Contains CPU statistics for the node.
+
.Properties of `cpu`
[%collapsible%open]
=======
`percent`::
(integer)
CPU usage in percent, or `-1` if not known at the time the stats are
computed.
`total`::
(<>)
CPU time used by the process on which the Java virtual machine is running.
`total_in_millis`::
(integer)
CPU time (in milliseconds) used by the process on which the Java virtual
machine is running, or `-1` if not supported.
=======
`mem`::
(object)
Contains virtual memory statistics for the node.
+
.Properties of `mem`
[%collapsible%open]
=======
`total_virtual`::
(<>)
Size of virtual memory that is guaranteed to be available to the
running process.
`total_virtual_in_bytes`::
(integer)
Size in bytes of virtual memory that is guaranteed to be available to the
running process.
=======
======
[[cluster-nodes-stats-api-response-body-jvm]]
`jvm`::
(object)
Contains Java Virtual Machine (JVM) statistics for the node.
+
.Properties of `jvm`
[%collapsible%open]
======
`timestamp`::
(integer)
Last time JVM statistics were refreshed.
`uptime`::
(<>)
JVM uptime.
`uptime_in_millis`::
(integer)
JVM uptime in milliseconds.
`mem`::
(object)
Contains JVM memory usage statistics for the node.
+
.Properties of `mem`
[%collapsible%open]
=======
`heap_used`::
(<>)
Memory currently in use by the heap.
`heap_used_in_bytes`::
(integer)
Memory, in bytes, currently in use by the heap.
`heap_used_percent`::
(integer)
Percentage of memory currently in use by the heap.
`heap_committed`::
(<>)
Amount of memory available for use by the heap.
`heap_committed_in_bytes`::
(integer)
Amount of memory, in bytes, available for use by the heap.
`heap_max`::
(<>)
Maximum amount of memory available for use by the heap.
`heap_max_in_bytes`::
(integer)
Maximum amount of memory, in bytes, available for use by the heap.
`non_heap_used`::
(<>)
Non-heap memory used.
`non_heap_used_in_bytes`::
(integer)
Non-heap memory used, in bytes.
`non_heap_committed`::
(<>)
Amount of non-heap memory available.
`non_heap_committed_in_bytes`::
(integer)
Amount of non-heap memory available, in bytes.
`pools`::
(object)
Contains statistics about heap memory usage for the node.
+
.Properties of `pools`
[%collapsible%open]
========
`young`::
(object)
Contains statistics about memory usage by the young generation heap for the
node.
+
.Properties of `young`
[%collapsible%open]
=========
`used`::
(<>)
Memory used by the young generation heap.
`used_in_bytes`::
(integer)
Memory, in bytes, used by the young generation heap.
`max`::
(<>)
Maximum amount of memory available for use by the young generation heap.
`max_in_bytes`::
(integer)
Maximum amount of memory, in bytes, available for use by the young generation
heap.
`peak_used`::
(<>)
Largest amount of memory historically used by the young generation heap.
`peak_used_in_bytes`::
(integer)
Largest amount of memory, in bytes, historically used by the young generation
heap.
`peak_max`::
(<>)
Largest amount of memory historically used by the young generation heap.
`peak_max_in_bytes`::
(integer)
Largest amount of memory, in bytes, historically used by the young generation
heap.
=========
`survivor`::
(object)
Contains statistics about memory usage by the survivor space for the node.
+
.Properties of `survivor`
[%collapsible%open]
=========
`used`::
(<>)
Memory used by the survivor space.
`used_in_bytes`::
(integer)
Memory, in bytes, used by the survivor space.
`max`::
(<>)
Maximum amount of memory available for use by the survivor space.
`max_in_bytes`::
(integer)
Maximum amount of memory, in bytes, available for use by the survivor space.
`peak_used`::
(<>)
Largest amount of memory historically used by the survivor space.
`peak_used_in_bytes`::
(integer)
Largest amount of memory, in bytes, historically used by the survivor space.
`peak_max`::
(<>)
Largest amount of memory historically used by the survivor space.
`peak_max_in_bytes`::
(integer)
Largest amount of memory, in bytes, historically used by the survivor space.
=========
`old`::
(object)
Contains statistics about memory usage by the old generation heap for the node.
+
.Properties of `old`
[%collapsible%open]
=========
`used`::
(<>)
Memory used by the old generation heap.
`used_in_bytes`::
(integer)
Memory, in bytes, used by the old generation heap.
`max`::
(<>)
Maximum amount of memory available for use by the old generation heap.
`max_in_bytes`::
(integer)
Maximum amount of memory, in bytes, available for use by the old generation
heap.
`peak_used`::
(<>)
Largest amount of memory historically used by the old generation heap.
`peak_used_in_bytes`::
(integer)
Largest amount of memory, in bytes, historically used by the old generation
heap.
`peak_max`::
(<>)
Highest memory limit historically available for use by the old generation heap.
`peak_max_in_bytes`::
(integer)
Highest memory limit, in bytes, historically available for use by the old
generation heap.
=========
========
=======
`threads`::
(object)
Contains statistics about JVM thread usage for the node.
+
.Properties of `threads`
[%collapsible%open]
=======
`count`::
(integer)
Number of active threads in use by JVM.
`peak_count`::
(integer)
Highest number of threads used by JVM.
=======
`gc`::
(object)
Contains statistics about JVM garbage collectors for the node.
+
.Properties of `gc`
[%collapsible%open]
=======
`collectors`::
(object)
Contains statistics about JVM garbage collectors for the node.
+
.Properties of `collectors`
[%collapsible%open]
========
`young`::
(object)
Contains statistics about JVM garbage collectors that collect young generation
objects for the node.
+
.Properties of `young`
[%collapsible%open]
=========
`collection_count`::
(integer)
Number of JVM garbage collectors that collect young generation objects.
`collection_time`::
(<>)
Total time spent by JVM collecting young generation objects.
`collection_time_in_millis`::
(integer)
Total time in milliseconds spent by JVM collecting young generation objects.
=========
`old`::
(object)
Contains statistics about JVM garbage collectors that collect old generation
objects for the node.
+
.Properties of `old`
[%collapsible%open]
=========
`collection_count`::
(integer)
Number of JVM garbage collectors that collect old generation objects.
`collection_time`::
(<>)
Total time spent by JVM collecting old generation objects.
`collection_time_in_millis`::
(integer)
Total time in milliseconds spent by JVM collecting old generation objects.
=========
========
=======
`buffer_pools`::
(object)
Contains statistics about JVM buffer pools for the node.
+
.Properties of `buffer_pools`
[%collapsible%open]
=======
`mapped`::
(object)
Contains statistics about mapped JVM buffer pools for the node.
+
.Properties of `mapped`
[%collapsible%open]
========
`count`::
(integer)
Number of mapped buffer pools.
`used`::
(<>)
Size of mapped buffer pools.
`used_in_bytes`::
(integer)
Size, in bytes, of mapped buffer pools.
`total_capacity`::
(<>)
Total capacity of mapped buffer pools.
`total_capacity_in_bytes`::
(integer)
Total capacity, in bytes, of mapped buffer pools.
========
`direct`::
(object)
Contains statistics about direct JVM buffer pools for the node.
+
.Properties of `direct`
[%collapsible%open]
========
`count`::
(integer)
Number of direct buffer pools.
`used`::
(<>)
Size of direct buffer pools.
`used_in_bytes`::
(integer)
Size, in bytes, of direct buffer pools.
`total_capacity`::
(<>)
Total capacity of direct buffer pools.
`total_capacity_in_bytes`::
(integer)
Total capacity, in bytes, of direct buffer pools.
========
=======
`classes`::
(object)
Contains statistics about classes loaded by JVM for the node.
+
.Properties of `classes`
[%collapsible%open]
=======
`current_loaded_count`::
(integer)
Number of classes currently loaded by JVM.
`total_loaded_count`::
(integer)
Total number of classes loaded since the JVM started.
`total_unloaded_count`::
(integer)
Total number of classes unloaded since the JVM started.
=======
======
[[cluster-nodes-stats-api-response-body-threadpool]]
`thread_pool`::
(object)
Contains thread pool statistics for the node
+
.Properties of `thread_pool`
[%collapsible%open]
======
``::
(object)
Contains statistics about the thread pool for the node.
+
.Properties of ``
[%collapsible%open]
=======
`threads`::
(integer)
Number of threads in the thread pool.
`queue`::
(integer)
Number of tasks in queue for the thread pool.
`active`::
(integer)
Number of active threads in the thread pool.
`rejected`::
(integer)
Number of tasks rejected by the thread pool executor.
`largest`::
(integer)
Highest number of active threads in the thread pool.
`completed`::
(integer)
Number of tasks completed by the thread pool executor.
=======
======
[[cluster-nodes-stats-api-response-body-fs]]
`fs`::
(object)
Contains file store statistics for the node.
+
.Properties of `fs`
[%collapsible%open]
======
`timestamp`::
(integer)
Last time the file stores statistics were refreshed. Recorded in
milliseconds since the {wikipedia}/Unix_time[Unix Epoch].
`total`::
(object)
Contains statistics for all file stores of the node.
+
.Properties of `total`
[%collapsible%open]
=======
`total`::
(<>)
Total size of all file stores.
`total_in_bytes`::
(integer)
Total size (in bytes) of all file stores.
`free`::
(<>)
Total unallocated disk space in all file stores.
`free_in_bytes`::
(integer)
Total number of unallocated bytes in all file stores.
`available`::
(<>)
Total disk space available to this Java virtual machine on all file
stores. Depending on OS or process level restrictions, this might appear
less than `free`. This is the actual amount of free disk
space the {es} node can utilise.
`available_in_bytes`::
(integer)
Total number of bytes available to this Java virtual machine on all file
stores. Depending on OS or process level restrictions, this might appear
less than `free_in_bytes`. This is the actual amount of free disk
space the {es} node can utilise.
=======
`least_usage_estimate`::
(object)
Contains statistics for the file store with the least estimated usage. See
<> for a list of child parameters.
`most_usage_estimate`::
(object)
Contains statistics for the file store with the most estimated usage. See
<> for a list of child parameters.
[[cluster-nodes-stats-fs-data]]
`data`::
(array of objects)
List of all file stores.
+
.Properties of `data`
[%collapsible%open]
=======
`path`::
(string)
Path to the file store.
`mount`::
(string)
Mount point of the file store (ex: /dev/sda2).
+
NOTE: This parameter is not provided for the `least_usage_estimate` or
`most_usage_estimate` file stores.
`type`::
(string)
Type of the file store (ex: ext4).
`total`::
(<>)
Total size of the file store.
`total_in_bytes`::
(integer)
Total size (in bytes) of the file store.
`free`::
(<>)
Total amount of unallocated disk space in the file store.
`free_in_bytes`::
(integer)
Total number of unallocated bytes in the file store.
`available`::
(<>)
Total amount of disk space available to this Java virtual machine on this file
store.
`available_in_bytes`::
(integer)
Total number of bytes available to this Java virtual machine on this file
store.
=======
`io_stats` (Linux only)::
(objects)
Contains I/O statistics for the node.
+
.Properties of `io_stats`
[%collapsible%open]
=======
`devices` (Linux only)::
(array)
Array of disk metrics for each device that is backing an {es} data path.
These disk metrics are probed periodically and averages between the last
probe and the current probe are computed.
+
.Properties of `devices`
[%collapsible%open]
========
`device_name` (Linux only)::
(string)
The Linux device name.
`operations` (Linux only)::
(integer)
The total number of read and write operations for the device completed since
starting {es}.
`read_operations` (Linux only)::
(integer)
The total number of read operations for the device completed since starting
{es}.
`write_operations` (Linux only)::
(integer)
The total number of write operations for the device completed since starting
{es}.
`read_kilobytes` (Linux only)::
(integer)
The total number of kilobytes read for the device since starting {es}.
`write_kilobytes` (Linux only)::
(integer)
The total number of kilobytes written for the device since starting {es}.
========
`operations` (Linux only)::
(integer)
The total number of read and write operations across all devices used by
{es} completed since starting {es}.
`read_operations` (Linux only)::
(integer)
The total number of read operations for across all devices used by {es}
completed since starting {es}.
`write_operations` (Linux only)::
(integer)
The total number of write operations across all devices used by {es}
completed since starting {es}.
`read_kilobytes` (Linux only)::
(integer)
The total number of kilobytes read across all devices used by {es} since
starting {es}.
`write_kilobytes` (Linux only)::
(integer)
The total number of kilobytes written across all devices used by {es} since
starting {es}.
=======
======
[[cluster-nodes-stats-api-response-body-transport]]
`transport`::
(object)
Contains transport statistics for the node.
+
.Properties of `transport`
[%collapsible%open]
======
`server_open`::
(integer)
Number of open TCP connections used for internal communication between nodes.
`rx_count`::
(integer)
Total number of RX (receive) packets received by the node during internal
cluster communication.
`rx_size`::
(<>)
Size of RX packets received by the node during internal cluster communication.
`rx_size_in_bytes`::
(integer)
Size, in bytes, of RX packets received by the node during internal cluster
communication.
`tx_count`::
(integer)
Total number of TX (transmit) packets sent by the node during internal cluster
communication.
`tx_size`::
(<>)
Size of TX packets sent by the node during internal cluster communication.
`tx_size_in_bytes`::
(integer)
Size, in bytes, of TX packets sent by the node during internal cluster
communication.
======
[[cluster-nodes-stats-api-response-body-http]]
`http`::
(object)
Contains http statistics for the node.
+
.Properties of `http`
[%collapsible%open]
======
`current_open`::
(integer)
Current number of open HTTP connections for the node.
`total_opened`::
(integer)
Total number of HTTP connections opened for the node.
======
[[cluster-nodes-stats-api-response-body-breakers]]
`breakers`::
(object)
Contains circuit breaker statistics for the node.
+
.Properties of `breakers`
[%collapsible%open]
======
``::
(object)
Contains statistics for the circuit breaker.
+
.Properties of ``
[%collapsible%open]
=======
`limit_size_in_bytes`::
(integer)
Memory limit, in bytes, for the circuit breaker.
`limit_size`::
(<>)
Memory limit for the circuit breaker.
`estimated_size_in_bytes`::
(integer)
Estimated memory used, in bytes, for the operation.
`estimated_size`::
(<>)
Estimated memory used for the operation.
`overhead`::
(float)
A constant that all estimates for the circuit breaker are multiplied with to
calculate a final estimate.
`tripped`::
(integer)
Total number of times the circuit breaker has been triggered and prevented an
out of memory error.
=======
======
[[cluster-nodes-stats-api-response-body-script]]
`script`::
(object)
Contains script statistics for the node.
+
.Properties of `script`
[%collapsible%open]
======
`compilations`::
(integer)
Total number of inline script compilations performed by the node.
`cache_evictions`::
(integer)
Total number of times the script cache has evicted old data.
`compilation_limit_triggered`::
(integer)
Total number of times the <> circuit breaker has limited inline script compilations.
======
[[cluster-nodes-stats-api-response-body-discovery]]
`discovery`::
(object)
Contains node discovery statistics for the node.
+
.Properties of `discovery`
[%collapsible%open]
======
`cluster_state_queue`::
(object)
Contains statistics for the cluster state queue of the node.
+
.Properties of `cluster_state_queue`
[%collapsible%open]
=======
`total`::
(integer)
Total number of cluster states in queue.
`pending`::
(integer)
Number of pending cluster states in queue.
`committed`::
(integer)
Number of committed cluster states in queue.
=======
`published_cluster_states`::
(object)
Contains statistics for the published cluster states of the node.
+
.Properties of `published_cluster_states`
[%collapsible%open]
=======
`full_states`::
(integer)
Number of published cluster states.
`incompatible_diffs`::
(integer)
Number of incompatible differences between published cluster states.
`compatible_diffs`::
(integer)
Number of compatible differences between published cluster states.
=======
======
[[cluster-nodes-stats-api-response-body-ingest]]
`ingest`::
(object)
Contains ingest statistics for the node.
+
.Properties of `ingest`
[%collapsible%open]
======
`total`::
(object)
Contains statistics about ingest operations for the node.
+
.Properties of `total`
[%collapsible%open]
=======
`count`::
(integer)
Total number of documents ingested during the lifetime of this node.
`time`::
(<>)
Total time spent preprocessing ingest documents during the lifetime of this
node.
`time_in_millis`::
(integer)
Total time, in milliseconds, spent preprocessing ingest documents during the
lifetime of this node.
`current`::
(integer)
Total number of documents currently being ingested.
`failed`::
(integer)
Total number of failed ingest operations during the lifetime of this node.
=======
`pipelines`::
(object)
Contains statistics about ingest pipelines for the node.
+
.Properties of `pipelines`
[%collapsible%open]
=======
``::
(object)
Contains statistics about the ingest pipeline.
+
.Properties of ``
[%collapsible%open]
========
`count`::
(integer)
Number of documents preprocessed by the ingest pipeline.
`time`::
(<>)
Total time spent preprocessing documents in the ingest pipeline.
`time_in_millis`::
(integer)
Total time, in milliseconds, spent preprocessing documents in the ingest
pipeline.
`failed`::
(integer)
Total number of failed operations for the ingest pipeline.
`processors`::
(array of objects)
Contains statistics for the ingest processors for the ingest pipeline.
+
.Properties of `processors`
[%collapsible%open]
=========
``::
(object)
Contains statistics for the ingest processor.
+
.Properties of ``
[%collapsible%open]
==========
`count`::
(integer)
Number of documents transformed by the processor.
`time`::
(<>)
Time spent by the processor transforming documents.
`time_in_millis`::
(integer)
Time, in milliseconds, spent by the processor transforming documents.
`current`::
(integer)
Number of documents currently being transformed by the processor.
`failed`::
(integer)
Number of failed operations for the processor.
==========
=========
========
=======
======
[[cluster-nodes-stats-api-response-body-indexing-pressure]]
`indexing_pressure`::
(object)
Contains <> statistics for the node.
+
.Properties of `indexing_pressure`
[%collapsible%open]
======
`memory`::
(object)
Contains statistics for memory consumption from indexing load.
+
.Properties of ``
[%collapsible%open]
=======
`current`::
(object)
Contains statistics for current indexing load.
+
.Properties of ``
[%collapsible%open]
========
`combined_coordinating_and_primary`::
(<>)
Memory consumed by indexing requests in the coordinating or primary stage. This
value is not the sum of coordinating and primary as a node can reuse the
coordinating memory if the primary stage is executed locally.
`combined_coordinating_and_primary_in_bytes`::
(integer)
Memory consumed, in bytes, by indexing requests in the coordinating or primary
stage. This value is not the sum of coordinating and primary as a node can
reuse the coordinating memory if the primary stage is executed locally.
`coordinating`::
(<>)
Memory consumed by indexing requests in the coordinating stage.
`coordinating_in_bytes`::
(integer)
Memory consumed, in bytes, by indexing requests in the coordinating stage.
`primary`::
(<>)
Memory consumed by indexing requests in the primary stage.
`primary_in_bytes`::
(integer)
Memory consumed, in bytes, by indexing requests in the primary stage.
`replica`::
(<>)
Memory consumed by indexing requests in the replica stage.
`replica_in_bytes`::
(integer)
Memory consumed, in bytes, by indexing requests in the replica stage.
`all`::
(<>)
Memory consumed by indexing requests in the coordinating, primary, or replica stage.
`all_in_bytes`::
(integer)
Memory consumed, in bytes, by indexing requests in the coordinating, primary,
or replica stage.
========
`total`::
(object)
Contains statistics for the cumulative indexing load since the node started.
+
.Properties of ``
[%collapsible%open]
========
`combined_coordinating_and_primary`::
(<>)
Memory consumed by indexing requests in the coordinating or primary stage. This
value is not the sum of coordinating and primary as a node can reuse the
coordinating memory if the primary stage is executed locally.
`combined_coordinating_and_primary_in_bytes`::
(integer)
Memory consumed, in bytes, by indexing requests in the coordinating or primary
stage. This value is not the sum of coordinating and primary as a node can
reuse the coordinating memory if the primary stage is executed locally.
`coordinating`::
(<>)
Memory consumed by indexing requests in the coordinating stage.
`coordinating_in_bytes`::
(integer)
Memory consumed, in bytes, by indexing requests in the coordinating stage.
`primary`::
(<>)
Memory consumed by indexing requests in the primary stage.
`primary_in_bytes`::
(integer)
Memory consumed, in bytes, by indexing requests in the primary stage.
`replica`::
(<>)
Memory consumed by indexing requests in the replica stage.
`replica_in_bytes`::
(integer)
Memory consumed, in bytes, by indexing requests in the replica stage.
`all`::
(<>)
Memory consumed by indexing requests in the coordinating, primary, or replica stage.
`all_in_bytes`::
(integer)
Memory consumed, in bytes, by indexing requests in the coordinating, primary,
or replica stage.
`coordinating_rejections`::
(integer)
Number of indexing requests rejected in the coordinating stage.
`primary_rejections`::
(integer)
Number of indexing requests rejected in the primary stage.
`replica_rejections`::
(integer)
Number of indexing requests rejected in the replica stage.
========
=======
======
[[cluster-nodes-stats-api-response-body-adaptive-selection]]
`adaptive_selection`::
(object)
Contains adaptive selection statistics for the node.
+
.Properties of `adaptive_selection`
[%collapsible%open]
======
`outgoing_searches`::
(integer)
The number of outstanding search requests from the node these stats are for
to the keyed node.
`avg_queue_size`::
(integer)
The exponentially weighted moving average queue size of search requests on
the keyed node.
`avg_service_time`::
(<>)
The exponentially weighted moving average service time of search requests on
the keyed node.
`avg_service_time_ns`::
(integer)
The exponentially weighted moving average service time, in nanoseconds, of
search requests on the keyed node.
`avg_response_time`::
(<>)
The exponentially weighted moving average response time of search requests
on the keyed node.
`avg_response_time_ns`::
(integer)
The exponentially weighted moving average response time, in nanoseconds, of
search requests on the keyed node.
`rank`::
(string)
The rank of this node; used for shard selection when routing search
requests.
======
=====
====
[[cluster-nodes-stats-api-example]]
==== {api-examples-title}
[source,console]
--------------------------------------------------
# return just indices
GET /_nodes/stats/indices
# return just os and process
GET /_nodes/stats/os,process
# return just process for node with IP address 10.0.0.1
GET /_nodes/10.0.0.1/stats/process
--------------------------------------------------
All stats can be explicitly requested via `/_nodes/stats/_all` or
`/_nodes/stats?metric=_all`.
You can get information about indices stats on `node`, `indices`, or `shards`
level.
[source,console]
--------------------------------------------------
# Fielddata summarized by node
GET /_nodes/stats/indices/fielddata?fields=field1,field2
# Fielddata summarized by node and index
GET /_nodes/stats/indices/fielddata?level=indices&fields=field1,field2
# Fielddata summarized by node, index, and shard
GET /_nodes/stats/indices/fielddata?level=shards&fields=field1,field2
# You can use wildcards for field names
GET /_nodes/stats/indices/fielddata?fields=field*
--------------------------------------------------
You can get statistics about search groups for searches executed
on this node.
[source,console]
--------------------------------------------------
# All groups with all stats
GET /_nodes/stats?groups=_all
# Some groups from just the indices stats
GET /_nodes/stats/indices?groups=foo,bar
--------------------------------------------------
[[cluster-nodes-stats-ingest-ex]]
===== Retrieve ingest statistics only
To return only ingest-related node statistics, set the `` path
parameter to `ingest` and use the
<> query parameter.
[source,console]
--------------------------------------------------
GET /_nodes/stats/ingest?filter_path=nodes.*.ingest
--------------------------------------------------
You can use the `metric` and `filter_path` query parameters to get the same
response.
[source,console]
--------------------------------------------------
GET /_nodes/stats?metric=ingest&filter_path=nodes.*.ingest
--------------------------------------------------
To further refine the response, change the `filter_path` value.
For example, the following request only returns ingest pipeline statistics.
[source,console]
--------------------------------------------------
GET /_nodes/stats?metric=ingest&filter_path=nodes.*.ingest.pipelines
--------------------------------------------------
",12239,True,2561.3644551179395,median
"
CLASS unit_tests DEFINITION FOR TESTING
FINAL
DURATION SHORT
RISK LEVEL HARMLESS
.
*?
*?
*?
*?unit_Tests
*?
*?f_Cut
*?
*?ZZZCL_DATETIME
*?
*?
*?
*?
*?
*?
*?
*?
*?
PRIVATE SECTION.
METHODS: method_chaining FOR TESTING.
METHODS: add FOR TESTING.
METHODS: add_days FOR TESTING.
METHODS: add_hours FOR TESTING.
METHODS: add_minutes FOR TESTING.
METHODS: add_months FOR TESTING.
METHODS: add_seconds FOR TESTING.
METHODS: add_weeks FOR TESTING.
METHODS: add_years FOR TESTING.
METHODS: as_date FOR TESTING.
METHODS: as_iso_timestamp FOR TESTING.
METHODS: as_long_timestamp FOR TESTING.
METHODS: as_timestamp FOR TESTING.
METHODS: begin_of_day FOR TESTING.
METHODS: begin_of_month FOR TESTING.
METHODS: begin_of_quarter FOR TESTING.
METHODS: begin_of_week FOR TESTING.
METHODS: begin_of_year FOR TESTING.
METHODS: clone FOR TESTING.
METHODS: day_of_week FOR TESTING.
METHODS: end_of_day FOR TESTING.
METHODS: end_of_month FOR TESTING.
METHODS: end_of_quarter FOR TESTING.
METHODS: end_of_week FOR TESTING.
METHODS: end_of_year FOR TESTING.
METHODS: from_date FOR TESTING.
METHODS: from_iso_timestamp FOR TESTING.
METHODS: from_now FOR TESTING.
METHODS: from_today FOR TESTING.
METHODS: get_dayname FOR TESTING.
METHODS: get_day_of_week FOR TESTING.
METHODS: get_day_of_year FOR TESTING.
METHODS: get_ultimo FOR TESTING.
METHODS: get_number_of_days_of_month FOR TESTING.
METHODS: get_number_of_days_of_year FOR TESTING.
METHODS: is_last_day_of_month FOR TESTING.
METHODS: set FOR TESTING.
METHODS: subtract FOR TESTING.
METHODS: get_quarter FOR TESTING.
METHODS: get_iso_week FOR TESTING.
METHODS: is_leap_year FOR TESTING.
METHODS: is_before FOR TESTING.
METHODS: is_before_or_equal FOR TESTING.
METHODS: is_after FOR TESTING.
METHODS: is_after_or_equal FOR TESTING.
METHODS: is_equal FOR TESTING.
METHODS: create_list FOR TESTING.
METHODS: sub_days FOR TESTING.
METHODS: sub_hours FOR TESTING.
METHODS: sub_minutes FOR TESTING.
METHODS: sub_months FOR TESTING.
METHODS: sub_seconds FOR TESTING.
METHODS: sub_weeks FOR TESTING.
METHODS: sub_years FOR TESTING.
METHODS: diff FOR TESTING.
ENDCLASS. ""unit_Tests
CLASS unit_tests IMPLEMENTATION.
METHOD method_chaining.
DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ).
o_datetime->add_days( 3
)->add_hours( 12
)->add_minutes( 30
)->add_seconds( 45
)->add_weeks( 2
)->add_months( 3
)->add_years( 3 ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20240624123045'
msg = 'Method chaining check #01' ).
o_datetime->add_days( -3
)->add_hours( -12
)->add_minutes( -30
)->add_seconds( -45
)->add_weeks( -2
)->add_months( -3
)->add_years( -3 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210307000000'
msg = 'Method chaining check #02' ).
ENDMETHOD.
METHOD add.
"" ISO Timestamp im Format 2021-01-01T01:01:01+01:00
DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ).
o_datetime->add( iv_field = zcl_datetime=>c_fields-day
iv_value = 3 ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210310000000'
msg = 'Datum +3 Tage fehlerhaft' ).
o_datetime->add( iv_field = zcl_datetime=>c_fields-day
iv_value = -5 ).
o_datetime->add( iv_field = zcl_datetime=>c_fields-hour
iv_value = -3 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210304210000'
msg = 'Datum -5 Tage - 3 Stunden fehlerhaft' ).
o_datetime->add( iv_field = zcl_datetime=>c_fields-week
iv_value = 1 ).
o_datetime->add( iv_field = zcl_datetime=>c_fields-hour
iv_value = 3 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210312000000'
msg = 'Datum +1 Woche +3 Stunden fehlerhaft' ).
o_datetime = zcl_datetime=>from_date( iv_date = '20210228' iv_time = zcl_datetime=>c_times-end_of_day ).
o_datetime->add( iv_field = zcl_datetime=>c_fields-second
iv_value = 1 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210301000000'
msg = 'Datum +1 Sekunde fehlerhaft' ).
ENDMETHOD.
METHOD add_days.
DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ).
o_datetime->add_days( 5 ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210312000000'
msg = 'Datum +5 Tage fehlerhaft' ).
o_datetime->add_days( -12 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210228000000'
msg = 'Datum -12 Tage fehlerhaft' ).
ENDMETHOD.
METHOD add_hours.
DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' iv_time = '060000' ).
o_datetime->add_hours( 8 ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210307140000'
msg = 'Add hours check #01' ).
o_datetime->add_hours( 16 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210308060000'
msg = 'Add hours check #02' ).
o_datetime->add_hours( -24 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210307060000'
msg = 'Add hours check #03' ).
ENDMETHOD.
METHOD add_minutes.
DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' iv_time = '060000' ).
o_datetime->add_minutes( 8 ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210307060800'
msg = 'Add minutes check #01' ).
o_datetime->add_minutes( 52 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210307070000'
msg = 'Add minutes check #02' ).
o_datetime->add_minutes( 60 * 24 * 2 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210309070000'
msg = 'Add minutes check #03' ).
o_datetime->add_minutes( -1 * ( 60 * 24 * 3 ) ).
o_datetime->add_minutes( -60 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210306060000'
msg = 'Add minutes check #04' ).
ENDMETHOD.
METHOD add_months.
DATA(o_datetime) = zcl_datetime=>from_date( '20210131' ).
DATA(date) = o_datetime->add_months( 1 )->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20210228'
msg = 'Add month check #01' ).
date = o_datetime->add_months( 36 )->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20240228'
msg = 'Add month check #02' ).
ENDMETHOD.
METHOD add_seconds.
DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' iv_time = '060000' ).
o_datetime->add_seconds( 8 ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210307060008'
msg = 'Add seconds check #01' ).
o_datetime->add_seconds( 52 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210307060100'
msg = 'Add seconds check #02' ).
o_datetime->add_seconds( 60 * 60 * 24 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210308060100'
msg = 'Add seconds check #03' ).
o_datetime->add_seconds( -600 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210308055100'
msg = 'Add seconds check #04' ).
ENDMETHOD.
METHOD add_weeks.
DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' ).
o_datetime->add_weeks( 1 ).
DATA(date) = o_datetime->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20210314'
msg = 'Add weeks check #01' ).
o_datetime->add_weeks( -2 ).
date = o_datetime->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20210228'
msg = 'Add weeks check #02' ).
ENDMETHOD.
METHOD add_years.
DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' ).
o_datetime->add_years( 1 ).
DATA(date) = o_datetime->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20220307'
msg = 'Add years check #01' ).
o_datetime->add_years( -2 ).
date = o_datetime->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20200307'
msg = 'Add years check #02' ).
ENDMETHOD.
METHOD as_date.
DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' ).
DATA(date) = o_datetime->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20210307'
msg = 'As date check #01' ).
o_datetime = zcl_datetime=>from_date( iv_date = '20210331' ).
date = o_datetime->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20210331'
msg = 'As date check #02' ).
o_datetime = zcl_datetime=>from_date( iv_date = '20210401' ).
date = o_datetime->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20210401'
msg = 'As date check #02' ).
ENDMETHOD.
METHOD as_iso_timestamp.
DATA(o_datetime) = zcl_datetime=>from_timestamp( '20210307093045' ).
DATA(iso_timestamp) = o_datetime->as_iso_timestamp( ).
cl_aunit_assert=>assert_equals( act = iso_timestamp
exp = '2021-03-07T09:30:45Z'
msg = 'As ISO timestamp check #01' ).
ENDMETHOD.
METHOD as_long_timestamp.
DATA(o_datetime) = zcl_datetime=>from_timestamp( '20210307093045' ).
DATA(long_timestamp) = o_datetime->as_long_timestamp( ).
cl_aunit_assert=>assert_equals( act = long_timestamp
exp = '20210307093045.0000000'
msg = 'As date check #01' ).
ENDMETHOD.
METHOD as_timestamp.
DATA(o_datetime) = zcl_datetime=>from_timestamp( '20210307093045' ).
DATA(long_timestamp) = o_datetime->as_long_timestamp( ).
cl_aunit_assert=>assert_equals( act = long_timestamp
exp = '20210307093045'
msg = 'As date check #02' ).
ENDMETHOD.
METHOD begin_of_day.
DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' iv_time = '235959' ).
o_datetime->begin_of_day( ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210307000000'
msg = 'Begin of day check #01' ).
ENDMETHOD.
METHOD begin_of_month.
DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ).
o_datetime->begin_of_month( ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210301000000'
msg = 'Begin of month check #01' ).
ENDMETHOD.
METHOD begin_of_quarter.
DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ).
o_datetime->begin_of_quarter( ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210101000000'
msg = 'Begin of quarter check #01' ).
ENDMETHOD.
METHOD begin_of_week.
DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ).
DATA(date) = o_datetime->begin_of_week( )->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20201228'
msg = 'Begin of week check #01' ).
ENDMETHOD.
METHOD begin_of_year.
DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ).
o_datetime->begin_of_quarter( ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210101000000'
msg = 'Begin of year check #01' ).
ENDMETHOD.
METHOD clone.
DATA(o_this_datetime) = zcl_datetime=>from_now( ).
DATA(o_other_datetime) = o_this_datetime->clone( ).
IF o_this_datetime = o_other_datetime.
cl_aunit_assert=>fail( 'Clone check #01' ).
ENDIF.
IF NOT o_this_datetime->is_equal( o_other_datetime ).
cl_aunit_assert=>fail( 'Clone check #02' ).
ENDIF.
ENDMETHOD.
METHOD day_of_week.
DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ). "" Sunday
o_datetime->day_of_week( zcl_datetime=>c_day_of_week-wednesday ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210303000000'
msg = 'Day of week check #01' ).
o_datetime->day_of_week( zcl_datetime=>c_day_of_week-monday ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210301000000'
msg = 'Day of week check #02' ).
ENDMETHOD.
METHOD end_of_day.
DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' iv_time = '120000' ).
o_datetime->end_of_day( ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210307235959'
msg = 'End of day check #01' ).
ENDMETHOD.
METHOD end_of_month.
DATA(o_datetime) = zcl_datetime=>from_date( '20200205' ).
DATA(ts) = o_datetime->end_of_month( )->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20200229000000'
msg = 'End of month check #01' ).
o_datetime = zcl_datetime=>from_date( '20210205' ).
ts = o_datetime->end_of_month( )->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210228000000'
msg = 'End of month check #02' ).
ENDMETHOD.
METHOD end_of_quarter.
DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ). "" Sunday
o_datetime->end_of_quarter( ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210331000000'
msg = 'End of quarter check #01' ).
o_datetime->add_days( 1 )->end_of_quarter( ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210630000000'
msg = 'End of quarter check #02' ).
o_datetime->add_days( 1 )->end_of_quarter( ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210930000000'
msg = 'End of quarter check #03' ).
o_datetime->add_days( 1 )->end_of_quarter( ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20211231000000'
msg = 'End of quarter check #04' ).
ENDMETHOD.
METHOD end_of_week.
DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ).
DATA(date) = o_datetime->end_of_week( )->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20210103'
msg = 'End of week check #01' ).
o_datetime = zcl_datetime=>from_date( '20210301' ).
date = o_datetime->end_of_week( )->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20210307'
msg = 'End of week check #02' ).
ENDMETHOD.
METHOD end_of_year.
DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ).
DATA(date) = o_datetime->end_of_year( )->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20211231'
msg = 'End of year check #01' ).
ENDMETHOD.
METHOD from_date.
DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ).
DATA(date) = o_datetime->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20210101'
msg = 'From date check #01' ).
TRY.
o_datetime = zcl_datetime=>from_date( '20210229' ). "" 2021 is a none leap year...29th of february is not a valid date.
cl_aunit_assert=>fail( msg = 'From date check #02' ).
CATCH cx_parameter_invalid_range ##NO_HANDLER.
"" Everything is fine. We had expected an exception.
ENDTRY.
TRY.
o_datetime = zcl_datetime=>from_date( '20200229' ). "" 2021 is a leap year...29th of february is a valid date.
CATCH cx_parameter_invalid_range ##NO_HANDLER.
cl_aunit_assert=>fail( msg = 'From date check #03' ).
"" Everything is fine. We had expected an exception.
ENDTRY.
TRY.
o_datetime = zcl_datetime=>from_date( iv_date = '20200229' iv_time = '243030' ).
cl_aunit_assert=>fail( msg = 'From date check #04' ).
CATCH cx_parameter_invalid_range ##NO_HANDLER.
"" Everything is fine. We had expected an exception.
ENDTRY.
TRY.
o_datetime = zcl_datetime=>from_date( iv_date = '20200229' iv_time = '000000' ).
CATCH cx_parameter_invalid_range ##NO_HANDLER.
cl_aunit_assert=>fail( msg = 'From date check #05' ).
ENDTRY.
ENDMETHOD.
METHOD from_iso_timestamp.
DATA(o_datetime) = zcl_datetime=>from_iso_timestamp( '2020-04-21T18:09:25Z' ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20200421180925'
msg = 'From iso timestamp check #01' ).
TRY.
o_datetime = zcl_datetime=>from_iso_timestamp( '2020-04-21T28:09:25Z' ). "" 28:09:25 is not a valid time...
cl_aunit_assert=>fail( msg = 'From iso timestamp check #02' ).
CATCH cx_xlf_illegal_argument ##NO_HANDLER.
"" Everything is fine. We had expected an exception.
ENDTRY.
ENDMETHOD.
METHOD from_now.
DATA(current_date) = sy-datum.
DATA(current_time) = sy-uzeit.
DATA(o_datetime) = zcl_datetime=>from_now( ).
DATA(ts) = o_datetime->as_timestamp( ).
DATA(o_dt_reference) = zcl_datetime=>from_timestamp( CONV timestamp( |{ current_date }{ current_time }| ) ).
DATA(delta) = abs( o_datetime->diff( iv_field = zcl_datetime=>c_fields-second
io_datetime = o_dt_reference ) ).
"" Max delta of one second is okay. Be aware that this test fails in debugger
"" if you arent fast enough...
IF delta > 1.
cl_aunit_assert=>fail( msg = 'From now check #01' ).
ENDIF.
ENDMETHOD.
METHOD from_today.
DATA(current_date) = sy-datum.
DATA(o_datetime) = zcl_datetime=>from_today( ).
DATA(date) = o_datetime->as_date( ).
IF date NE current_date.
cl_aunit_assert=>fail( msg = 'From today check #01' ).
ENDIF.
ENDMETHOD.
METHOD get_dayname.
##TODO.
ENDMETHOD.
METHOD get_day_of_week.
DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ).
"" We step throug next 7 day and check the expected day of week.
"" Checks are done relative to given date 1st January of 2021
DATA(day_of_week) = o_datetime->get_day_of_week( ).
cl_aunit_assert=>assert_equals( act = day_of_week
exp = zcl_datetime=>c_day_of_week-friday
msg = 'Day of week check #01' ).
o_datetime->add_days( 1 ).
day_of_week = o_datetime->get_day_of_week( ).
cl_aunit_assert=>assert_equals( act = day_of_week
exp = zcl_datetime=>c_day_of_week-saturday
msg = 'Day of week check #02' ).
o_datetime->add_days( 1 ).
day_of_week = o_datetime->get_day_of_week( ).
cl_aunit_assert=>assert_equals( act = day_of_week
exp = zcl_datetime=>c_day_of_week-sunday
msg = 'Day of week check #03' ).
o_datetime->add_days( 1 ).
day_of_week = o_datetime->get_day_of_week( ).
cl_aunit_assert=>assert_equals( act = day_of_week
exp = zcl_datetime=>c_day_of_week-monday
msg = 'Day of week check #04' ).
o_datetime->add_days( 1 ).
day_of_week = o_datetime->get_day_of_week( ).
cl_aunit_assert=>assert_equals( act = day_of_week
exp = zcl_datetime=>c_day_of_week-tuesday
msg = 'Day of week check #05' ).
o_datetime->add_days( 1 ).
day_of_week = o_datetime->get_day_of_week( ).
cl_aunit_assert=>assert_equals( act = day_of_week
exp = zcl_datetime=>c_day_of_week-wednesday
msg = 'Day of week check #06' ).
o_datetime->add_days( 1 ).
day_of_week = o_datetime->get_day_of_week( ).
cl_aunit_assert=>assert_equals( act = day_of_week
exp = zcl_datetime=>c_day_of_week-thursday
msg = 'Day of week check #07' ).
o_datetime->add_days( 1 ).
day_of_week = o_datetime->get_day_of_week( ).
cl_aunit_assert=>assert_equals( act = day_of_week
exp = zcl_datetime=>c_day_of_week-friday
msg = 'Day of week check #08' ).
o_datetime = zcl_datetime=>from_date( '20211231' ).
day_of_week = o_datetime->get_day_of_week( ).
cl_aunit_assert=>assert_equals( act = day_of_week
exp = zcl_datetime=>c_day_of_week-friday
msg = 'Day of week check #09' ).
ENDMETHOD.
METHOD get_ultimo.
DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ).
DATA(ultimo) = o_datetime->get_ultimo( ).
cl_aunit_assert=>assert_equals( act = ultimo
exp = '20210131'
msg = 'Get last day of month check #01' ).
ultimo = o_datetime->add_months( 1
)->get_ultimo( ).
cl_aunit_assert=>assert_equals( act = ultimo
exp = '20210228'
msg = 'Get last day of month check #02' ).
ultimo = o_datetime->add_years( -1
)->get_ultimo( ). "" 2020 was a leap year...
cl_aunit_assert=>assert_equals( act = ultimo
exp = '20200229'
msg = 'Get last day of month check #03' ).
ENDMETHOD.
METHOD get_number_of_days_of_month.
"" The result is calculated in the same way.
me->get_ultimo( ).
ENDMETHOD.
METHOD get_number_of_days_of_year.
DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ).
DATA(number_of_days_of_year) = o_datetime->get_number_of_days_of_year( ).
cl_aunit_assert=>assert_equals( act = number_of_days_of_year
exp = zcl_datetime=>c_day_of_year-max_days_in_none_leap_year
msg = 'Get number of days of year check #01' ).
number_of_days_of_year = o_datetime->add_years( -1
)->get_number_of_days_of_year( ).
cl_aunit_assert=>assert_equals( act = number_of_days_of_year
exp = zcl_datetime=>c_day_of_year-max_days_in_leap_year
msg = 'Get number of days of year check #02' ).
ENDMETHOD.
METHOD is_last_day_of_month.
DATA(o_datetime) = zcl_datetime=>from_date( '20210131' ).
DATA(fl_last_day_of_month) = o_datetime->is_last_day_of_month( ).
cl_aunit_assert=>assert_equals( act = fl_last_day_of_month
exp = abap_true
msg = 'Is last day of month check #01' ).
fl_last_day_of_month = o_datetime->add_days( 1
)->is_last_day_of_month( ).
cl_aunit_assert=>assert_equals( act = fl_last_day_of_month
exp = abap_false
msg = 'Is last day of month check #02' ).
ENDMETHOD.
METHOD set.
DATA(o_datetime) = zcl_datetime=>from_date( '20210131' ).
o_datetime->set( iv_field = zcl_datetime=>c_fields-year
iv_value = 2020 ).
o_datetime->set( iv_field = zcl_datetime=>c_fields-month
iv_value = 3 ).
o_datetime->set( iv_field = zcl_datetime=>c_fields-day
iv_value = 1 ).
o_datetime->set( iv_field = zcl_datetime=>c_fields-hour
iv_value = 9 ).
o_datetime->set( iv_field = zcl_datetime=>c_fields-minute
iv_value = 30 ).
o_datetime->set( iv_field = zcl_datetime=>c_fields-second
iv_value = 45 ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20200301093045'
msg = 'Set check #01' ).
ENDMETHOD.
METHOD subtract.
ENDMETHOD.
METHOD get_day_of_year.
DATA(o_datetime) = zcl_datetime=>from_date( '19900806' ).
o_datetime->get_day_of_year( ).
ENDMETHOD.
METHOD get_quarter.
DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ).
DATA(quarter) = o_datetime->get_quarter( ).
cl_aunit_assert=>assert_equals( act = quarter
exp = 1
msg = 'Quarter calc check #01' ).
o_datetime->add_months( 3 ).
quarter = o_datetime->get_quarter( ).
cl_aunit_assert=>assert_equals( act = quarter
exp = 2
msg = 'Quarter calc check #02' ).
o_datetime->add_months( 3 ).
quarter = o_datetime->get_quarter( ).
cl_aunit_assert=>assert_equals( act = quarter
exp = 3
msg = 'Quarter calc check #03' ).
o_datetime->add_months( 3 ).
quarter = o_datetime->get_quarter( ).
cl_aunit_assert=>assert_equals( act = quarter
exp = 4
msg = 'Quarter calc check #04' ).
o_datetime->add_months( 3 ).
quarter = o_datetime->get_quarter( ).
cl_aunit_assert=>assert_equals( act = quarter
exp = 1
msg = 'Quarter calc check #05' ).
ENDMETHOD.
METHOD get_iso_week.
DATA(o_datetime) = zcl_datetime=>from_date( '20211231' ).
DATA(wa_iso_week) = o_datetime->get_iso_week( ).
cl_aunit_assert=>assert_equals( act = wa_iso_week
exp = VALUE zcl_datetime=>ty_iso_week(
week = 52
year = 2021
day_of_week = zcl_datetime=>c_day_of_week-friday )
msg = 'ISO week check #01' ).
o_datetime = zcl_datetime=>from_date( '20210101' ).
wa_iso_week = o_datetime->get_iso_week( ).
cl_aunit_assert=>assert_equals( act = wa_iso_week
exp = VALUE zcl_datetime=>ty_iso_week(
week = 53
year = 2020
day_of_week = zcl_datetime=>c_day_of_week-friday )
msg = 'ISO week check #02' ).
o_datetime = zcl_datetime=>from_date( '20200104' ).
wa_iso_week = o_datetime->get_iso_week( ).
cl_aunit_assert=>assert_equals( act = wa_iso_week
exp = VALUE zcl_datetime=>ty_iso_week(
week = 1
year = 2020
day_of_week = zcl_datetime=>c_day_of_week-saturday )
msg = 'ISO week check #03' ).
o_datetime = zcl_datetime=>from_date( '20200229' ).
wa_iso_week = o_datetime->get_iso_week( ).
cl_aunit_assert=>assert_equals( act = wa_iso_week
exp = VALUE zcl_datetime=>ty_iso_week(
week = 9
year = 2020
day_of_week = zcl_datetime=>c_day_of_week-saturday )
msg = 'ISO week check #04' ).
o_datetime = zcl_datetime=>from_date( '20200106' ).
wa_iso_week = o_datetime->get_iso_week( ).
cl_aunit_assert=>assert_equals( act = wa_iso_week
exp = VALUE zcl_datetime=>ty_iso_week(
week = 2
year = 2020
day_of_week = zcl_datetime=>c_day_of_week-monday )
msg = 'ISO week check #05' ).
ENDMETHOD.
METHOD is_leap_year.
DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ).
DATA(fl_is_leap_year) = o_datetime->is_leap_year( ).
cl_aunit_assert=>assert_equals( act = fl_is_leap_year
exp = abap_false
msg = 'Leap year check #01' ).
o_datetime = zcl_datetime=>from_date( '20200101' ).
fl_is_leap_year = o_datetime->is_leap_year( ).
cl_aunit_assert=>assert_equals( act = fl_is_leap_year
exp = abap_true
msg = 'Leap year check #02' ).
o_datetime = zcl_datetime=>from_date( '16000101' ).
fl_is_leap_year = o_datetime->is_leap_year( ).
cl_aunit_assert=>assert_equals( act = fl_is_leap_year
exp = abap_true
msg = 'Leap year check #03' ).
o_datetime = zcl_datetime=>from_date( '19000101' ).
fl_is_leap_year = o_datetime->is_leap_year( ).
cl_aunit_assert=>assert_equals( act = fl_is_leap_year
exp = abap_false
msg = 'Leap year check #04' ).
ENDMETHOD.
METHOD is_before.
DATA(o_this) = zcl_datetime=>from_now( ).
DATA(o_other) = o_this->clone( )->add_days( -1 ).
IF o_other->is_before( o_this ).
"" Works as expected...
ELSE.
cl_aunit_assert=>fail( msg = 'Is before check #01' ).
ENDIF.
IF o_this->is_before( o_other ).
cl_aunit_assert=>fail( msg = 'Is before check #02' ).
ELSE.
"" Works as expected...
ENDIF.
o_other = o_this->clone( )->add_seconds( -1 ).
IF o_other->is_before( o_this ).
cl_aunit_assert=>fail( msg = 'Is before check #03' ).
ELSE.
"" Works as expected...
ENDIF.
IF o_this->is_before( o_other ).
cl_aunit_assert=>fail( msg = 'Is before check #04' ).
ELSE.
"" Works as expected...
ENDIF.
IF o_other->is_before( io_datetime = o_this iv_ignore_time = abap_false ).
"" Works as expected...
ELSE.
cl_aunit_assert=>fail( msg = 'Is before check #05' ).
ENDIF.
ENDMETHOD.
METHOD is_before_or_equal.
DATA(o_this) = zcl_datetime=>from_now( ).
DATA(o_other) = o_this->clone( ).
IF o_other->is_before_or_equal( o_this ).
"" Works as expected...
ELSE.
cl_aunit_assert=>fail( msg = 'Is before or equal check #01' ).
ENDIF.
o_other->add_seconds( -1 ).
IF o_other->is_before_or_equal( o_this ).
"" Works as expected...
ELSE.
cl_aunit_assert=>fail( msg = 'Is before or equal check #02' ).
ENDIF.
o_other = o_this->clone( )->add_seconds( 1 ).
IF o_other->is_before_or_equal( o_this ).
"" Works as expected...
ELSE.
cl_aunit_assert=>fail( msg = 'Is before or equal check #03' ).
ENDIF.
IF o_other->is_before_or_equal( io_datetime = o_this iV_ignore_time = abap_false ).
cl_aunit_assert=>fail( msg = 'Is before or equal check #03' ).
ELSE.
"" Works as expected...
ENDIF.
ENDMETHOD.
METHOD is_after.
DATA(o_this) = zcl_datetime=>from_now( ).
DATA(o_other) = o_this->clone( ).
IF o_this->is_after( o_other ).
cl_aunit_assert=>fail( msg = 'Is after check #01' ).
ELSE.
"" Works as expected...
ENDIF.
o_other->add_days( - 1 ).
IF o_this->is_after( o_other ).
"" Works as expected...
ELSE.
cl_aunit_assert=>fail( msg = 'Is after check #02' ).
ENDIF.
o_other = o_this->clone( )->add_seconds( -1 ).
IF o_this->is_after( io_datetime = o_other iv_ignore_time = abap_false ).
"" Works as expected...
ELSE.
cl_aunit_assert=>fail( msg = 'Is after check #03' ).
ENDIF.
o_other = o_this->clone( )->add_seconds( 1 ).
IF o_this->is_after( io_datetime = o_other iv_ignore_time = abap_false ).
cl_aunit_assert=>fail( msg = 'Is after check #03' ).
ELSE.
"" Works as expected...
ENDIF.
ENDMETHOD.
METHOD is_after_or_equal.
DATA(o_this) = zcl_datetime=>from_now( ).
DATA(o_other) = o_this->clone( ).
IF o_this->is_after_or_equal( o_other ).
"" Works as expected...
ELSE.
cl_aunit_assert=>fail( msg = 'Is after or equal check #01' ).
ENDIF.
o_other->add_days( 1 ).
IF o_this->is_after_or_equal( o_other ).
cl_aunit_assert=>fail( msg = 'Is after or equal check #02' ).
ELSE.
"" Works as expected...
ENDIF.
o_other = o_this->clone( ).
IF o_this->is_after_or_equal( io_datetime = o_other iv_ignore_time = abap_false ).
"" Works as expected...
ELSE.
cl_aunit_assert=>fail( msg = 'Is after or equal check #03' ).
ENDIF.
o_other->add_seconds( 1 ).
IF o_this->is_after_or_equal( io_datetime = o_other iv_ignore_time = abap_false ).
cl_aunit_assert=>fail( msg = 'Is after or equal check #04' ).
ELSE.
"" Works as expected...
ENDIF.
o_other = o_this->clone( )->add_seconds( - 1 ).
IF o_this->is_after_or_equal( io_datetime = o_other iv_ignore_time = abap_false ).
"" Works as expected...
ELSE.
cl_aunit_assert=>fail( msg = 'Is after or equal check #05' ).
ENDIF.
ENDMETHOD.
METHOD is_equal.
DATA(o_this) = zcl_datetime=>from_now( ).
DATA(o_other) = o_this->clone( ).
IF o_this->is_equal( o_other ).
"" Works as expected...
ELSE.
cl_aunit_assert=>fail( msg = 'Is equal check #01' ).
ENDIF.
o_other->add_days( 1 ).
IF o_this->is_equal( o_other ).
cl_aunit_assert=>fail( msg = 'Is equal check #02' ).
ELSE.
"" Works as expected...
ENDIF.
o_other = o_this->clone( )->add_seconds( 1 ).
IF o_this->is_equal( o_other ).
"" Works as expected...
ELSE.
cl_aunit_assert=>fail( msg = 'Is equal check #03' ).
ENDIF.
IF o_this->is_equal( io_datetime = o_other iv_ignore_time = abap_false ).
cl_aunit_assert=>fail( msg = 'Is equal check #04' ).
ELSE.
"" Works as expected...
ENDIF.
ENDMETHOD.
METHOD create_list.
DATA(o_this) = zcl_datetime=>from_date( '20210307' ).
o_this->begin_of_year( )->begin_of_day( ).
"" Create a list with all 12 month in a year
DATA(t_datetime_list) = zcl_datetime=>create_list( io_start = o_this
iv_increment_field = zcl_datetime=>c_fields-month
iv_increment_value = 1
iv_num_of_elements = 12 ).
cl_aunit_assert=>assert_equals( act = lines( t_datetime_list )
exp = 12
msg = 'Create list check #01' ).
cl_aunit_assert=>assert_equals( act = t_datetime_list[ 1 ]-o_datetime->as_date( )
exp = CONV dats( '20210101' )
msg = 'Create list check #02' ).
cl_aunit_assert=>assert_equals( act = t_datetime_list[ 2 ]-o_datetime->as_date( )
exp = CONV dats( '20210201' )
msg = 'Create list check #03' ).
cl_aunit_assert=>assert_equals( act = t_datetime_list[ 3 ]-o_datetime->as_date( )
exp = CONV dats( '20210301' )
msg = 'Create list check #04' ).
cl_aunit_assert=>assert_equals( act = t_datetime_list[ 4 ]-o_datetime->as_date( )
exp = CONV dats( '20210401' )
msg = 'Create list check #05' ).
cl_aunit_assert=>assert_equals( act = t_datetime_list[ 5 ]-o_datetime->as_date( )
exp = CONV dats( '20210501' )
msg = 'Create list check #06' ).
cl_aunit_assert=>assert_equals( act = t_datetime_list[ 6 ]-o_datetime->as_date( )
exp = CONV dats( '20210601' )
msg = 'Create list check #07' ).
cl_aunit_assert=>assert_equals( act = t_datetime_list[ 7 ]-o_datetime->as_date( )
exp = CONV dats( '20210701' )
msg = 'Create list check #08' ).
cl_aunit_assert=>assert_equals( act = t_datetime_list[ 8 ]-o_datetime->as_date( )
exp = CONV dats( '20210801' )
msg = 'Create list check #09' ).
cl_aunit_assert=>assert_equals( act = t_datetime_list[ 9 ]-o_datetime->as_date( )
exp = CONV dats( '20210901' )
msg = 'Create list check #10' ).
cl_aunit_assert=>assert_equals( act = t_datetime_list[ 10 ]-o_datetime->as_date( )
exp = CONV dats( '20211001' )
msg = 'Create list check #11' ).
cl_aunit_assert=>assert_equals( act = t_datetime_list[ 11 ]-o_datetime->as_date( )
exp = CONV dats( '20211101' )
msg = 'Create list check #12' ).
cl_aunit_assert=>assert_equals( act = t_datetime_list[ 12 ]-o_datetime->as_date( )
exp = CONV dats( '20211201' )
msg = 'Create list check #13' ).
"" Creating date list with all 31 days of january
t_datetime_list = zcl_datetime=>create_list( io_start = o_this
iv_increment_field = zcl_datetime=>c_fields-day
iv_increment_value = 1
iv_num_of_elements = 31 ).
cl_aunit_assert=>assert_equals( act = lines( t_datetime_list )
exp = 31
msg = 'Create list check #14' ).
"" Testing only one sample
cl_aunit_assert=>assert_equals( act = t_datetime_list[ 15 ]-o_datetime->as_date( )
exp = CONV dats( '20210115' )
msg = 'Create list check #14' ).
ENDMETHOD.
METHOD sub_days.
DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ).
o_datetime->sub_days( 5 ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210302000000'
msg = 'Sub days check #01' ).
o_datetime->sub_days( -10 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210312000000'
msg = 'Sub days check #02' ).
ENDMETHOD.
METHOD sub_hours.
DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' iv_time = '060000' ).
o_datetime->sub_hours( 8 ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210306220000'
msg = 'Sub hours check #01' ).
o_datetime->sub_hours( 16 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210306060000'
msg = 'Sub hours check #02' ).
o_datetime->sub_hours( -24 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210307060000'
msg = 'Sub hours check #03' ).
ENDMETHOD.
METHOD sub_minutes.
DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' iv_time = '060000' ).
o_datetime->sub_minutes( 8 ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210307055200'
msg = 'Sub minutes check #01' ).
o_datetime->sub_minutes( 52 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210307050000'
msg = 'Sub minutes check #02' ).
ENDMETHOD.
METHOD sub_months.
DATA(o_datetime) = zcl_datetime=>from_date( '20210131' ).
DATA(date) = o_datetime->sub_months( 1 )->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20201231'
msg = 'Sub month check #01' ).
date = o_datetime->sub_months( 36 )->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20171231'
msg = 'Sub month check #02' ).
ENDMETHOD.
METHOD sub_seconds.
DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' iv_time = '060000' ).
o_datetime->sub_seconds( 8 ).
DATA(ts) = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210307055952'
msg = 'Sub seconds check #01' ).
o_datetime->sub_seconds( 52 ).
ts = o_datetime->as_timestamp( ).
cl_aunit_assert=>assert_equals( act = ts
exp = '20210307055900'
msg = 'Sub seconds check #02' ).
ENDMETHOD.
METHOD sub_weeks.
DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' ).
o_datetime->sub_weeks( 1 ).
DATA(date) = o_datetime->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20210228'
msg = 'Sub weeks check #01' ).
o_datetime->sub_weeks( -2 ).
date = o_datetime->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20210314'
msg = 'Sub weeks check #02' ).
ENDMETHOD.
METHOD sub_years.
DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' ).
o_datetime->sub_years( 1 ).
DATA(date) = o_datetime->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20200307'
msg = 'Sub years check #01' ).
o_datetime->sub_years( -2 ).
date = o_datetime->as_date( ).
cl_aunit_assert=>assert_equals( act = date
exp = '20220307'
msg = 'Sub years check #02' ).
ENDMETHOD.
METHOD diff.
DATA(o_this) = zcl_datetime=>from_date( iv_date = '20210307' ).
DATA(o_other) = o_this->clone( )->add_hours( 36 ).
DATA(diff) = o_this->diff( io_datetime = o_other
iv_field = zcl_datetime=>c_fields-day ).
cl_aunit_assert=>assert_equals( act = diff
exp = CONV zcl_datetime=>ty_diff( '1.5' )
msg = 'Diff check #01' ).
diff = o_this->diff( io_datetime = o_other
iv_field = zcl_datetime=>c_fields-day
iv_round_mode = zcl_datetime=>c_rouding-round_ceiling ).
cl_aunit_assert=>assert_equals( act = diff
exp = CONV zcl_datetime=>ty_diff( '2' )
msg = 'Diff check #02' ).
diff = o_this->diff( io_datetime = o_other
iv_field = zcl_datetime=>c_fields-day
iv_round_mode = zcl_datetime=>c_rouding-round_down ).
cl_aunit_assert=>assert_equals( act = diff
exp = CONV zcl_datetime=>ty_diff( '1' )
msg = 'Diff check #02' ).
o_other = o_this->clone( )->add_hours( 44 ).
diff = o_this->diff( io_datetime = o_other
iv_field = zcl_datetime=>c_fields-day ).
cl_aunit_assert=>assert_equals( act = diff
exp = CONV zcl_datetime=>ty_diff( '1.833333333333333' )
msg = 'Diff check #02' ).
o_this = zcl_datetime=>from_date( '20210101' ).
o_other = zcl_datetime=>from_date( '20211231' ).
diff = o_this->diff( io_datetime = o_other
iv_field = zcl_datetime=>c_fields-month ).
ENDMETHOD.
ENDCLASS.
",12880,True,3144.685192996604,median
":toc: macro
toc::[]
:idprefix:
:idseparator: -
ifdef::env-github[]
:tip-caption: :bulb:
:note-caption: :information_source:
:important-caption: :heavy_exclamation_mark:
:caution-caption: :fire:
:warning-caption: :warning:
endif::[]
= devon4j adding Custom Functionality
Now we have a fully functional blank project. All we have to do now is to create the components and services which will compose our application.
First, we are going to develop the views of the app through its components, then we will create the services with the logic, security and back-end connection.
== Creating Components
[NOTE]
====
You have already learned about creating Components in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#create-a-new-component[here]. +
You can go back and read that section again to refresh your memory.
====
Our app is going to consist of 3 main views:
* Login
* Register
* ViewQueue
To navigate between these views/components, we are going to implement routes using the Angular Router.
To see our progress, move to the root folder of the `angular` project and run `ng serve -o` again. This will recompile and publish our client app to http://localhost:4200. Angular will keep watching for changes, so whenever we modify the code, the app will automatically reload.
=== Root Component
`app.component.ts` inside `angular/src/app` will be our root component, so we don't have to create a new file yet. We are going to add elements to the root component that will be common no matter what view will be displayed.
[NOTE]
====
You have already learned about the Root Component in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#root-component[here]. +
You can go back and read that section again to refresh your memory.
====
This applies to the header element which will be on top of the window and on top of all other components. If you want, you can read more about https://teradata.github.io/covalent/#/layouts[Covalent layouts], which we are going to use a lot from now on, for every view component.
[NOTE]
====
You have already learned about Covalent Layouts in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#teradata-covalent-layouts[here]. +
You can go back and read that section again to refresh your memory.
====
We don't really need anything more than a header, so we are going to use the simplest layout for this purpose; the *nav view*.
In order to be able to use Covalent and Angular Material we are going to create a core module, which we will import into every other module where we want to use Covalent and Angular Material. First, we create a folder called `shared` in the `angular/src/app` directory. Inside there we are going to create a file called `core.module.ts` and will fill it with the following content:
[source, typescript]
----
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {
MatAutocompleteModule,
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
MatCheckboxModule,
MatChipsModule,
MatDatepickerModule,
MatDialogModule,
MatExpansionModule,
MatGridListModule,
MatIconModule,
MatInputModule,
MatListModule,
MatMenuModule,
MatNativeDateModule,
MatPaginatorModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatRadioModule,
MatRippleModule,
MatSelectModule,
MatSidenavModule,
MatSliderModule,
MatSlideToggleModule,
MatSnackBarModule,
MatSortModule,
MatTableModule,
MatTabsModule,
MatToolbarModule,
MatTooltipModule,
} from '@angular/material';
import { CdkTableModule } from '@angular/cdk/table';
import {
CovalentChipsModule,
CovalentLayoutModule,
CovalentExpansionPanelModule,
CovalentDataTableModule,
CovalentPagingModule,
CovalentDialogsModule,
CovalentLoadingModule,
CovalentMediaModule,
CovalentNotificationsModule,
CovalentCommonModule,
} from '@covalent/core';
@NgModule({
imports: [
RouterModule,
BrowserAnimationsModule,
MatCardModule,
MatButtonModule,
MatIconModule,
CovalentMediaModule,
CovalentLayoutModule,
CdkTableModule,
],
exports: [
CommonModule,
CovalentChipsModule,
CovalentLayoutModule,
CovalentExpansionPanelModule,
CovalentDataTableModule,
CovalentPagingModule,
CovalentDialogsModule,
CovalentLoadingModule,
CovalentMediaModule,
CovalentNotificationsModule,
CovalentCommonModule,
CdkTableModule,
MatAutocompleteModule,
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
MatCheckboxModule,
MatChipsModule,
MatDatepickerModule,
MatDialogModule,
MatExpansionModule,
MatGridListModule,
MatIconModule,
MatInputModule,
MatListModule,
MatMenuModule,
MatNativeDateModule,
MatPaginatorModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatRadioModule,
MatRippleModule,
MatSelectModule,
MatSidenavModule,
MatSliderModule,
MatSlideToggleModule,
MatSnackBarModule,
MatSortModule,
MatTableModule,
MatTabsModule,
MatToolbarModule,
MatTooltipModule,
HttpClientModule,
],
declarations: [],
providers: [
HttpClientModule
],
})
export class CoreModule {}
----
[NOTE]
====
This `CoreModule` has almost every module of the different components for *Angular Material* and *Covalent Teradata*. If you decide to use a component that is not included yet, you need to add the corresponding module here.
====
Remember that we need to import this `CoreModule` module into the `AppModule` and inside every module of the different components that use *Angular Material* and *Covalent Teradata*. If a component does not have a module, it will be imported in the `AppModule` and hence automatically have the `CoreModule`. Our `app.module.ts` should have the following content:
[source, typescript]
----
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
// Application components and services
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CoreModule } from './shared/core.module';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
CoreModule,
],
providers: [
],
bootstrap: [AppComponent],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class AppModule { }
----
[NOTE]
====
Even if we setup module correctly the html file can give us this red flag: ""If 'td-layout' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.""
To solve this we add ""schemas: [ CUSTOM_ELEMENTS_SCHEMA ]"" insde the @NgModule of all the afected modules.
====
[NOTE]
====
Remember this step because you will have to repeat it for every other component from Teradata you use in your app.
====
Now we can use this layout, so let's implement it in `app.component.html`. Use the following code:
[source, html]
----
Jump The Queue
app works!
----
[NOTE]
====
You have already learned about Toolbars in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#toolbars[here]. +
You can go back and read that section again to refresh your memory.
====
[NOTE]
====
You have already learned about Toolbars in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#toolbars[here]. +
You can go back and read that section again to refresh your memory.
====
Once this is done, our app should have a header and ""app works!"" should appear in the body of the page:
image::images/devon4ng/3.BuildYourOwn/root_header.jpg[Root Header, 250]
To go a step further, we have to modify the body of the root component because it should be the *output of the router*. Now it's time to prepare the routing system.
First, we need to create a component to show as default which will be our access view. We will modify it later. Stop `ng serve` and run:
----
ng generate component form-login
----
It will add a folder to our project with all the files needed for a component. Now we can move on to the router task again. Run `ng serve` again to continue the development.
Let's create a module that navigates between components when the Router checks for routes. The file `app-routing.module.ts` was created automatically when we chose to include Angular Routing during project creation and we only need to modify it now:
[source, typescript]
----
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FormLoginComponent } from './form-login/form-login.component';
const appRoutes: Routes = [
{ path: 'FormLogin', component: FormLoginComponent}, // Redirect if url path is /FormLogin.
{ path: '**', redirectTo: '/FormLogin', pathMatch: 'full' } // Redirect if url path do not match any other route.
];
@NgModule({
imports: [
RouterModule.forRoot(
appRoutes,
{ enableTracing: true }, // <-- debugging purposes only
),
],
exports: [RouterModule],
})
export class AppRoutingModule {}
----
[NOTE]
====
You have already learned about Routing in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#routing[here]. +
You can go back and read that section again to refresh your memory.
====
Finally, we remove the `
app works!
` from `app.component.html` and replace it with a `` tag. The final result of our root component will look like this:
image::images/devon4ng/3.BuildYourOwn/root_router.jpg[Root Router, 250]
As you can see, now the body content is the HTML of `FormLoginComponent`. This is because we told the Router to redirect to formlogin when the path is `/FormLogin`, but also, redirect to it by default if any of the other routes match the given path.
For now we are going to leave the header like this. In the future we will separate it into another component inside a layout folder.
=== LoginForm Component
As we have already created this component from the section before, let's move on to building the template of the login view.
First, we need to add the Covalent Layout and the card to the file `form-login.component.html`:
[source, html]
----
Login
----
This will add a grey background to the view and a card on top of it with the title ""Login"" now that we have the basic structure of the view.
Now we are going to add this image:
image::images/devon4ng/3.BuildYourOwn/jumptheq.png[JumpTheQueue Logo Image, 250]
In order to have it available, save it in the following path of the project: `angular/src/assets/images/` and name it `jumptheq.png`.
The final code with the form added will look like this:
[source, html]
----
----
This code will give us as a result similar to this:
image::images/devon4ng/3.BuildYourOwn/formlogin.png[Form Login, 250]
This is going to be the container for the login. +
Now we will continue with the second component: Login.
=== Login Component
Our first step will be to create the component in the exact same way we created the `FormLogin` component but this time we are going to generate it in a new folder called components inside formlogin. Putting every child component inside that folder will allow us to keep a good and clear structure. In order to do this, we use the command:
----
ng generate component form-login/components/login
----
After _Angular/CLI_ has finished generating the component, we have to create two modules, one for the form-login and one for the login:
1.- We create a new file called `login-module.ts` in the login root:
[source, typescript]
----
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CoreModule } from 'src/app/shared/core.module';
import { LoginComponent } from './login.component';
@NgModule({
imports: [CommonModule, CoreModule],
providers: [],
declarations: [LoginComponent],
exports: [LoginComponent],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class LoginModule {}
----
2.- We create a new file called `form-login-module.ts` in the form-login root:
[source, typescript]
----
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormLoginComponent } from './form-login.component';
import { CoreModule } from '../shared/core.module';
import { LoginModule } from './components/login/login-module';
@NgModule({
imports: [CommonModule, CoreModule, LoginModule],
providers: [],
declarations: [FormLoginComponent],
exports: [FormLoginComponent],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class FormLoginModule {}
----
As you can see, the `LoginModule` is already added to the `FormLoginModule`. Once this is done, we need to remove the `FormLoginComponent` and the `LoginComponent` from the `declarations` since they are already declared in their own modules. Then add the `FormLoginModule`. This will be done inside `AppModule`:
[source, typescript]
----
...
import { FormLoginModule } from './form-login/form-login-module';
...
declarations: [
AppComponent,
]
imports: [
BrowserModule,
FormLoginModule,
CoreModule,
AppRoutingModule
]
...
----
[NOTE]
====
This is done so the `form-login` (container/wrapper) and the `login` stay separated allowing us to reuse the login without having the card around in other views.
====
After this, we modify the `login.component.html` and add the form:
[source, typescript]
----
----
[NOTE]
====
You have already learned about Forms in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#forms[here]. +
You can go back and read that section again to refresh your memory.
====
This form contains two input containers from Material. The containers enclose the input with the properties listed above.
We also need to add a button to send the information and redirect to the `QueueViewer` or show an error if something went wrong in the process. But for the moment, as we neither have another component nor the auth service yet, we will implement the button visually, as well as the validator to disable it if the form is not correct. We will tackle the on-click-event later.
As a last step we will add this component to the `form-login-component.html`:
[source, html]
----
----
Now you should see something like this:
image::images/devon4ng/3.BuildYourOwn/login.png[JumpTheQueue Login Screen, 250]
With two components already created, we need to use the router to navigate between them. Following the application flow of events, we are going to add a _navigate_ function to the register button. When we press it, we will be redirected to our future register component.
=== Register Component
First, we are going to generate the register component via:
----
ng generate component register`
----
This will create our component so we can start working on it. Turning back to `login.component.html` we have to modify these lines of code:
[source, html]
----
----
Now that we have a minimum of navigation flow inside our application, we are going to generate our first service using the command:
----
ng generate service register/services/register
----
This will create a folder ""services"" inside ""register"" and create the service itself. Services are where we keep the logic that connects to our database and fetches data which is going to be used by our `component.ts`.
In order to use the service, we are going to create some interface models. Let's create a folder called `backendModels` inside ""shared"" and inside this folder a file called `interfaces.ts` in which we are going to add the model interfaces that will match our backend:
[source, typescript]
----
export class Visitor {
id?: number;
username: string;
name: string;
password: string;
phoneNumber: string;
acceptedCommercial: boolean;
acceptedTerms: boolean;
userType: boolean;
}
export class VisitorArray {
content: Visitor[];
}
----
[NOTE]
====
You have already learned about creating new services in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-services#create-a-new-service[here]. +
You can go back and read that section again to refresh your memory.
====
If we take a closer look, we can see that id has a `?` behind it. This indicates that the id is optional.
[NOTE]
====
At this point we are going to assume that you have finished the https://github.com/devonfw/jump-the-queue/wiki/build-devon4j-application[devon4j] part of this tutorial, or have at least downloaded the project and have the back end running locally on http://localhost:8081.
====
After doing this, we are going to add an environment variable with our base-URL for the REST services. This way we won't have to change every URL when we switch to production. Inside `environments/environment.ts` we add:
[source, typescript]
----
export const environment: {production: boolean, baseUrlRestServices: string} = {
production: false,
baseUrlRestServices: 'http://localhost:8081/jumpthequeue/services/rest'
};
----
Now in the service, we are going to add a `registerVisitor` method.
To call the server in this method we are going to inject the Angular `HttpClient` class from `@angular/common/http`. This class is the standard used by Angular to perform HTTP calls. The register call demands a `Visitor` model which we created in the `interfaces` file. We are going to build a POST call and send the information to the proper URL of the server service. The call will return an observable:
[source, typescript]
----
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Visitor} from 'src/app/shared/backendModels/interfaces';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class RegisterService {
private baseUrl = environment.baseUrlRestServices;
constructor(private http: HttpClient) { }
registerVisitor(visitor: Visitor): Observable {
return this.http.post(`${this.baseUrl}` + '/visitormanagement/v1/visitor', visitor);
}
}
----
This method will send our model to the backend and return an Observable that we will use on the `component.ts`.
[NOTE]
====
You have already learned about Observables and RxJs in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-services#server-communication[here]. +
You can go back and read that section again to refresh your memory.
====
Now we are going to modify `register.component.ts` to call this service:
[source, typescript]
----
import { Component, OnInit } from '@angular/core';
import { RegisterService } from './services/register.service';
import { Visitor } from '../shared/backendModels/interfaces';
import { Router } from '@angular/router';
import { MatSnackBar } from '@angular/material/snack-bar';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {
constructor(private registerService: RegisterService, private router: Router, public snackBar: MatSnackBar) { }
submitRegister(formValue): void {
const visitor: Visitor = new Visitor();
visitor.username = formValue.username;
visitor.name = formValue.name;
visitor.phoneNumber = formValue.phoneNumber;
visitor.password = formValue.password;
visitor.acceptedCommercial = formValue.acceptedCommercial;
visitor.acceptedTerms = formValue.acceptedTerms;
visitor.userType = false;
this.registerService.registerVisitor(visitor).subscribe(
(visitorResult: Visitor) => console.log(JSON.stringify(visitorResult)), // When call is received
(err) => this.snackBar.open(err.error.message, 'OK', {
duration: 5000,
}), // When theres an error
);
}
ngOnInit() {
}
}
----
In this file we injected `RegisterService` and `Router` to use them. Then, inside the method `submitRegister`, we created a visitor that we are going to pass to the service. We called the service method `registerVisitor`, we passed the visitor and we subscribed to the `Observable`, which we returned from the service. This subscription allows us to control three things:
. What to do when the data is received.
. What to do when there's an error.
. What to do when the call is complete.
Finally, we modify the `register.component.html` to send the form values to the method:
[source, html]
----
...