diff --git a/ch6/.gitignore b/ch6/.gitignore
new file mode 100644
index 0000000..8ca4c1a
--- /dev/null
+++ b/ch6/.gitignore
@@ -0,0 +1,27 @@
+# Compiled class file
+*.class
+
+# Log file
+*.log
+
+# Output files
+target/*
+
+# Package Files
+*.jar
+*.war
+*.nar
+*.ear
+*.zip
+*.tar.gz
+*.rar
+
+
+# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
+hs_err_pid*
+
+# IDE-specific files
+.classpath
+.project
+.settings/*
+/target/
diff --git a/ch6/LICENSE b/ch6/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/ch6/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/ch6/README.md b/ch6/README.md
new file mode 100644
index 0000000..e340565
--- /dev/null
+++ b/ch6/README.md
@@ -0,0 +1,31 @@
+# Sample code from Practical Cloud Native Development with MicroProfile 4.0, Chapter 6: Observing and Monitoring Cloud-Native Applications
+
+## Introduction
+
+The samples in this repository are intended to be a supplement to the book, _Practical Cloud Native Development with
+MicroProfile 4.0_ by Emily Jiang, Andy McCright, John Alcorn, David Chan, and Alasdair Nottingham. Chapter 6: Observing and Monitoring Cloud-Native Applications
+ discusses the various MicroProfile technologies that concentrate on the task of monitorng and observing your cloud-native application.
+This repo contains the sample code featured in this chapter with the exception of the single OpenTracing sample. The OpenTracing sample shown was purely for reference and is displayed in its entirety in the chapter.
+All samples run on the Open Liberty application server.
+
+## Running the samples
+
+In order to run these samples, you will need to use [Git](https://git-scm.com/) and [Maven](https://maven.apache.org/)
+along with a Java Development Kit v8 or higher - I recommend downloading from [AdoptOpenJDK](https://adoptopenjdk.net/).
+
+These samples are best run in an IDE like VS Code, Eclipse, Intelli-J, etc. That way, you can view the source code while
+running the sample in a separate window/tab.
+
+To build the code samples and start the server, use the command: `mvn clean package liberty:run`
+This will clean any previously built code, build the source code in the project, download the latest version of Open
+Liberty (unless previously downloaded), package the application into a server, and start the server. The first time you
+run this command may take a little while, but once Open Liberty has been downloaded and the server packaged, subsequent
+starts will be much faster.
+
+This command will run the server in the foreground. Once you see the magic message,
+`CWWKF0011I: The book server is ready to run a smarter planet.`, you are ready to test the application. By default, the
+server will listen on port 9080, so if you are attempting view the Health and Metrics data you would send a request to
+http://localhost:9080/health and http://localhost:9080/metrics respectively - you can put this directly in a web browser
+or invoke it from the command line with a tool like [curl](https://curl.se/).
+
+To stop the server in the current terminal window, press `Ctrl-C`.
\ No newline at end of file
diff --git a/ch6/pom.xml b/ch6/pom.xml
new file mode 100644
index 0000000..3a915a4
--- /dev/null
+++ b/ch6/pom.xml
@@ -0,0 +1,97 @@
+
+
+ 4.0.0
+ com.packt.microprofile
+ ch6
+ 1.0-SNAPSHOT
+ war
+
+ 3.2
+ 11
+ false
+ 11
+ [19.0.0.9,)
+ book
+
+
+
+ org.eclipse.microprofile
+ microprofile
+ 4.0.1
+ pom
+ provided
+
+
+ org.glassfish
+ javax.json
+ 1.1.4
+
+
+ org.eclipse
+ yasson
+ 1.0.8
+
+
+ org.reactivestreams
+ reactive-streams
+ 1.0.3
+ provided
+
+
+
+ book
+
+
+
+ liberty
+
+ true
+
+
+
+
+ io.openliberty.tools
+ liberty-maven-plugin
+ ${openliberty.maven.version}
+
+
+ package-server
+ package
+
+ create
+ install-feature
+ deploy
+ package
+
+
+ target/wlp-package
+
+
+
+
+ runnable
+ ${final.name}
+
+ ${final.name}
+ https://server.example.com
+
+
+
+
+
+
+
+ io.jaegertracing
+ jaeger-client
+ 1.6.0
+
+
+ org.slf4j
+ slf4j-jdk14
+ 1.7.25
+
+
+
+
+
diff --git a/ch6/src/main/java/com/packt/microprofile/book/ch6/health/CDIMethodProducerChecks.java b/ch6/src/main/java/com/packt/microprofile/book/ch6/health/CDIMethodProducerChecks.java
new file mode 100644
index 0000000..e1344b0
--- /dev/null
+++ b/ch6/src/main/java/com/packt/microprofile/book/ch6/health/CDIMethodProducerChecks.java
@@ -0,0 +1,33 @@
+package com.packt.microprofile.book.ch6.health;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.enterprise.inject.Produces;
+
+import org.eclipse.microprofile.health.HealthCheck;
+import org.eclipse.microprofile.health.HealthCheckResponse;
+import org.eclipse.microprofile.health.Liveness;
+import org.eclipse.microprofile.health.Readiness;
+
+@ApplicationScoped
+public class CDIMethodProducerChecks {
+
+ @Produces
+ @Liveness
+ HealthCheck livenessCDIMethodProducer() {
+ return () -> HealthCheckResponse.named("cdiMemoryUsage").status(getMemUsage() < 0.9).build();
+ }
+
+ @Produces
+ @Readiness
+ HealthCheck readinessCDIMethodProducer() {
+ return () -> HealthCheckResponse.named("cdiCpuUsage").status(getCpuUsage() < 0.9).build();
+ }
+
+ public Double getMemUsage() {
+ return Utility.getMemUsage();
+ }
+
+ public Double getCpuUsage() {
+ return Utility.getCpuUsage();
+ }
+}
diff --git a/ch6/src/main/java/com/packt/microprofile/book/ch6/health/LivenessCheck.java b/ch6/src/main/java/com/packt/microprofile/book/ch6/health/LivenessCheck.java
new file mode 100644
index 0000000..6796ed3
--- /dev/null
+++ b/ch6/src/main/java/com/packt/microprofile/book/ch6/health/LivenessCheck.java
@@ -0,0 +1,50 @@
+package com.packt.microprofile.book.ch6.health;
+
+import java.lang.management.ManagementFactory;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.management.AttributeNotFoundException;
+import javax.management.InstanceNotFoundException;
+import javax.management.MBeanException;
+import javax.management.MBeanServer;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+import javax.management.ReflectionException;
+import javax.management.openmbean.CompositeData;
+
+import org.eclipse.microprofile.health.HealthCheck;
+import org.eclipse.microprofile.health.HealthCheckResponse;
+import org.eclipse.microprofile.health.HealthCheckResponseBuilder;
+import org.eclipse.microprofile.health.Liveness;
+
+@ApplicationScoped
+@Liveness
+public class LivenessCheck implements HealthCheck {
+
+ public HealthCheckResponse call() {
+
+ // Percentage value from 0.0-1.0
+ Double memoryUsage = getMemUsage();
+
+ /*
+ * Alternatively, you can use the the below line instead which uses the status()
+ * method. No need for an if-else block!
+ */
+ // return HealthCheckResponse.builder().name("LivenessCheck").status(memoryUsage
+ // < 0.9).withData("MemoryUsage", memoryUsage.toString()).build();
+
+ HealthCheckResponseBuilder builder = HealthCheckResponse.named("LivenessCheck");
+ if (memoryUsage < 0.9) {
+ builder.up();
+ } else {
+ builder.down();
+ }
+ builder = builder.withData("MemoryUsage", memoryUsage.toString());
+ return builder.build();
+
+ }
+
+ public Double getMemUsage() {
+ return Utility.getMemUsage();
+ }
+}
diff --git a/ch6/src/main/java/com/packt/microprofile/book/ch6/health/ReadinessCheck.java b/ch6/src/main/java/com/packt/microprofile/book/ch6/health/ReadinessCheck.java
new file mode 100644
index 0000000..9a062a6
--- /dev/null
+++ b/ch6/src/main/java/com/packt/microprofile/book/ch6/health/ReadinessCheck.java
@@ -0,0 +1,23 @@
+package com.packt.microprofile.book.ch6.health;
+
+import javax.enterprise.context.ApplicationScoped;
+
+import org.eclipse.microprofile.health.HealthCheck;
+import org.eclipse.microprofile.health.HealthCheckResponse;
+import org.eclipse.microprofile.health.Readiness;
+
+@ApplicationScoped
+@Readiness
+public class ReadinessCheck implements HealthCheck {
+
+ final String NAME = "evenNumberPhobic";
+
+ public HealthCheckResponse call() {
+ long time = System.currentTimeMillis();
+
+ if (time % 2 == 0)
+ return HealthCheckResponse.down(NAME);
+ else
+ return HealthCheckResponse.up(NAME);
+ }
+}
diff --git a/ch6/src/main/java/com/packt/microprofile/book/ch6/health/Utility.java b/ch6/src/main/java/com/packt/microprofile/book/ch6/health/Utility.java
new file mode 100644
index 0000000..cfdf7c3
--- /dev/null
+++ b/ch6/src/main/java/com/packt/microprofile/book/ch6/health/Utility.java
@@ -0,0 +1,54 @@
+package com.packt.microprofile.book.ch6.health;
+
+import java.lang.management.ManagementFactory;
+
+import javax.management.AttributeNotFoundException;
+import javax.management.InstanceNotFoundException;
+import javax.management.MBeanException;
+import javax.management.MBeanServer;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+import javax.management.ReflectionException;
+import javax.management.openmbean.CompositeData;
+
+public class Utility {
+
+ public static Double getMemUsage() {
+ MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
+
+ CompositeData compositeData;
+ try {
+ compositeData = (CompositeData) mbeanServer.getAttribute(new ObjectName("java.lang:type=Memory"),
+ "HeapMemoryUsage");
+ Number heapUsed = (Number) compositeData.get("used");
+ compositeData = (CompositeData) mbeanServer.getAttribute(new ObjectName("java.lang:type=Memory"),
+ "HeapMemoryUsage");
+ Number heapMax = (Number) compositeData.get("max");
+ return heapUsed.doubleValue() / heapMax.doubleValue();
+ } catch (InstanceNotFoundException | AttributeNotFoundException | MalformedObjectNameException
+ | ReflectionException | MBeanException exception) {
+ exception.printStackTrace();
+ System.err.println(
+ "Encountered an error while retrieving Mbeans. Will default to a memory usage value of 0.5");
+ return 0.5;
+ }
+ }
+
+ public static Double getCpuUsage() {
+ MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
+
+ Number cpuLoad;
+ try {
+ cpuLoad = (Number) mbeanServer.getAttribute(new ObjectName("java.lang:type=OperatingSystem"),
+ "ProcessCpuLoad");
+ return cpuLoad.doubleValue();
+ } catch (InstanceNotFoundException | AttributeNotFoundException | MalformedObjectNameException
+ | ReflectionException | MBeanException e) {
+ e.printStackTrace();
+ System.err
+ .println("Encountered an error while retrieving Mbeans. Will default to a CPU usage value of 0.5");
+ return 0.5;
+ }
+
+ }
+}
diff --git a/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/ConcurrentGaugeAnnotatedResource.java b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/ConcurrentGaugeAnnotatedResource.java
new file mode 100644
index 0000000..225ea8b
--- /dev/null
+++ b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/ConcurrentGaugeAnnotatedResource.java
@@ -0,0 +1,40 @@
+package com.packt.microprofile.book.ch6.metrics;
+
+import org.eclipse.microprofile.metrics.annotation.ConcurrentGauge;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+
+@ApplicationScoped
+@Path("/concurrentGaugeAnnotatedResource")
+public class ConcurrentGaugeAnnotatedResource {
+
+ private final String CONCURRENTGAUGE_METRIC_NAME = "annotatedConcurrentGaugeMetric";
+
+ @GET
+ @Path("/concurrentGauge")
+ public String getConcurrentGauge(){
+ ExecutorService executorService = Executors.newCachedThreadPool();
+
+ Runnable sleeper = () -> sleeper();
+
+ for (int i = 0; i < 10; i++) {
+ executorService.submit(sleeper);
+ }
+
+ return "Concurrent Gauge created and invoked in parallel";
+ }
+
+ @ConcurrentGauge(name = CONCURRENTGAUGE_METRIC_NAME, absolute = true)
+ public void sleeper() {
+ try {
+ Thread.sleep(10000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+}
diff --git a/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/ConcurrentGaugeResource.java b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/ConcurrentGaugeResource.java
new file mode 100644
index 0000000..78de680
--- /dev/null
+++ b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/ConcurrentGaugeResource.java
@@ -0,0 +1,44 @@
+package com.packt.microprofile.book.ch6.metrics;
+
+import org.eclipse.microprofile.metrics.ConcurrentGauge;
+import org.eclipse.microprofile.metrics.MetricRegistry;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.inject.Inject;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+
+@ApplicationScoped
+@Path("/concurrentGaugeResource")
+public class ConcurrentGaugeResource {
+
+ @Inject
+ MetricRegistry metricRegistry;
+
+ private final String CONCURRENTGAUGE_METRIC_NAME = "concurrentGaugeMetric";
+ @GET
+ @Path("/concurrentGauge")
+ public String getConcurrentGage(){
+ ExecutorService executorService = Executors.newCachedThreadPool();
+
+ Runnable sleeper = () -> {
+ ConcurrentGauge concurrentGauge = metricRegistry.concurrentGauge(CONCURRENTGAUGE_METRIC_NAME);
+ concurrentGauge.inc();
+ try {
+ Thread.sleep(10000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ concurrentGauge.dec();
+ };
+
+ for (int i = 0; i < 10; i++) {
+ executorService.submit(sleeper);
+ }
+
+ return "Concurrent Gauge created and invoked in parallel";
+ }
+
+}
diff --git a/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/CounterAnnotatedResource.java b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/CounterAnnotatedResource.java
new file mode 100644
index 0000000..c86ff78
--- /dev/null
+++ b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/CounterAnnotatedResource.java
@@ -0,0 +1,19 @@
+package com.packt.microprofile.book.ch6.metrics;
+
+import org.eclipse.microprofile.metrics.annotation.Counted;
+import javax.enterprise.context.ApplicationScoped;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+
+@ApplicationScoped
+@Path("/counterAnnotatedResource")
+@Counted
+public class CounterAnnotatedResource {
+
+ @GET
+ @Path("/getResource")
+ public String getResource() {
+ return "Counting the class";
+ }
+}
+
diff --git a/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/CounterResource.java b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/CounterResource.java
new file mode 100644
index 0000000..c109c57
--- /dev/null
+++ b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/CounterResource.java
@@ -0,0 +1,52 @@
+package com.packt.microprofile.book.ch6.metrics;
+
+import org.eclipse.microprofile.metrics.Counter;
+import org.eclipse.microprofile.metrics.Metadata;
+import org.eclipse.microprofile.metrics.MetricID;
+import org.eclipse.microprofile.metrics.MetricRegistry;
+import org.eclipse.microprofile.metrics.MetricType;
+import org.eclipse.microprofile.metrics.Tag;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.inject.Inject;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+
+@ApplicationScoped
+@Path("/counterResource")
+public class CounterResource {
+
+ @Inject
+ MetricRegistry metricRegistry;
+
+ private final String COUNTER_METRIC_NAME = "counterMetric";
+ private final Tag COUNTER_TAG = new Tag("metricType", "counter");
+
+ @GET
+ @Path("/counter1")
+ public String getCounter1(){
+
+ Metadata counterMetadata = Metadata.builder()
+ .withName(COUNTER_METRIC_NAME)
+ .withType(MetricType.COUNTER)
+ .build();
+
+ Counter counter = metricRegistry.counter(counterMetadata, COUNTER_TAG);
+ counter.inc(); // increments by one
+
+ return "A counter metric has been created and incremented "
+ + "by 1, the total is now " + counter.getCount();
+ }
+
+ @GET
+ @Path("/counter2")
+ public String getCounter2(){
+ MetricID counterMetricID = new MetricID(COUNTER_METRIC_NAME, COUNTER_TAG);
+ Counter counter = metricRegistry.counter(counterMetricID);
+
+ counter.inc(3);
+
+ return "A counter metric was retrieve and incremented "
+ + "by 3, the total is now " + counter.getCount();
+ }
+}
diff --git a/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/GaugeResource.java b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/GaugeResource.java
new file mode 100644
index 0000000..c1f80c5
--- /dev/null
+++ b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/GaugeResource.java
@@ -0,0 +1,25 @@
+package com.packt.microprofile.book.ch6.metrics;
+
+import org.eclipse.microprofile.metrics.MetricUnits;
+import org.eclipse.microprofile.metrics.annotation.Gauge;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+
+@ApplicationScoped
+@Path("/gaugeResource")
+public class GaugeResource {
+
+ @Gauge(name="time.since.epoch", unit = MetricUnits.MILLISECONDS)
+ public long getGaugeWithAnnotations() {
+ return System.currentTimeMillis();
+ }
+
+ @GET
+ @Path("/gauge")
+ public String getGauge(){
+ return "Gauge Resource";
+ }
+
+}
diff --git a/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/HistogramResource.java b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/HistogramResource.java
new file mode 100644
index 0000000..ce609d2
--- /dev/null
+++ b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/HistogramResource.java
@@ -0,0 +1,47 @@
+package com.packt.microprofile.book.ch6.metrics;
+
+import org.eclipse.microprofile.metrics.Histogram;
+import org.eclipse.microprofile.metrics.Metadata;
+import org.eclipse.microprofile.metrics.MetricRegistry;
+import org.eclipse.microprofile.metrics.MetricType;
+import org.eclipse.microprofile.metrics.MetricUnits;
+import org.eclipse.microprofile.metrics.Snapshot;
+
+import java.util.Random;
+import javax.enterprise.context.ApplicationScoped;
+import javax.inject.Inject;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+
+@ApplicationScoped
+@Path("/histogramResource")
+public class HistogramResource {
+
+ @Inject
+ MetricRegistry metricRegistry;
+
+ private final String HISTOGRAM_METRIC_NAME = "histogramMetric";
+ @GET
+ @Path("/histogram")
+ public String getHistogram() {
+ Metadata histogramMetadata = Metadata.builder()
+ .withName(HISTOGRAM_METRIC_NAME)
+ .withUnit(MetricUnits.MILLISECONDS)
+ .withDescription("This histogram tracks random millesconds")
+ .withType(MetricType.HISTOGRAM).build();
+
+ Histogram histogram = metricRegistry.histogram(histogramMetadata);
+
+ Random random = new Random();
+ for (int i = 0; i < 1000 ; i++) {
+ int randomInt = random.nextInt(1000);
+ histogram.update(randomInt);
+ }
+
+ int count = (int) histogram.getCount(); //returns long value of count
+ Snapshot snapshot = histogram.getSnapshot(); //rest of the stats
+
+ return "Histogram created/retrieved and is tracking random milleseconds";
+ }
+
+}
diff --git a/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/MeterAnnotatedResource.java b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/MeterAnnotatedResource.java
new file mode 100644
index 0000000..6640296
--- /dev/null
+++ b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/MeterAnnotatedResource.java
@@ -0,0 +1,22 @@
+package com.packt.microprofile.book.ch6.metrics;
+
+import org.eclipse.microprofile.metrics.annotation.Metered;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+
+@ApplicationScoped
+@Path("/meterAnnotatedResource")
+public class MeterAnnotatedResource {
+
+ private final String METER_METRIC_NAME = "annotatedMeterMetric";
+
+ @GET
+ @Path("/meter")
+ @Metered(name=METER_METRIC_NAME, absolute=true, tags= {"metricType=meter"})
+ public String getMeterWithAnnotations() {
+ return "Meter created/retrieved and marked by 1 with annotations";
+ }
+
+}
diff --git a/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/MeterResource.java b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/MeterResource.java
new file mode 100644
index 0000000..529634d
--- /dev/null
+++ b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/MeterResource.java
@@ -0,0 +1,40 @@
+package com.packt.microprofile.book.ch6.metrics;
+
+import org.eclipse.microprofile.metrics.Meter;
+import org.eclipse.microprofile.metrics.MetricID;
+import org.eclipse.microprofile.metrics.MetricRegistry;
+import org.eclipse.microprofile.metrics.Tag;
+import javax.enterprise.context.ApplicationScoped;
+import javax.inject.Inject;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.QueryParam;
+
+@ApplicationScoped
+@Path("/meterResource")
+public class MeterResource {
+
+ @Inject
+ MetricRegistry metricRegistry;
+
+ private final String METER_METRIC_NAME = "meterMetric";
+ private final Tag METER_TAG = new Tag("metricType", "meter");
+
+ @GET
+ @Path("/meter")
+ public String getMeter() throws Exception {
+ Meter meter = metricRegistry.meter(METER_METRIC_NAME, METER_TAG);
+ meter.mark();
+ return "Meter created/retrieved and marked by 1";
+ }
+
+ @GET
+ @Path("/meter2")
+ public String getMeter2(@QueryParam("value") @DefaultValue("1") int value) throws Exception {
+ MetricID meterMetricID = new MetricID(METER_METRIC_NAME, METER_TAG);
+ Meter meter = metricRegistry.meter(meterMetricID);
+ meter.mark(value);
+ return "Meter created/retrieved and marked by " + value;
+ }
+}
\ No newline at end of file
diff --git a/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/MetricApplication.java b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/MetricApplication.java
new file mode 100644
index 0000000..3b25a63
--- /dev/null
+++ b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/MetricApplication.java
@@ -0,0 +1,10 @@
+package com.packt.microprofile.book.ch6.metrics;
+import javax.enterprise.context.ApplicationScoped;
+import javax.ws.rs.ApplicationPath;
+import javax.ws.rs.core.Application;;
+
+@ApplicationScoped
+@ApplicationPath("/")
+public class MetricApplication extends Application {
+
+}
\ No newline at end of file
diff --git a/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/MetricsResource.java b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/MetricsResource.java
new file mode 100644
index 0000000..5928667
--- /dev/null
+++ b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/MetricsResource.java
@@ -0,0 +1,62 @@
+package com.packt.microprofile.book.ch6.metrics;
+
+import org.eclipse.microprofile.metrics.Counter;
+import org.eclipse.microprofile.metrics.Metadata;
+import org.eclipse.microprofile.metrics.MetricID;
+import org.eclipse.microprofile.metrics.MetricRegistry;
+import org.eclipse.microprofile.metrics.MetricType;
+import org.eclipse.microprofile.metrics.MetricUnits;
+import org.eclipse.microprofile.metrics.Tag;
+import org.eclipse.microprofile.metrics.annotation.Metric;
+import org.eclipse.microprofile.metrics.annotation.RegistryType;
+import javax.enterprise.context.ApplicationScoped;
+import javax.inject.Inject;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+
+@ApplicationScoped
+@Path("/metricsResource")
+public class MetricsResource {
+
+ @Inject
+ @RegistryType(type = MetricRegistry.Type.APPLICATION)
+ MetricRegistry metricRegistry;
+
+ @GET
+ @Path("/")
+ public String getResource() {
+ return "Welcome to the Metrics playgorund";
+ }
+
+ /**
+ * Sample Metadata, Tag and MetricID creation.
+ */
+ public void metadataTagMetricIDExample() {
+ String metricName = "myMetric";
+ Metadata metadata = Metadata.builder().withName(metricName).withType(MetricType.INVALID)
+ .withDisplayName("Human readable display name")
+ .withDescription("This metadata example" + " demonstrates how to create a" + " Metadata object")
+ .withUnit(MetricUnits.NONE).build();
+
+ Tag tag = new Tag("tagKey", "tagValue");
+ Tag anotherTag = new Tag("anotherTag", "tagValue");
+
+ MetricID metricID = new MetricID(metricName, tag, anotherTag);
+ }
+
+ /*
+ * Sample injections using the @Metrics annotation
+ */
+
+ @Inject
+ @Metric(name = "fieldInjectedCounter")
+ Counter fieldInjectedCounter;
+
+ Counter parameterInjectedCounter;
+
+ @Inject
+ public void setCounterMetric(@Metric(name = "parameterInjectedCounter") Counter parameterInjectedCounter) {
+ this.parameterInjectedCounter = parameterInjectedCounter;
+ }
+
+}
diff --git a/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/TimersAnnotatedResource.java b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/TimersAnnotatedResource.java
new file mode 100644
index 0000000..55f07cf
--- /dev/null
+++ b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/TimersAnnotatedResource.java
@@ -0,0 +1,27 @@
+package com.packt.microprofile.book.ch6.metrics;
+
+import org.eclipse.microprofile.metrics.annotation.SimplyTimed;
+import org.eclipse.microprofile.metrics.annotation.Timed;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+
+@ApplicationScoped
+@Path("/timersAnnotatedResource")
+public class TimersAnnotatedResource {
+
+ private final String ANNOTATED_TIMER_METRIC_NAME = "annotatedTimerMetric";
+ private final String ANNOTATED_SIMPLETIMER_METRIC_NAME = "annotatedSimpleTimerMetric";
+
+ @GET
+ @Path("/timers")
+ @Timed(name=ANNOTATED_TIMER_METRIC_NAME, absolute=true)
+ @SimplyTimed(name= ANNOTATED_SIMPLETIMER_METRIC_NAME, absolute=true)
+ public String getTimerWithAnnotations() {
+ //some business logic to time
+ return "@Timed and @SimplyTimed";
+ }
+
+
+}
diff --git a/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/TimersResource.java b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/TimersResource.java
new file mode 100644
index 0000000..de15d44
--- /dev/null
+++ b/ch6/src/main/java/com/packt/microprofile/book/ch6/metrics/TimersResource.java
@@ -0,0 +1,62 @@
+package com.packt.microprofile.book.ch6.metrics;
+
+import org.eclipse.microprofile.metrics.MetricRegistry;
+import org.eclipse.microprofile.metrics.SimpleTimer;
+import org.eclipse.microprofile.metrics.Timer;
+
+import java.util.concurrent.Callable;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.inject.Inject;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+
+@ApplicationScoped
+@Path("/timersResource")
+public class TimersResource {
+
+ @Inject
+ MetricRegistry metricRegistry;
+
+ private final String TIMER_METRIC_NAME = "timerMetric";
+ private final String SIMPLETIMER_METRIC_NAME = "simpleTimerMetric";
+
+ @GET
+ @Path("/timer")
+ public String getTimer() {
+
+ Timer timer = metricRegistry.timer(TIMER_METRIC_NAME);
+ Timer.Context timerContext = timer.time();
+ timerContext.close();
+
+ Runnable runnableTimer = () -> {
+ try {
+ Thread.sleep(2000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ };
+
+ // Time a Runnable
+ timer.time(runnableTimer);
+ return "Timer created/retrieved and recorded total elapsed time of " + timer.getElapsedTime();
+ }
+
+ @GET
+ @Path("/simpleTimer")
+ public String getSimpleTimer() throws Exception {
+
+ SimpleTimer simpleTimer = metricRegistry.simpleTimer(SIMPLETIMER_METRIC_NAME);
+ SimpleTimer.Context simpleTimerContext = simpleTimer.time();
+ simpleTimerContext.close();
+
+ // Time a Callable
+ Callable callable = () -> {
+ Thread.sleep(2000);
+ return "Finished Callable";
+ };
+ simpleTimer.time(callable);
+
+ return "SimpleTimer created/retrieved and recorded total elapsed time of " + simpleTimer.getElapsedTime();
+ }
+}
diff --git a/ch6/src/main/liberty/config/server.xml b/ch6/src/main/liberty/config/server.xml
new file mode 100644
index 0000000..24bda5e
--- /dev/null
+++ b/ch6/src/main/liberty/config/server.xml
@@ -0,0 +1,27 @@
+
+
+
+
+ jaxrs-2.1
+ mpMetrics-3.0
+ mpHealth-3.0
+ cdi-2.0
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/ch6/src/main/resources/.gitkeep b/ch6/src/main/resources/.gitkeep
new file mode 100644
index 0000000..e69de29
diff --git a/ch6/src/main/resources/META-INF/microprofile-config.properties b/ch6/src/main/resources/META-INF/microprofile-config.properties
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/ch6/src/main/resources/META-INF/microprofile-config.properties
@@ -0,0 +1 @@
+
diff --git a/ch6/src/main/webapp/.gitkeep b/ch6/src/main/webapp/.gitkeep
new file mode 100644
index 0000000..e69de29
diff --git a/ch6/src/main/webapp/WEB-INF/beans.xml b/ch6/src/main/webapp/WEB-INF/beans.xml
new file mode 100644
index 0000000..2777559
--- /dev/null
+++ b/ch6/src/main/webapp/WEB-INF/beans.xml
@@ -0,0 +1,6 @@
+
+
+