instance_id
stringlengths 17
39
| repo
stringclasses 8
values | issue_id
stringlengths 14
34
| pr_id
stringlengths 14
34
| linking_methods
sequencelengths 1
3
| base_commit
stringlengths 40
40
| merge_commit
stringlengths 0
40
⌀ | hints_text
sequencelengths 0
106
| resolved_comments
sequencelengths 0
119
| created_at
unknown | labeled_as
sequencelengths 0
7
| problem_title
stringlengths 7
174
| problem_statement
stringlengths 0
55.4k
| gold_files
sequencelengths 0
10
| gold_files_postpatch
sequencelengths 1
10
| test_files
sequencelengths 0
60
| gold_patch
stringlengths 220
5.83M
| test_patch
stringlengths 386
194k
⌀ | split_random
stringclasses 3
values | split_time
stringclasses 3
values | issue_start_time
unknown | issue_created_at
unknown | issue_by_user
stringlengths 3
21
| split_repo
stringclasses 3
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pinpoint-apm/pinpoint/4630_4694 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4630 | pinpoint-apm/pinpoint/4694 | [
"keyword_issue_to_pr"
] | f1e3a14ea2e65945f456c9aacc995a968a3dd0e0 | 071836693df5dd563215b9422ef33869c6cf52d5 | [
"I found that there isn't \" java.lang.management\" in the IBM JDK 1.6\r\nSo pp-agent can't suppot the IBM JDK 1.6, is it right?\r\n@emeroad\r\n\r\n![image](https://user-images.githubusercontent.com/20055737/45656389-b891b980-bb17-11e8-8dea-83252f1d77ca.png)\r\n\r\n\r\n![image](https://user-images.githubusercontent.com/20055737/45656365-926c1980-bb17-11e8-9786-46846331ec02.png)\r\n",
"@shenhongwei33 @chuanyi-fang \r\nLooks like your version of ibm java 6 does not have the method above.\r\nWe'll fix the startup error in the next version.\r\n\r\nIn the mean time, could you try it again with the jdk 6 downloaded from the ibm website?\r\nThanks.",
"#3579 ",
"This issue/proposal has been automatically marked as stale because it hasn't had any recent activity. It will automatically be closed if no further activity occurs for 20days. If you think this should still be open, or the problem still persists, just pop a reply in the comments and one of the maintainers will (try!) to follow up. Thank you for your interest and contribution to the Pinpoint Community.\n",
"resolved via #4694 "
] | [] | "2018-10-01T10:01:03Z" | [
"stale"
] | Pinpoint Agent load failure | WebSphere Platform 7.0.0.0 [ND 7.0.0.0 r0835.03] running with process name spark-w1Node01Cell\spark-w1Node01\server1 and process id 10489
Host Operating System is Linux, version 3.10.0-327.28.3.el7.x86_64
Java version = 1.6.0, Java Compiler = j9jit24, Java VM name = IBM J9 VM
was.install.root = /data/WAS
user.install.root = /data/WAS/profiles/AppSrv01
Java Home = /data/WAS/java/jre
ws.ext.dirs = /data/WAS/java/lib:/data/WAS/profiles/AppSrv01/classes:/data/WAS/classes:/data/WAS/lib:/data/WAS/installedChannels:/data/WAS/lib/ext:/data/WAS/web/help:/data/WAS/deploytool/itp/plugins/com.ibm.etools.ejbdeploy/runtime
Classpath = /data/WAS/profiles/AppSrv01/properties:/data/WAS/properties:/data/WAS/lib/startup.jar:/data/WAS/lib/bootstrap.jar:/data/WAS/lib/jsf-nls.jar:/data/WAS/lib/lmproxy.jar:/data/WAS/lib/urlprotocols.jar:/data/WAS/deploytool/itp/batchboot.jar:/data/WAS/deploytool/itp/batch2.jar:/data/WAS/java/lib/tools.jar:/data/pinpoint-agent/pinpoint-bootstrap-1.5.0.jar:/data/pinpoint-agent/pinpoint-bootstrap-1.5.0.jar
Java Library path = /data/WAS/java/jre/lib/amd64/compressedrefs:/data/WAS/java/jre/lib/amd64:/data/WAS/bin::/usr/lib
************* End Display Current Environment *************
2018-09-17 19:56:47 [WARN ](com.navercorp.pinpoint.bootstrap.PinpointStarter) pinpoint start failed.
com.navercorp.pinpoint.bootstrap.BootStrapException: execute fail. Error:null
at com.navercorp.pinpoint.bootstrap.ContextClassLoaderExecuteTemplate.execute(ContextClassLoaderExecuteTemplate.java:52)
at com.navercorp.pinpoint.bootstrap.AgentClassLoader.boot(AgentClassLoader.java:73)
at com.navercorp.pinpoint.bootstrap.PinpointStarter.start(PinpointStarter.java:125)
at com.navercorp.pinpoint.bootstrap.PinpointBootStrap.premain(PinpointBootStrap.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:45)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:599)
at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:335)
at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:350)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:45)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:39)
at java.lang.reflect.Constructor.newInstance(Constructor.java:515)
at com.navercorp.pinpoint.bootstrap.AgentClassLoader$2.call(AgentClassLoader.java:78)
at com.navercorp.pinpoint.bootstrap.ContextClassLoaderExecuteTemplate.execute(ContextClassLoaderExecuteTemplate.java:42)
... 9 more
Caused by: com.google.inject.CreationException: Unable to create injector, see the following errors:
1) Error injecting constructor, java.lang.NoSuchMethodError: com/ibm/lang/management/OperatingSystemMXBean.getProcessCpuTimeByNS()J
at com.navercorp.pinpoint.profiler.monitor.DefaultAgentStatMonitor.<init>(DefaultAgentStatMonitor.java:63)
while locating com.navercorp.pinpoint.profiler.monitor.DefaultAgentStatMonitor
at com.navercorp.pinpoint.profiler.context.module.ApplicationContextModule.configure(ApplicationContextModule.java:258)
while locating com.navercorp.pinpoint.profiler.monitor.AgentStatMonitor
1 error
at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:470)
at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:184)
at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:110)
at com.google.inject.Guice.createInjector(Guice.java:99)
at com.google.inject.Guice.createInjector(Guice.java:84)
at com.navercorp.pinpoint.profiler.context.module.DefaultApplicationContext.<init>(DefaultApplicationContext.java:102)
at com.navercorp.pinpoint.profiler.context.module.DefaultApplicationContext.<init>(DefaultApplicationContext.java:86)
at com.navercorp.pinpoint.profiler.DefaultAgent.newApplicationContext(DefaultAgent.java:125)
at com.navercorp.pinpoint.profiler.DefaultAgent.<init>(DefaultAgent.java:118)
at com.navercorp.pinpoint.profiler.DefaultAgent.<init>(DefaultAgent.java:69)
... 15 more
Caused by: java.lang.NoSuchMethodError: com/ibm/lang/management/OperatingSystemMXBean.getProcessCpuTimeByNS()J
at com.navercorp.pinpoint.profiler.monitor.metric.cpu.ibm.Java6CpuLoadMetric.getSnapshot(Java6CpuLoadMetric.java:47)
at com.navercorp.pinpoint.profiler.monitor.collector.cpu.DefaultCpuLoadMetricCollector.collect(DefaultCpuLoadMetricCollector.java:40)
at com.navercorp.pinpoint.profiler.monitor.collector.cpu.DefaultCpuLoadMetricCollector.collect(DefaultCpuLoadMetricCollector.java:26)
at com.navercorp.pinpoint.profiler.monitor.collector.AgentStatCollector.collect(AgentStatCollector.java:99)
at com.navercorp.pinpoint.profiler.monitor.collector.AgentStatCollector.collect(AgentStatCollector.java:34)
at com.navercorp.pinpoint.profiler.monitor.CollectJob.run(CollectJob.java:67)
at com.navercorp.pinpoint.profiler.monitor.DefaultAgentStatMonitor.preLoadClass(DefaultAgentStatMonitor.java:104)
at com.navercorp.pinpoint.profiler.monitor.DefaultAgentStatMonitor.<init>(DefaultAgentStatMonitor.java:91)
at com.navercorp.pinpoint.profiler.monitor.DefaultAgentStatMonitor.<init>(DefaultAgentStatMonitor.java:63)
at com.navercorp.pinpoint.profiler.monitor.DefaultAgentStatMonitor$$FastClassByGuice$$1e15b61b.newInstance(<generated>)
at com.google.inject.internal.DefaultConstructionProxyFactory$FastClassProxy.newInstance(DefaultConstructionProxyFactory.java:89)
at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:111)
at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:90)
at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:268)
at com.google.inject.internal.FactoryProxy.get(FactoryProxy.java:56)
at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:46)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1092)
at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:194)
at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:41)
at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:205)
at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:199)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1085)
at com.google.inject.internal.InternalInjectorCreator.loadEagerSingletons(InternalInjectorCreator.java:199)
at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:180)
... 23 more
*****************************************************************************
* Pinpoint Agent load failure
*****************************************************************************
How to solve this problem?
| [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java",
"commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java"
] | [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java",
"commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/CpuUsageProvider.java"
] | [] | diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java
index f16ce008cb6e..da036fdac33a 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java
@@ -16,6 +16,9 @@
package com.navercorp.pinpoint.bootstrap.classloader;
+import com.navercorp.pinpoint.common.util.JvmType;
+import com.navercorp.pinpoint.common.util.JvmUtils;
+
/**
* @author Woonduk Kang(emeroad)
*/
@@ -40,17 +43,8 @@ public static BootLoader newBootLoader() {
}
private static boolean isJ9VM() {
- // ibm-j9 java.vm.name=IBM J9 VM;
- // openj9 java.vm.name=Eclipse OpenJ9 VM
-// if (System.getProperty("java.vm.name", "").contains("J9 VM")) {
-// return true;
-// }
- try {
- ClassLoader.class.getDeclaredField("bootstrapClassLoader");
- return true;
- } catch (NoSuchFieldException e) {
- return false;
- }
+ JvmType jvmType = JvmUtils.getType();
+ return jvmType == JvmType.IBM;
}
}
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java
index b615eaeae1e7..b0e11b3aa218 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java
@@ -44,12 +44,19 @@ public class J9BootLoader implements BootLoader {
}
private static ClassLoader findBootstrapClassLoader() {
+ Field bootstrapClassLoader;
+ try {
+ bootstrapClassLoader = ClassLoader.class.getDeclaredField("bootstrapClassLoader");
+ } catch (NoSuchFieldException e) {
+ try {
+ bootstrapClassLoader = ClassLoader.class.getDeclaredField("systemClassLoader");
+ } catch (NoSuchFieldException e2) {
+ throw new IllegalStateException("bootstrapClassLoader not found Caused by:" + e.getMessage() + ", and " + e2.getMessage(), e2);
+ }
+ }
try {
- Field bootstrapClassLoader = ClassLoader.class.getDeclaredField("bootstrapClassLoader");
bootstrapClassLoader.setAccessible(true);
return (ClassLoader) bootstrapClassLoader.get(ClassLoader.class);
- } catch (NoSuchFieldException e) {
- throw new IllegalStateException("bootstrapClassLoader not found Caused by:" + e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new IllegalStateException("bootstrapClassLoader access fail Caused by:" + e.getMessage(), e);
}
diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java
index a63af83b5fe7..2537eb561172 100644
--- a/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java
+++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java
@@ -23,7 +23,9 @@
*/
public enum JvmType {
UNKNOWN(null),
- IBM("IBM"),
+ // ibm-j9 java.vm.name=IBM J9 VM;
+ // openj9 java.vm.name=Eclipse OpenJ9 VM
+ IBM("J9"),
OPENJDK("OpenJDK"),
ORACLE("HotSpot");
diff --git a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java
index cee669e9b80e..a4c2bdf899c0 100644
--- a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java
+++ b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java
@@ -46,12 +46,14 @@ public double getJvmCpuUsage(final long cpuTimeNS, final long upTimeMS) {
final long diffUpTimeMS = upTimeMS - lastUpTimeMS;
final long totalUpTimeNS = (diffUpTimeMS * 1000000) * CPU_COUNT;
- final double cpuLoad = totalUpTimeNS > 0 ?
- Math.min(100F, totalCpuTimeNS / (float) totalUpTimeNS) : UNSUPPORTED;
+ double cpuUsage = UNSUPPORTED;
+ if (totalUpTimeNS > 0) {
+ cpuUsage = Math.min(100F, totalCpuTimeNS / (float) totalUpTimeNS);
+ }
this.lastCpuTimeNS = cpuTimeNS;
this.lastUpTimeMS = upTimeMS;
- return cpuLoad;
+ return cpuUsage;
}
}
diff --git a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java
index 6faf29537b21..d54426415f4c 100644
--- a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java
+++ b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java
@@ -16,11 +16,15 @@
package com.navercorp.pinpoint.profiler.monitor.metric.cpu.ibm;
+import com.ibm.lang.management.OperatingSystemMXBean;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetric;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetricSnapshot;
+import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuUsageProvider;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.JvmCpuUsageCalculator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-import java.lang.management.OperatingSystemMXBean;
+import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
/**
@@ -28,32 +32,58 @@
*/
public class Java6CpuLoadMetric implements CpuLoadMetric {
- private final JvmCpuUsageCalculator jvmCpuUsageCalculator = new JvmCpuUsageCalculator();
- private final com.ibm.lang.management.OperatingSystemMXBean operatingSystemMXBean;
- private final RuntimeMXBean runtimeMXBean;
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
- public Java6CpuLoadMetric(OperatingSystemMXBean operatingSystemMXBean, RuntimeMXBean runtimeMXBean) {
+ private CpuUsageProvider jvmCpuUsageProvider;
+
+ public Java6CpuLoadMetric() {
+ final OperatingSystemMXBean operatingSystemMXBean = (com.ibm.lang.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
if (operatingSystemMXBean == null) {
- throw new NullPointerException("operatingSystemMXBean must not be null");
+ throw new IllegalStateException("OperatingSystemMXBean not available");
+ }
+ RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
+ if (runtimeMXBean == null) {
+ throw new IllegalStateException("RuntimeMXBean not available");
}
- this.operatingSystemMXBean = (com.ibm.lang.management.OperatingSystemMXBean) operatingSystemMXBean;
- this.runtimeMXBean = runtimeMXBean;
+
+ CpuUsageProvider jvmCpuUsageProvider = new JvmCpuUsageProvider(operatingSystemMXBean, runtimeMXBean);
+ try {
+ jvmCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving jvm cpu usage. Cause : {}", e.getMessage());
+ jvmCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
+ }
+ this.jvmCpuUsageProvider = jvmCpuUsageProvider;
}
@Override
public CpuLoadMetricSnapshot getSnapshot() {
- double jvmCpuUsage = UNCOLLECTED_USAGE;
- if (runtimeMXBean != null) {
- long cpuTimeNS = operatingSystemMXBean.getProcessCpuTimeByNS();
- long upTimeMS = runtimeMXBean.getUptime();
- jvmCpuUsage = jvmCpuUsageCalculator.getJvmCpuUsage(cpuTimeNS, upTimeMS);
- }
- double systemCpuUsage = operatingSystemMXBean.getSystemCpuLoad();
- return new CpuLoadMetricSnapshot(jvmCpuUsage, systemCpuUsage);
+ double jvmCpuUsage = jvmCpuUsageProvider.getCpuUsage();
+ return new CpuLoadMetricSnapshot(jvmCpuUsage, UNCOLLECTED_USAGE);
}
@Override
public String toString() {
return "CpuLoadMetric for IBM Java 1.6";
}
+
+ private static class JvmCpuUsageProvider implements CpuUsageProvider {
+
+ private final JvmCpuUsageCalculator jvmCpuUsageCalculator = new JvmCpuUsageCalculator();
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+ private final RuntimeMXBean runtimeMXBean;
+
+ private JvmCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean, RuntimeMXBean runtimeMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ this.runtimeMXBean = runtimeMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ long cpuTimeNS = operatingSystemMXBean.getProcessCpuTimeByNS();
+ long upTimeMS = runtimeMXBean.getUptime();
+ return jvmCpuUsageCalculator.getJvmCpuUsage(cpuTimeNS, upTimeMS);
+ }
+ }
}
diff --git a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java
index e3fe36eef104..d4f9ee627ac1 100644
--- a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java
+++ b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java
@@ -18,9 +18,13 @@
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetric;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetricSnapshot;
+import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuUsageProvider;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.JvmCpuUsageCalculator;
+import com.sun.management.OperatingSystemMXBean;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-import java.lang.management.OperatingSystemMXBean;
+import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
/**
@@ -28,32 +32,58 @@
*/
public class Java6CpuLoadMetric implements CpuLoadMetric {
- private final JvmCpuUsageCalculator jvmCpuUsageCalculator = new JvmCpuUsageCalculator();
- private final com.sun.management.OperatingSystemMXBean operatingSystemMXBean;
- private final RuntimeMXBean runtimeMXBean;
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
- public Java6CpuLoadMetric(OperatingSystemMXBean operatingSystemMXBean, RuntimeMXBean runtimeMXBean) {
+ private final CpuUsageProvider jvmCpuUsageProvider;
+
+ public Java6CpuLoadMetric() {
+ final OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
if (operatingSystemMXBean == null) {
- throw new NullPointerException("operatingSystemMXBean must not be null");
+ throw new IllegalStateException("OperatingSystemMXBean not available");
+ }
+ final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
+ if (runtimeMXBean == null) {
+ throw new IllegalStateException("RuntimeMXBean not available");
}
- this.operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) operatingSystemMXBean;
- this.runtimeMXBean = runtimeMXBean;
+
+ CpuUsageProvider jvmCpuUsageProvider = new JvmCpuUsageProvider(operatingSystemMXBean, runtimeMXBean);
+ try {
+ jvmCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving jvm cpu usage. Cause : {}", e.getMessage());
+ jvmCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
+ }
+ this.jvmCpuUsageProvider = jvmCpuUsageProvider;
}
@Override
public CpuLoadMetricSnapshot getSnapshot() {
- double jvmCpuUsage = UNCOLLECTED_USAGE;
- if (runtimeMXBean != null) {
- long cpuTimeNS = operatingSystemMXBean.getProcessCpuTime();
- long upTimeMS = runtimeMXBean.getUptime();
- jvmCpuUsage = jvmCpuUsageCalculator.getJvmCpuUsage(cpuTimeNS, upTimeMS);
- }
- double systemCpuUsage = UNCOLLECTED_USAGE;
- return new CpuLoadMetricSnapshot(jvmCpuUsage, systemCpuUsage);
+ double jvmCpuUsage = jvmCpuUsageProvider.getCpuUsage();
+ return new CpuLoadMetricSnapshot(jvmCpuUsage, UNCOLLECTED_USAGE);
}
@Override
public String toString() {
return "CpuLoadMetric for Oracle Java 1.6";
}
+
+ private static class JvmCpuUsageProvider implements CpuUsageProvider {
+
+ private final JvmCpuUsageCalculator jvmCpuUsageCalculator = new JvmCpuUsageCalculator();
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+ private final RuntimeMXBean runtimeMXBean;
+
+ private JvmCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean, RuntimeMXBean runtimeMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ this.runtimeMXBean = runtimeMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ long cpuTimeNS = operatingSystemMXBean.getProcessCpuTime();
+ long upTimeMS = runtimeMXBean.getUptime();
+ return jvmCpuUsageCalculator.getJvmCpuUsage(cpuTimeNS, upTimeMS);
+ }
+ }
}
diff --git a/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java b/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java
index 7d6abb3b2c8b..1baeb68910f1 100644
--- a/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java
+++ b/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java
@@ -16,29 +16,54 @@
package com.navercorp.pinpoint.profiler.monitor.metric.cpu.ibm;
+import com.ibm.lang.management.OperatingSystemMXBean;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetric;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetricSnapshot;
+import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuUsageProvider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-import java.lang.management.OperatingSystemMXBean;
+import java.lang.management.ManagementFactory;
/**
* @author HyunGil Jeong
*/
public class DefaultCpuLoadMetric implements CpuLoadMetric {
- private final com.ibm.lang.management.OperatingSystemMXBean operatingSystemMXBean;
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
- public DefaultCpuLoadMetric(OperatingSystemMXBean operatingSystemMXBean) {
+ private final CpuUsageProvider jvmCpuUsageProvider;
+ private final CpuUsageProvider systemCpuUsageProvider;
+
+ public DefaultCpuLoadMetric() {
+ final OperatingSystemMXBean operatingSystemMXBean = (com.ibm.lang.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
if (operatingSystemMXBean == null) {
- throw new NullPointerException("operatingSystemMXBean must not be null");
+ throw new IllegalStateException("OperatingSystemMXBean not available");
+ }
+
+ CpuUsageProvider jvmCpuUsageProvider = new JvmCpuUsageProvider(operatingSystemMXBean);
+ try {
+ jvmCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving jvm cpu usage. Cause : {}", e.getMessage());
+ jvmCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
+ }
+ this.jvmCpuUsageProvider = jvmCpuUsageProvider;
+
+ CpuUsageProvider systemCpuUsageProvider = new SystemCpuUsageProvider(operatingSystemMXBean);
+ try {
+ systemCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving system cpu usage. Cause : {}", e.getMessage());
+ systemCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
}
- this.operatingSystemMXBean = (com.ibm.lang.management.OperatingSystemMXBean) operatingSystemMXBean;
+ this.systemCpuUsageProvider = systemCpuUsageProvider;
}
@Override
public CpuLoadMetricSnapshot getSnapshot() {
- double jvmCpuUsage = operatingSystemMXBean.getProcessCpuLoad();
- double systemCpuUsage = operatingSystemMXBean.getSystemCpuLoad();
+ double jvmCpuUsage = jvmCpuUsageProvider.getCpuUsage();
+ double systemCpuUsage = systemCpuUsageProvider.getCpuUsage();
return new CpuLoadMetricSnapshot(jvmCpuUsage, systemCpuUsage);
}
@@ -46,4 +71,32 @@ public CpuLoadMetricSnapshot getSnapshot() {
public String toString() {
return "CpuLoadMetric for IBM Java 1.7+";
}
+
+ private static class JvmCpuUsageProvider implements CpuUsageProvider {
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+
+ private JvmCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ return operatingSystemMXBean.getProcessCpuLoad();
+ }
+ }
+
+ private static class SystemCpuUsageProvider implements CpuUsageProvider {
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+
+ private SystemCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ return operatingSystemMXBean.getSystemCpuLoad();
+ }
+ }
}
diff --git a/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java b/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java
index 9954ba770128..5f3d011674a4 100644
--- a/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java
+++ b/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java
@@ -18,27 +18,52 @@
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetric;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetricSnapshot;
+import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuUsageProvider;
+import com.sun.management.OperatingSystemMXBean;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-import java.lang.management.OperatingSystemMXBean;
+import java.lang.management.ManagementFactory;
/**
* @author HyunGil Jeong
*/
public class DefaultCpuLoadMetric implements CpuLoadMetric {
- private final com.sun.management.OperatingSystemMXBean operatingSystemMXBean;
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
- public DefaultCpuLoadMetric(OperatingSystemMXBean operatingSystemMXBean) {
+ private final CpuUsageProvider jvmCpuUsageProvider;
+ private final CpuUsageProvider systemCpuUsageProvider;
+
+ public DefaultCpuLoadMetric() {
+ final OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
if (operatingSystemMXBean == null) {
- throw new NullPointerException("operatingSystemMXBean must not be null");
+ throw new IllegalStateException("OperatingSystemMXBean not available");
+ }
+
+ CpuUsageProvider jvmCpuUsageProvider = new JvmCpuUsageProvider(operatingSystemMXBean);
+ try {
+ jvmCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving jvm cpu usage. Cause : {}", e.getMessage());
+ jvmCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
+ }
+ this.jvmCpuUsageProvider = jvmCpuUsageProvider;
+
+ CpuUsageProvider systemCpuUsageProvider = new SystemCpuUsageProvider(operatingSystemMXBean);
+ try {
+ systemCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving system cpu usage. Cause : {}", e.getMessage());
+ systemCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
}
- this.operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) operatingSystemMXBean;
+ this.systemCpuUsageProvider = systemCpuUsageProvider;
}
@Override
public CpuLoadMetricSnapshot getSnapshot() {
- double jvmCpuUsage = operatingSystemMXBean.getProcessCpuLoad();
- double systemCpuUsage = operatingSystemMXBean.getSystemCpuLoad();
+ double jvmCpuUsage = jvmCpuUsageProvider.getCpuUsage();
+ double systemCpuUsage = systemCpuUsageProvider.getCpuUsage();
return new CpuLoadMetricSnapshot(jvmCpuUsage, systemCpuUsage);
}
@@ -46,4 +71,32 @@ public CpuLoadMetricSnapshot getSnapshot() {
public String toString() {
return "CpuLoadMetric for Oracle Java 1.7+";
}
+
+ private static class JvmCpuUsageProvider implements CpuUsageProvider {
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+
+ private JvmCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ return operatingSystemMXBean.getProcessCpuLoad();
+ }
+ }
+
+ private static class SystemCpuUsageProvider implements CpuUsageProvider {
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+
+ private SystemCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ return operatingSystemMXBean.getSystemCpuLoad();
+ }
+ }
}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java
index 322e31d4b252..f4d6faa4db26 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java
@@ -26,9 +26,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.lang.management.ManagementFactory;
-import java.lang.management.OperatingSystemMXBean;
-import java.lang.management.RuntimeMXBean;
import java.lang.reflect.Constructor;
/**
@@ -85,27 +82,15 @@ private CpuLoadMetric createCpuLoadMetric(String classToLoad) {
if (classToLoad == null) {
return CpuLoadMetric.UNSUPPORTED_CPU_LOAD_METRIC;
}
- OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
- if (operatingSystemMXBean == null) {
- return CpuLoadMetric.UNSUPPORTED_CPU_LOAD_METRIC;
- }
try {
@SuppressWarnings("unchecked")
Class<CpuLoadMetric> cpuLoadMetricClass = (Class<CpuLoadMetric>) Class.forName(classToLoad);
try {
- // Create CpuLoadMetric for Java 7+
- Constructor<CpuLoadMetric> cpuLoadMetricConstructor = cpuLoadMetricClass.getConstructor(OperatingSystemMXBean.class);
- return cpuLoadMetricConstructor.newInstance(operatingSystemMXBean);
- } catch (NoSuchMethodException e1) {
- try {
- // Create CpuLoadMetric for Java 6
- RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
- Constructor<CpuLoadMetric> cpuLoadMetricConstructor = cpuLoadMetricClass.getConstructor(OperatingSystemMXBean.class, RuntimeMXBean.class);
- return cpuLoadMetricConstructor.newInstance(operatingSystemMXBean, runtimeMXBean);
- } catch (NoSuchMethodException e2) {
- logger.warn("Unknown CpuLoadMetric : {}", classToLoad);
- return CpuLoadMetric.UNSUPPORTED_CPU_LOAD_METRIC;
- }
+ Constructor<CpuLoadMetric> cpuLoadMetricConstructor = cpuLoadMetricClass.getConstructor();
+ return cpuLoadMetricConstructor.newInstance();
+ } catch (NoSuchMethodException e) {
+ logger.warn("Unknown CpuLoadMetric : {}", classToLoad);
+ return CpuLoadMetric.UNSUPPORTED_CPU_LOAD_METRIC;
}
} catch (Exception e) {
logger.warn("Error creating CpuLoadMetric [" + classToLoad + "]", e);
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/CpuUsageProvider.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/CpuUsageProvider.java
new file mode 100644
index 000000000000..66f0717134d1
--- /dev/null
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/CpuUsageProvider.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * 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.
+ */
+
+package com.navercorp.pinpoint.profiler.monitor.metric.cpu;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface CpuUsageProvider {
+
+ double getCpuUsage();
+
+ CpuUsageProvider UNSUPPORTED = new CpuUsageProvider() {
+ @Override
+ public double getCpuUsage() {
+ return CpuLoadMetric.UNCOLLECTED_USAGE;
+ }
+ };
+}
| null | train | test | "2018-10-01T10:11:31" | "2018-09-17T12:38:45Z" | ghost | test |
pinpoint-apm/pinpoint/3579_4694 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/3579 | pinpoint-apm/pinpoint/4694 | [
"keyword_issue_to_pr"
] | f1e3a14ea2e65945f456c9aacc995a968a3dd0e0 | 071836693df5dd563215b9422ef33869c6cf52d5 | [
"Hi @saver123sc \r\nDoes the problem exist in 1.6.2?\r\n\r\nCould you check your jre for `long com.ibm.lang.management.OperatingSystemMXBean.getProcessCpuTimeByNS()` method? \r\nIt should be there as per the [documentation]( https://www.ibm.com/support/knowledgecenter/en/SSYKE2_6.0.0/com.ibm.java.api.60.doc/com.ibm.lang.management/com/ibm/lang/management/OperatingSystemMXBean.html).\r\n\r\nCould you also post your agent log so we can take a look at it? (The log file is located under *$PINPOINT_AGENT/log* directory).\r\n\r\nIn the mean time, you could also try setting `profiler.jvm.vendor.name=oracle` in *pinpoint.config* and see if that works.\r\nThanks.",
"@Xylus \r\n\r\nThank you,Problems on websphere7, I have solved it by reshipment wesphere\r\n",
"Glad to hear you worked it out :+1: ",
"> @Xylus\r\n> \r\n> Thank you,Problems on websphere7, I have solved it by reshipment wesphere\r\n\r\nI also get this problem. And how to solve it.",
"@chuanyi-fang I think some versions of ibm java 7 does not have the method above, causing startup failure.\r\nThe issue will be fixed next version.\r\n\r\nIn the mean time, please try downloading the jdk 7 from the ibm website and try again.\r\nPlease check #4585 for more detail.",
"I have found the method in the \"jlm.jar\" of WAS's \"jre.pak\".And solved now.\r\n![image](https://user-images.githubusercontent.com/20055737/45728906-b5242e00-bbfc-11e8-83dd-c0f372bca988.png)\r\n",
"resolved via #4694 "
] | [] | "2018-10-01T10:01:03Z" | [
"question"
] | pinpoint start failed. | After deploymented agent1.70 ,the following error after start the websphere server:
native_stderr.log:
2017-11-21 14:40:30 [WARN ](com.navercorp.pinpoint.bootstrap.PinpointStarter) pinpoint start failed.
com.navercorp.pinpoint.bootstrap.BootStrapException: execute fail. Error:null
at com.navercorp.pinpoint.bootstrap.ContextClassLoaderExecuteTemplate.execute(ContextClassLoaderExecuteTemplate.java:52)
at com.navercorp.pinpoint.bootstrap.AgentClassLoader.boot(AgentClassLoader.java:73)
at com.navercorp.pinpoint.bootstrap.PinpointStarter.start(PinpointStarter.java:125)
at com.navercorp.pinpoint.bootstrap.PinpointBootStrap.premain(PinpointBootStrap.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:45)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:599)
at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:335)
at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:350)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:45)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:39)
at java.lang.reflect.Constructor.newInstance(Constructor.java:515)
at com.navercorp.pinpoint.bootstrap.AgentClassLoader$2.call(AgentClassLoader.java:78)
at com.navercorp.pinpoint.bootstrap.ContextClassLoaderExecuteTemplate.execute(ContextClassLoaderExecuteTemplate.java:42)
... 9 more
Caused by: com.google.inject.CreationException: Unable to create injector, see the following errors:
1) Error injecting constructor, java.lang.NoSuchMethodError: com/ibm/lang/management/OperatingSystemMXBean.getProcessCpuTimeByNS()J
at com.navercorp.pinpoint.profiler.monitor.DefaultAgentStatMonitor.<init>(DefaultAgentStatMonitor.java:63)
while locating com.navercorp.pinpoint.profiler.monitor.DefaultAgentStatMonitor
at com.navercorp.pinpoint.profiler.context.module.ApplicationContextModule.configure(ApplicationContextModule.java:258)
while locating com.navercorp.pinpoint.profiler.monitor.AgentStatMonitor
1 error
at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:470)
at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:184)
at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:110)
at com.google.inject.Guice.createInjector(Guice.java:99)
at com.google.inject.Guice.createInjector(Guice.java:84)
at com.navercorp.pinpoint.profiler.context.module.DefaultApplicationContext.<init>(DefaultApplicationContext.java:102)
at com.navercorp.pinpoint.profiler.context.module.DefaultApplicationContext.<init>(DefaultApplicationContext.java:86)
at com.navercorp.pinpoint.profiler.DefaultAgent.newApplicationContext(DefaultAgent.java:125)
at com.navercorp.pinpoint.profiler.DefaultAgent.<init>(DefaultAgent.java:118)
at com.navercorp.pinpoint.profiler.DefaultAgent.<init>(DefaultAgent.java:69)
... 15 more
Caused by: java.lang.NoSuchMethodError: com/ibm/lang/management/OperatingSystemMXBean.getProcessCpuTimeByNS()J
at com.navercorp.pinpoint.profiler.monitor.metric.cpu.ibm.Java6CpuLoadMetric.getSnapshot(Java6CpuLoadMetric.java:47)
at com.navercorp.pinpoint.profiler.monitor.collector.cpu.DefaultCpuLoadMetricCollector.collect(DefaultCpuLoadMetricCollector.java:40)
at com.navercorp.pinpoint.profiler.monitor.collector.cpu.DefaultCpuLoadMetricCollector.collect(DefaultCpuLoadMetricCollector.java:26)
at com.navercorp.pinpoint.profiler.monitor.collector.AgentStatCollector.collect(AgentStatCollector.java:99)
at com.navercorp.pinpoint.profiler.monitor.collector.AgentStatCollector.collect(AgentStatCollector.java:34)
at com.navercorp.pinpoint.profiler.monitor.CollectJob.run(CollectJob.java:67)
at com.navercorp.pinpoint.profiler.monitor.DefaultAgentStatMonitor.preLoadClass(DefaultAgentStatMonitor.java:104)
at com.navercorp.pinpoint.profiler.monitor.DefaultAgentStatMonitor.<init>(DefaultAgentStatMonitor.java:91)
at com.navercorp.pinpoint.profiler.monitor.DefaultAgentStatMonitor.<init>(DefaultAgentStatMonitor.java:63)
at com.navercorp.pinpoint.profiler.monitor.DefaultAgentStatMonitor$$FastClassByGuice$$1e15b61b.newInstance(<generated>)
at com.google.inject.internal.DefaultConstructionProxyFactory$FastClassProxy.newInstance(DefaultConstructionProxyFactory.java:89)
at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:111)
at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:90)
at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:268)
at com.google.inject.internal.FactoryProxy.get(FactoryProxy.java:56)
at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:46)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1092)
at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:194)
at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:41)
at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:205)
at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:199)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1085)
at com.google.inject.internal.InternalInjectorCreator.loadEagerSingletons(InternalInjectorCreator.java:199)
at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:180)
... 23 more
*****************************************************************************
* Pinpoint Agent load failure
*****************************************************************************
************ Start Display Current Environment ************
WebSphere Platform 7.0.0.0 [ND 7.0.0.0 r0835.03] running with process name saverNode01Cell\saverNode01\server1 and process id 16969
Host Operating System is Linux, version 3.10.0-693.el7.x86_64
Java version = 1.6.0, Java Compiler = j9jit24, Java VM name = IBM J9 VM
was.install.root = /opt/IBM/WebSphere/AppServer
user.install.root = /opt/IBM/WebSphere/AppServer/profiles/test01
Java Home = /opt/IBM/WebSphere/AppServer/java/jre
ws.ext.dirs = /opt/IBM/WebSphere/AppServer/java/lib:/opt/IBM/WebSphere/AppServer/profiles/test01/classes:/opt/IBM/WebSphere/AppServer/classes:/opt/IBM/WebSphere/AppServer/lib:/opt/IBM/WebSphere/AppServer/installedChannels:/opt/IBM/WebSphere/AppServer/lib/ext:/opt/IBM/WebSphere/AppServer/web/help:/opt/IBM/WebSphere/AppServer/deploytool/itp/plugins/com.ibm.etools.ejbdeploy/runtime
Classpath = /opt/IBM/WebSphere/AppServer/profiles/test01/properties:/opt/IBM/WebSphere/AppServer/properties:/opt/IBM/WebSphere/AppServer/lib/startup.jar:/opt/IBM/WebSphere/AppServer/lib/bootstrap.jar:/opt/IBM/WebSphere/AppServer/lib/jsf-nls.jar:/opt/IBM/WebSphere/AppServer/lib/lmproxy.jar:/opt/IBM/WebSphere/AppServer/lib/urlprotocols.jar:/opt/IBM/WebSphere/AppServer/deploytool/itp/batchboot.jar:/opt/IBM/WebSphere/AppServer/deploytool/itp/batch2.jar:/opt/IBM/WebSphere/AppServer/java/lib/tools.jar:/data/pp-agent/pinpoint-bootstrap-1.7.0-SNAPSHOT.jar:/data/pp-agent/pinpoint-bootstrap-1.7.0-SNAPSHOT.jar
Java Library path = /opt/IBM/WebSphere/AppServer/java/jre/lib/amd64/compressedrefs:/opt/IBM/WebSphere/AppServer/java/jre/lib/amd64:/opt/IBM/WebSphere/AppServer/bin::/usr/lib
************* End Display Current Environment ************* | [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java",
"commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java"
] | [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java",
"commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java",
"profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/CpuUsageProvider.java"
] | [] | diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java
index f16ce008cb6e..da036fdac33a 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/BootLoaderFactory.java
@@ -16,6 +16,9 @@
package com.navercorp.pinpoint.bootstrap.classloader;
+import com.navercorp.pinpoint.common.util.JvmType;
+import com.navercorp.pinpoint.common.util.JvmUtils;
+
/**
* @author Woonduk Kang(emeroad)
*/
@@ -40,17 +43,8 @@ public static BootLoader newBootLoader() {
}
private static boolean isJ9VM() {
- // ibm-j9 java.vm.name=IBM J9 VM;
- // openj9 java.vm.name=Eclipse OpenJ9 VM
-// if (System.getProperty("java.vm.name", "").contains("J9 VM")) {
-// return true;
-// }
- try {
- ClassLoader.class.getDeclaredField("bootstrapClassLoader");
- return true;
- } catch (NoSuchFieldException e) {
- return false;
- }
+ JvmType jvmType = JvmUtils.getType();
+ return jvmType == JvmType.IBM;
}
}
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java
index b615eaeae1e7..b0e11b3aa218 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/classloader/J9BootLoader.java
@@ -44,12 +44,19 @@ public class J9BootLoader implements BootLoader {
}
private static ClassLoader findBootstrapClassLoader() {
+ Field bootstrapClassLoader;
+ try {
+ bootstrapClassLoader = ClassLoader.class.getDeclaredField("bootstrapClassLoader");
+ } catch (NoSuchFieldException e) {
+ try {
+ bootstrapClassLoader = ClassLoader.class.getDeclaredField("systemClassLoader");
+ } catch (NoSuchFieldException e2) {
+ throw new IllegalStateException("bootstrapClassLoader not found Caused by:" + e.getMessage() + ", and " + e2.getMessage(), e2);
+ }
+ }
try {
- Field bootstrapClassLoader = ClassLoader.class.getDeclaredField("bootstrapClassLoader");
bootstrapClassLoader.setAccessible(true);
return (ClassLoader) bootstrapClassLoader.get(ClassLoader.class);
- } catch (NoSuchFieldException e) {
- throw new IllegalStateException("bootstrapClassLoader not found Caused by:" + e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new IllegalStateException("bootstrapClassLoader access fail Caused by:" + e.getMessage(), e);
}
diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java
index a63af83b5fe7..2537eb561172 100644
--- a/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java
+++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmType.java
@@ -23,7 +23,9 @@
*/
public enum JvmType {
UNKNOWN(null),
- IBM("IBM"),
+ // ibm-j9 java.vm.name=IBM J9 VM;
+ // openj9 java.vm.name=Eclipse OpenJ9 VM
+ IBM("J9"),
OPENJDK("OpenJDK"),
ORACLE("HotSpot");
diff --git a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java
index cee669e9b80e..a4c2bdf899c0 100644
--- a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java
+++ b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/JvmCpuUsageCalculator.java
@@ -46,12 +46,14 @@ public double getJvmCpuUsage(final long cpuTimeNS, final long upTimeMS) {
final long diffUpTimeMS = upTimeMS - lastUpTimeMS;
final long totalUpTimeNS = (diffUpTimeMS * 1000000) * CPU_COUNT;
- final double cpuLoad = totalUpTimeNS > 0 ?
- Math.min(100F, totalCpuTimeNS / (float) totalUpTimeNS) : UNSUPPORTED;
+ double cpuUsage = UNSUPPORTED;
+ if (totalUpTimeNS > 0) {
+ cpuUsage = Math.min(100F, totalCpuTimeNS / (float) totalUpTimeNS);
+ }
this.lastCpuTimeNS = cpuTimeNS;
this.lastUpTimeMS = upTimeMS;
- return cpuLoad;
+ return cpuUsage;
}
}
diff --git a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java
index 6faf29537b21..d54426415f4c 100644
--- a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java
+++ b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/Java6CpuLoadMetric.java
@@ -16,11 +16,15 @@
package com.navercorp.pinpoint.profiler.monitor.metric.cpu.ibm;
+import com.ibm.lang.management.OperatingSystemMXBean;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetric;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetricSnapshot;
+import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuUsageProvider;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.JvmCpuUsageCalculator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-import java.lang.management.OperatingSystemMXBean;
+import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
/**
@@ -28,32 +32,58 @@
*/
public class Java6CpuLoadMetric implements CpuLoadMetric {
- private final JvmCpuUsageCalculator jvmCpuUsageCalculator = new JvmCpuUsageCalculator();
- private final com.ibm.lang.management.OperatingSystemMXBean operatingSystemMXBean;
- private final RuntimeMXBean runtimeMXBean;
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
- public Java6CpuLoadMetric(OperatingSystemMXBean operatingSystemMXBean, RuntimeMXBean runtimeMXBean) {
+ private CpuUsageProvider jvmCpuUsageProvider;
+
+ public Java6CpuLoadMetric() {
+ final OperatingSystemMXBean operatingSystemMXBean = (com.ibm.lang.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
if (operatingSystemMXBean == null) {
- throw new NullPointerException("operatingSystemMXBean must not be null");
+ throw new IllegalStateException("OperatingSystemMXBean not available");
+ }
+ RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
+ if (runtimeMXBean == null) {
+ throw new IllegalStateException("RuntimeMXBean not available");
}
- this.operatingSystemMXBean = (com.ibm.lang.management.OperatingSystemMXBean) operatingSystemMXBean;
- this.runtimeMXBean = runtimeMXBean;
+
+ CpuUsageProvider jvmCpuUsageProvider = new JvmCpuUsageProvider(operatingSystemMXBean, runtimeMXBean);
+ try {
+ jvmCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving jvm cpu usage. Cause : {}", e.getMessage());
+ jvmCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
+ }
+ this.jvmCpuUsageProvider = jvmCpuUsageProvider;
}
@Override
public CpuLoadMetricSnapshot getSnapshot() {
- double jvmCpuUsage = UNCOLLECTED_USAGE;
- if (runtimeMXBean != null) {
- long cpuTimeNS = operatingSystemMXBean.getProcessCpuTimeByNS();
- long upTimeMS = runtimeMXBean.getUptime();
- jvmCpuUsage = jvmCpuUsageCalculator.getJvmCpuUsage(cpuTimeNS, upTimeMS);
- }
- double systemCpuUsage = operatingSystemMXBean.getSystemCpuLoad();
- return new CpuLoadMetricSnapshot(jvmCpuUsage, systemCpuUsage);
+ double jvmCpuUsage = jvmCpuUsageProvider.getCpuUsage();
+ return new CpuLoadMetricSnapshot(jvmCpuUsage, UNCOLLECTED_USAGE);
}
@Override
public String toString() {
return "CpuLoadMetric for IBM Java 1.6";
}
+
+ private static class JvmCpuUsageProvider implements CpuUsageProvider {
+
+ private final JvmCpuUsageCalculator jvmCpuUsageCalculator = new JvmCpuUsageCalculator();
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+ private final RuntimeMXBean runtimeMXBean;
+
+ private JvmCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean, RuntimeMXBean runtimeMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ this.runtimeMXBean = runtimeMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ long cpuTimeNS = operatingSystemMXBean.getProcessCpuTimeByNS();
+ long upTimeMS = runtimeMXBean.getUptime();
+ return jvmCpuUsageCalculator.getJvmCpuUsage(cpuTimeNS, upTimeMS);
+ }
+ }
}
diff --git a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java
index e3fe36eef104..d4f9ee627ac1 100644
--- a/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java
+++ b/profiler-optional/profiler-optional-jdk6/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/Java6CpuLoadMetric.java
@@ -18,9 +18,13 @@
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetric;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetricSnapshot;
+import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuUsageProvider;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.JvmCpuUsageCalculator;
+import com.sun.management.OperatingSystemMXBean;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-import java.lang.management.OperatingSystemMXBean;
+import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
/**
@@ -28,32 +32,58 @@
*/
public class Java6CpuLoadMetric implements CpuLoadMetric {
- private final JvmCpuUsageCalculator jvmCpuUsageCalculator = new JvmCpuUsageCalculator();
- private final com.sun.management.OperatingSystemMXBean operatingSystemMXBean;
- private final RuntimeMXBean runtimeMXBean;
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
- public Java6CpuLoadMetric(OperatingSystemMXBean operatingSystemMXBean, RuntimeMXBean runtimeMXBean) {
+ private final CpuUsageProvider jvmCpuUsageProvider;
+
+ public Java6CpuLoadMetric() {
+ final OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
if (operatingSystemMXBean == null) {
- throw new NullPointerException("operatingSystemMXBean must not be null");
+ throw new IllegalStateException("OperatingSystemMXBean not available");
+ }
+ final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
+ if (runtimeMXBean == null) {
+ throw new IllegalStateException("RuntimeMXBean not available");
}
- this.operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) operatingSystemMXBean;
- this.runtimeMXBean = runtimeMXBean;
+
+ CpuUsageProvider jvmCpuUsageProvider = new JvmCpuUsageProvider(operatingSystemMXBean, runtimeMXBean);
+ try {
+ jvmCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving jvm cpu usage. Cause : {}", e.getMessage());
+ jvmCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
+ }
+ this.jvmCpuUsageProvider = jvmCpuUsageProvider;
}
@Override
public CpuLoadMetricSnapshot getSnapshot() {
- double jvmCpuUsage = UNCOLLECTED_USAGE;
- if (runtimeMXBean != null) {
- long cpuTimeNS = operatingSystemMXBean.getProcessCpuTime();
- long upTimeMS = runtimeMXBean.getUptime();
- jvmCpuUsage = jvmCpuUsageCalculator.getJvmCpuUsage(cpuTimeNS, upTimeMS);
- }
- double systemCpuUsage = UNCOLLECTED_USAGE;
- return new CpuLoadMetricSnapshot(jvmCpuUsage, systemCpuUsage);
+ double jvmCpuUsage = jvmCpuUsageProvider.getCpuUsage();
+ return new CpuLoadMetricSnapshot(jvmCpuUsage, UNCOLLECTED_USAGE);
}
@Override
public String toString() {
return "CpuLoadMetric for Oracle Java 1.6";
}
+
+ private static class JvmCpuUsageProvider implements CpuUsageProvider {
+
+ private final JvmCpuUsageCalculator jvmCpuUsageCalculator = new JvmCpuUsageCalculator();
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+ private final RuntimeMXBean runtimeMXBean;
+
+ private JvmCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean, RuntimeMXBean runtimeMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ this.runtimeMXBean = runtimeMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ long cpuTimeNS = operatingSystemMXBean.getProcessCpuTime();
+ long upTimeMS = runtimeMXBean.getUptime();
+ return jvmCpuUsageCalculator.getJvmCpuUsage(cpuTimeNS, upTimeMS);
+ }
+ }
}
diff --git a/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java b/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java
index 7d6abb3b2c8b..1baeb68910f1 100644
--- a/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java
+++ b/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/ibm/DefaultCpuLoadMetric.java
@@ -16,29 +16,54 @@
package com.navercorp.pinpoint.profiler.monitor.metric.cpu.ibm;
+import com.ibm.lang.management.OperatingSystemMXBean;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetric;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetricSnapshot;
+import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuUsageProvider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-import java.lang.management.OperatingSystemMXBean;
+import java.lang.management.ManagementFactory;
/**
* @author HyunGil Jeong
*/
public class DefaultCpuLoadMetric implements CpuLoadMetric {
- private final com.ibm.lang.management.OperatingSystemMXBean operatingSystemMXBean;
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
- public DefaultCpuLoadMetric(OperatingSystemMXBean operatingSystemMXBean) {
+ private final CpuUsageProvider jvmCpuUsageProvider;
+ private final CpuUsageProvider systemCpuUsageProvider;
+
+ public DefaultCpuLoadMetric() {
+ final OperatingSystemMXBean operatingSystemMXBean = (com.ibm.lang.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
if (operatingSystemMXBean == null) {
- throw new NullPointerException("operatingSystemMXBean must not be null");
+ throw new IllegalStateException("OperatingSystemMXBean not available");
+ }
+
+ CpuUsageProvider jvmCpuUsageProvider = new JvmCpuUsageProvider(operatingSystemMXBean);
+ try {
+ jvmCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving jvm cpu usage. Cause : {}", e.getMessage());
+ jvmCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
+ }
+ this.jvmCpuUsageProvider = jvmCpuUsageProvider;
+
+ CpuUsageProvider systemCpuUsageProvider = new SystemCpuUsageProvider(operatingSystemMXBean);
+ try {
+ systemCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving system cpu usage. Cause : {}", e.getMessage());
+ systemCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
}
- this.operatingSystemMXBean = (com.ibm.lang.management.OperatingSystemMXBean) operatingSystemMXBean;
+ this.systemCpuUsageProvider = systemCpuUsageProvider;
}
@Override
public CpuLoadMetricSnapshot getSnapshot() {
- double jvmCpuUsage = operatingSystemMXBean.getProcessCpuLoad();
- double systemCpuUsage = operatingSystemMXBean.getSystemCpuLoad();
+ double jvmCpuUsage = jvmCpuUsageProvider.getCpuUsage();
+ double systemCpuUsage = systemCpuUsageProvider.getCpuUsage();
return new CpuLoadMetricSnapshot(jvmCpuUsage, systemCpuUsage);
}
@@ -46,4 +71,32 @@ public CpuLoadMetricSnapshot getSnapshot() {
public String toString() {
return "CpuLoadMetric for IBM Java 1.7+";
}
+
+ private static class JvmCpuUsageProvider implements CpuUsageProvider {
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+
+ private JvmCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ return operatingSystemMXBean.getProcessCpuLoad();
+ }
+ }
+
+ private static class SystemCpuUsageProvider implements CpuUsageProvider {
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+
+ private SystemCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ return operatingSystemMXBean.getSystemCpuLoad();
+ }
+ }
}
diff --git a/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java b/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java
index 9954ba770128..5f3d011674a4 100644
--- a/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java
+++ b/profiler-optional/profiler-optional-jdk7/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/oracle/DefaultCpuLoadMetric.java
@@ -18,27 +18,52 @@
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetric;
import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuLoadMetricSnapshot;
+import com.navercorp.pinpoint.profiler.monitor.metric.cpu.CpuUsageProvider;
+import com.sun.management.OperatingSystemMXBean;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-import java.lang.management.OperatingSystemMXBean;
+import java.lang.management.ManagementFactory;
/**
* @author HyunGil Jeong
*/
public class DefaultCpuLoadMetric implements CpuLoadMetric {
- private final com.sun.management.OperatingSystemMXBean operatingSystemMXBean;
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
- public DefaultCpuLoadMetric(OperatingSystemMXBean operatingSystemMXBean) {
+ private final CpuUsageProvider jvmCpuUsageProvider;
+ private final CpuUsageProvider systemCpuUsageProvider;
+
+ public DefaultCpuLoadMetric() {
+ final OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
if (operatingSystemMXBean == null) {
- throw new NullPointerException("operatingSystemMXBean must not be null");
+ throw new IllegalStateException("OperatingSystemMXBean not available");
+ }
+
+ CpuUsageProvider jvmCpuUsageProvider = new JvmCpuUsageProvider(operatingSystemMXBean);
+ try {
+ jvmCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving jvm cpu usage. Cause : {}", e.getMessage());
+ jvmCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
+ }
+ this.jvmCpuUsageProvider = jvmCpuUsageProvider;
+
+ CpuUsageProvider systemCpuUsageProvider = new SystemCpuUsageProvider(operatingSystemMXBean);
+ try {
+ systemCpuUsageProvider.getCpuUsage();
+ } catch (NoSuchMethodError e) {
+ logger.warn("Expected method not found for retrieving system cpu usage. Cause : {}", e.getMessage());
+ systemCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
}
- this.operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) operatingSystemMXBean;
+ this.systemCpuUsageProvider = systemCpuUsageProvider;
}
@Override
public CpuLoadMetricSnapshot getSnapshot() {
- double jvmCpuUsage = operatingSystemMXBean.getProcessCpuLoad();
- double systemCpuUsage = operatingSystemMXBean.getSystemCpuLoad();
+ double jvmCpuUsage = jvmCpuUsageProvider.getCpuUsage();
+ double systemCpuUsage = systemCpuUsageProvider.getCpuUsage();
return new CpuLoadMetricSnapshot(jvmCpuUsage, systemCpuUsage);
}
@@ -46,4 +71,32 @@ public CpuLoadMetricSnapshot getSnapshot() {
public String toString() {
return "CpuLoadMetric for Oracle Java 1.7+";
}
+
+ private static class JvmCpuUsageProvider implements CpuUsageProvider {
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+
+ private JvmCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ return operatingSystemMXBean.getProcessCpuLoad();
+ }
+ }
+
+ private static class SystemCpuUsageProvider implements CpuUsageProvider {
+
+ private final OperatingSystemMXBean operatingSystemMXBean;
+
+ private SystemCpuUsageProvider(OperatingSystemMXBean operatingSystemMXBean) {
+ this.operatingSystemMXBean = operatingSystemMXBean;
+ }
+
+ @Override
+ public double getCpuUsage() {
+ return operatingSystemMXBean.getSystemCpuLoad();
+ }
+ }
}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java
index 322e31d4b252..f4d6faa4db26 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/stat/cpu/CpuLoadMetricProvider.java
@@ -26,9 +26,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.lang.management.ManagementFactory;
-import java.lang.management.OperatingSystemMXBean;
-import java.lang.management.RuntimeMXBean;
import java.lang.reflect.Constructor;
/**
@@ -85,27 +82,15 @@ private CpuLoadMetric createCpuLoadMetric(String classToLoad) {
if (classToLoad == null) {
return CpuLoadMetric.UNSUPPORTED_CPU_LOAD_METRIC;
}
- OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
- if (operatingSystemMXBean == null) {
- return CpuLoadMetric.UNSUPPORTED_CPU_LOAD_METRIC;
- }
try {
@SuppressWarnings("unchecked")
Class<CpuLoadMetric> cpuLoadMetricClass = (Class<CpuLoadMetric>) Class.forName(classToLoad);
try {
- // Create CpuLoadMetric for Java 7+
- Constructor<CpuLoadMetric> cpuLoadMetricConstructor = cpuLoadMetricClass.getConstructor(OperatingSystemMXBean.class);
- return cpuLoadMetricConstructor.newInstance(operatingSystemMXBean);
- } catch (NoSuchMethodException e1) {
- try {
- // Create CpuLoadMetric for Java 6
- RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
- Constructor<CpuLoadMetric> cpuLoadMetricConstructor = cpuLoadMetricClass.getConstructor(OperatingSystemMXBean.class, RuntimeMXBean.class);
- return cpuLoadMetricConstructor.newInstance(operatingSystemMXBean, runtimeMXBean);
- } catch (NoSuchMethodException e2) {
- logger.warn("Unknown CpuLoadMetric : {}", classToLoad);
- return CpuLoadMetric.UNSUPPORTED_CPU_LOAD_METRIC;
- }
+ Constructor<CpuLoadMetric> cpuLoadMetricConstructor = cpuLoadMetricClass.getConstructor();
+ return cpuLoadMetricConstructor.newInstance();
+ } catch (NoSuchMethodException e) {
+ logger.warn("Unknown CpuLoadMetric : {}", classToLoad);
+ return CpuLoadMetric.UNSUPPORTED_CPU_LOAD_METRIC;
}
} catch (Exception e) {
logger.warn("Error creating CpuLoadMetric [" + classToLoad + "]", e);
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/CpuUsageProvider.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/CpuUsageProvider.java
new file mode 100644
index 000000000000..66f0717134d1
--- /dev/null
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/metric/cpu/CpuUsageProvider.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * 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.
+ */
+
+package com.navercorp.pinpoint.profiler.monitor.metric.cpu;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface CpuUsageProvider {
+
+ double getCpuUsage();
+
+ CpuUsageProvider UNSUPPORTED = new CpuUsageProvider() {
+ @Override
+ public double getCpuUsage() {
+ return CpuLoadMetric.UNCOLLECTED_USAGE;
+ }
+ };
+}
| null | train | test | "2018-10-01T10:11:31" | "2017-11-21T07:54:36Z" | saver123sc | test |
pinpoint-apm/pinpoint/4698_4699 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4698 | pinpoint-apm/pinpoint/4699 | [
"keyword_pr_to_issue"
] | 6f136c24ff92d6641a12f46fa132c9e09c336a30 | 5448471fd5fdc1711f27b9919dcb6c94ded18cc6 | [
"Hello, @bbvch13531 \r\n\r\nOf course, Go ahead. Let us know when you finish",
"Hi @RoySRose, Thank you for your kind answer. 😃 \r\nI send PR #4699. \r\nPTAL!"
] | [] | "2018-10-03T03:01:12Z" | [] | There are typo in doc/per-request_feature_guide.md | <!--
Please be as detailed as possible so that we can help answer your question as quickly as possible.
-->
There are typo in doc/per-request_feature_guide.md
line 288: `로그 메세지` -> `log message` for consistency
line 289: `출려된` -> `출력된` typo
line 511: `추가되야` -> `추가돼야` typo
Also other spacing grammer errors exist.
May I correct typo and send pull request?
I already signed CLA. | [
"doc/per-request_feature_guide.md"
] | [
"doc/per-request_feature_guide.md"
] | [] | diff --git a/doc/per-request_feature_guide.md b/doc/per-request_feature_guide.md
index 0aff94bcb84a..6731d35e4d45 100644
--- a/doc/per-request_feature_guide.md
+++ b/doc/per-request_feature_guide.md
@@ -279,18 +279,18 @@ For details in how the log buttons are generated, please refer to Pinpoint Web
### 1. 기능 설명
-Pinpoint에서는 log message를 request 단위로 구분할 수 있도록 log message 에 추가정보를 저장 해준다.
+Pinpoint에서는 log message를 request 단위로 구분할 수 있도록 log message 에 추가정보를 저장해준다.
다수의 요청을 처리하는 tomcat을 사용할 경우 로그 파일을 보면 시간순으로 출력된 로그를 확인할 수 있다.
그러나 동시에 요청된 다수의 request 각각에 대한 로그를 구분 해서 볼 수 없다.
-예를 들어 로그에서 exception message가 출력됐을때 그 exception이 발생한 request의 모든 log를 확인 하기 힘들다.
+예를 들어 로그에서 exception message가 출력됐을 때 그 exception이 발생한 request의 모든 log를 확인하기 힘들다.
-Pinpoint는 로그 메세지 마다 request와 연관된 정보(transactionId, spanId)를 MDC에 넣어줘서 request 단위로 log message를 구분할 수 있도록 해준다.
-로그에 출력된 transactionId는 pinpoint web의 transaction List 화면에 출려된 transactionId와 일치한다.
+Pinpoint는 log message 마다 request와 연관된 정보(transactionId, spanId)를 MDC에 넣어줘서 request 단위로 log message를 구분할 수 있도록 해준다.
+로그에 출력된 transactionId는 pinpoint web의 transaction List 화면에 출력된 transactionId와 일치한다.
구체적으로 예를 들어보자.
-Pinpoint를 사용하지 않았을때 exception이 발생했을 경우 로그 메시지를 살펴 보자.
-요청된 다수의 request 각각을 구분하여 로그를 확인 할 수가 없다.
+Pinpoint를 사용하지 않았을 때 exception이 발생했을 경우 로그 메시지를 살펴 보자.
+요청된 다수의 request 각각을 구분하여 로그를 확인할 수가 없다.
ex) Without Pinpoint
```
@@ -391,7 +391,7 @@ ex) With Pinpoint
**2-1 Pinpoint agent 설정**
-Pinpoint를 사용하려면 Pinpoint agent 설정파일(Pinpoint.config)의 logging 설정 값을 true로 변경해야한다.
+Pinpoint를 사용하려면 Pinpoint agent 설정파일(Pinpoint.config)의 logging 설정 값을 true로 변경해야 한다.
사용하는 logging 라이브러리에 해당하는 설정값만 true로 변경하면 된다.
아래 설정에 대한 예시가 있다.
@@ -508,7 +508,7 @@ log.button.name=log
**step 3**
pinpoint 1.5 이후 버전부터 log 기록 여부에 따라 log 버튼의 활성화가 결정되도록 개선 됐기 때문에
당신이 사용하는 logging appender의 로깅 메소드에 logging 여부를 저장하는 interceptor를 추가하는 플러그인을 개발해야 한다.
-플러그인 개발 방법은 다음 링크를 참고하면 된다([Link](https://github.com/naver/pinpoint-plugin-sample)). interceptor 로직이 추가되야 하는 위치는 appender class 내에 LoggingEvent 객체의 데이터를 이용하여 로깅을 하는 메소드다.
+플러그인 개발 방법은 다음 링크를 참고하면 된다([Link](https://github.com/naver/pinpoint-plugin-sample)). interceptor 로직이 추가돼야 하는 위치는 appender class 내에 LoggingEvent 객체의 데이터를 이용하여 로깅을 하는 메소드다.
아래는 interceptor 예제이다.
```
public class AppenderInterceptor implements AroundInterceptor0 {
| null | test | test | "2018-10-02T07:09:12" | "2018-10-03T02:57:40Z" | bbvch13531 | test |
pinpoint-apm/pinpoint/4755_4763 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4755 | pinpoint-apm/pinpoint/4763 | [
"keyword_pr_to_issue"
] | adb4cc9a1a7e0a820f43aa6cb63ed4ee4e111cfb | 0c579d661a55e8444c97483d2d407052987bc723 | [] | [] | "2018-10-17T09:54:25Z" | [
"enhancement",
"module:plugin"
] | Add support for spring-amqp-rabbit 2.1.0.RELEASE | #### Description
Constructor for `org.springframework.amqp.rabbit.support.Delivery` got an extra parameter in 2.1.0.RELEASE.
`org.springframework.amqp.rabbit.listener.BlockingQueueConsumer$ConsumerDecorator` has been removed in 2.1.0.RELEASE. | [
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java"
] | [
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java"
] | [
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_1_7_7_to_2_0_0_IT.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_0_3_to_2_1_0_IT.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_1_x_to_2_x_IT.java"
] | diff --git a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java
index fe0a042d21ef..930eb5699c53 100644
--- a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java
+++ b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/RabbitMQClientPlugin.java
@@ -384,6 +384,11 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
if (constructor != null) {
constructor.addScopedInterceptor("com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.DeliveryConstructInterceptor", RabbitMQClientConstants.RABBITMQ_CONSUMER_SCOPE, ExecutionPolicy.INTERNAL);
}
+ // spring-rabbit 2.1.0+
+ InstrumentMethod constructor_2_1_0 = target.getConstructor("java.lang.String", "com.rabbitmq.client.Envelope", "com.rabbitmq.client.AMQP$BasicProperties", "byte[]", "java.lang.String");
+ if (constructor_2_1_0 != null) {
+ constructor_2_1_0.addScopedInterceptor("com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.DeliveryConstructInterceptor", RabbitMQClientConstants.RABBITMQ_CONSUMER_SCOPE, ExecutionPolicy.INTERNAL);
+ }
target.addField(AsyncContextAccessor.class.getName());
return target.toBytecode();
}
| diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_1_7_7_to_2_0_0_IT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_1_7_7_to_2_0_0_IT.java
index a7e725ce595b..e369b45d0f4c 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_1_7_7_to_2_0_0_IT.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_1_7_7_to_2_0_0_IT.java
@@ -49,7 +49,7 @@
* <tt>BlockingQueueConsumer$ConsumerDecorator</tt> added in 2.0.3 has been backported to 1.7.7 as well.
*
* @author HyunGil Jeong
- * @see SpringAmqpRabbit_2_0_3_to_2_x_IT
+ * @see SpringAmqpRabbit_2_0_3_to_2_1_0_IT
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_0_3_to_2_x_IT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_0_3_to_2_1_0_IT.java
similarity index 99%
rename from agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_0_3_to_2_x_IT.java
rename to agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_0_3_to_2_1_0_IT.java
index 8f5d91d85c85..1c3e5d174ea1 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_0_3_to_2_x_IT.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_0_3_to_2_1_0_IT.java
@@ -59,9 +59,9 @@
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
@PinpointConfig("rabbitmq/client/pinpoint-rabbitmq.config")
-@Dependency({"org.springframework.amqp:spring-rabbit:[2.0.3.RELEASE,)", "com.fasterxml.jackson.core:jackson-core:2.8.11", "org.apache.qpid:qpid-broker:6.1.1"})
+@Dependency({"org.springframework.amqp:spring-rabbit:[2.0.3.RELEASE,2.1.0.RELEASE)", "com.fasterxml.jackson.core:jackson-core:2.8.11", "org.apache.qpid:qpid-broker:6.1.1"})
@JvmVersion(8)
-public class SpringAmqpRabbit_2_0_3_to_2_x_IT {
+public class SpringAmqpRabbit_2_0_3_to_2_1_0_IT {
private static final TestBroker BROKER = new TestBroker();
private static final TestApplicationContext CONTEXT = new TestApplicationContext();
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_1_x_to_2_x_IT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_1_x_to_2_x_IT.java
new file mode 100644
index 000000000000..43f292662fd4
--- /dev/null
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/rabbitmq/spring/SpringAmqpRabbit_2_1_x_to_2_x_IT.java
@@ -0,0 +1,310 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * 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.
+ */
+
+package com.navercorp.pinpoint.plugin.jdk7.rabbitmq.spring;
+
+import com.navercorp.pinpoint.bootstrap.plugin.test.Expectations;
+import com.navercorp.pinpoint.bootstrap.plugin.test.ExpectedTrace;
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
+import com.navercorp.pinpoint.common.trace.ServiceType;
+import com.navercorp.pinpoint.plugin.AgentPath;
+import com.navercorp.pinpoint.plugin.jdk7.rabbitmq.util.RabbitMQTestConstants;
+import com.navercorp.pinpoint.plugin.jdk7.rabbitmq.util.TestBroker;
+import com.navercorp.pinpoint.test.plugin.Dependency;
+import com.navercorp.pinpoint.test.plugin.JvmVersion;
+import com.navercorp.pinpoint.test.plugin.PinpointAgent;
+import com.navercorp.pinpoint.test.plugin.PinpointConfig;
+import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
+import com.navercorp.test.pinpoint.plugin.rabbitmq.PropagationMarker;
+import com.navercorp.test.pinpoint.plugin.rabbitmq.spring.config.CommonConfig;
+import com.navercorp.test.pinpoint.plugin.rabbitmq.spring.config.MessageListenerConfig_Post_1_4_0;
+import com.navercorp.test.pinpoint.plugin.rabbitmq.spring.config.ReceiverConfig_Post_1_6_0;
+import com.rabbitmq.client.AMQP;
+import com.rabbitmq.client.Channel;
+import com.rabbitmq.client.Consumer;
+import com.rabbitmq.client.Envelope;
+import com.rabbitmq.client.impl.AMQCommand;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.amqp.core.Message;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+
+/**
+ * <p>Spring-amqp rabbit 2.1.0 removed previously added <tt>BlockingQueueConsumer$ConsumerDecorator</tt>.
+ *
+ * @author HyunGil Jeong
+ */
+@RunWith(PinpointPluginTestSuite.class)
+@PinpointAgent(AgentPath.PATH)
+@PinpointConfig("rabbitmq/client/pinpoint-rabbitmq.config")
+@Dependency({"org.springframework.amqp:spring-rabbit:[2.1.0.RELEASE,)", "com.fasterxml.jackson.core:jackson-core:2.8.11", "org.apache.qpid:qpid-broker:6.1.1"})
+@JvmVersion(8)
+public class SpringAmqpRabbit_2_1_x_to_2_x_IT {
+
+ private static final TestBroker BROKER = new TestBroker();
+ private static final TestApplicationContext CONTEXT = new TestApplicationContext();
+
+ private final SpringAmqpRabbitTestRunner testRunner = new SpringAmqpRabbitTestRunner(CONTEXT);
+
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ BROKER.start();
+ CONTEXT.init(
+ CommonConfig.class,
+ MessageListenerConfig_Post_1_4_0.class,
+ ReceiverConfig_Post_1_6_0.class);
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() {
+ CONTEXT.close();
+ BROKER.shutdown();
+ }
+
+ @Test
+ public void testPush() throws Exception {
+ final String remoteAddress = testRunner.getRemoteAddress();
+
+ Class<?> rabbitTemplateClass = Class.forName("org.springframework.amqp.rabbit.core.RabbitTemplate");
+ Method rabbitTemplateConvertAndSend = rabbitTemplateClass.getDeclaredMethod("convertAndSend", String.class, String.class, Object.class);
+ ExpectedTrace rabbitTemplateConvertAndSendTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ rabbitTemplateConvertAndSend); // method
+ // automatic recovery deliberately disabled as Spring has it's own recovery mechanism
+ Class<?> channelNClass = Class.forName("com.rabbitmq.client.impl.ChannelN");
+ Method channelNBasicPublish = channelNClass.getDeclaredMethod("basicPublish", String.class, String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace channelNBasicPublishTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ channelNBasicPublish, // method
+ null, // rpc
+ remoteAddress, // endPoint
+ "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId
+ Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE),
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PUSH));
+ ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ "RabbitMQ Consumer Invocation", // method
+ "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc
+ null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip)
+ remoteAddress, // remoteAddress
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PUSH));
+ Class<?> consumerDispatcherClass = Class.forName("com.rabbitmq.client.impl.ConsumerDispatcher");
+ Method consumerDispatcherHandleDelivery = consumerDispatcherClass.getDeclaredMethod("handleDelivery", Consumer.class, String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace consumerDispatcherHandleDeliveryTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ consumerDispatcherHandleDelivery); // method
+ ExpectedTrace asynchronousInvocationTrace = Expectations.event(
+ ServiceType.ASYNC.getName(),
+ "Asynchronous Invocation");
+ Class<?> blockingQueueConsumerInternalConsumerClass = Class.forName("org.springframework.amqp.rabbit.listener.BlockingQueueConsumer$InternalConsumer");
+ Method blockingQueueConsumerInternalConsumerHandleDelivery = blockingQueueConsumerInternalConsumerClass.getDeclaredMethod("handleDelivery", String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace blockingQueueConsumerInternalConsumerHandleDeliveryTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ blockingQueueConsumerInternalConsumerHandleDelivery);
+ Class<?> deliveryClass = Class.forName("org.springframework.amqp.rabbit.support.Delivery");
+ Constructor<?> deliveryConstructor = deliveryClass.getDeclaredConstructor(String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class, String.class);
+ ExpectedTrace deliveryConstructorTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ deliveryConstructor);
+ Class<?> abstractMessageListenerContainerClass = Class.forName("org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer");
+ Method abstractMessageListenerContainerExecuteListener = abstractMessageListenerContainerClass.getDeclaredMethod("executeListener", Channel.class, Message.class);
+ ExpectedTrace abstractMessageListenerContainerExecuteListenerTrace = Expectations.event(
+ ServiceType.INTERNAL_METHOD.getName(),
+ abstractMessageListenerContainerExecuteListener);
+ Class<?> propagationMarkerClass = PropagationMarker.class;
+ Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark");
+ ExpectedTrace markTrace = Expectations.event(
+ ServiceType.INTERNAL_METHOD.getName(),
+ propagationMarkerMark);
+
+ ExpectedTrace[] expectedTraces = {
+ rabbitTemplateConvertAndSendTrace,
+ channelNBasicPublishTrace,
+ rabbitMqConsumerInvocationTrace,
+ consumerDispatcherHandleDeliveryTrace,
+ asynchronousInvocationTrace,
+ blockingQueueConsumerInternalConsumerHandleDeliveryTrace,
+ deliveryConstructorTrace,
+ asynchronousInvocationTrace,
+ abstractMessageListenerContainerExecuteListenerTrace,
+ markTrace
+ };
+
+ final PluginTestVerifier verifier = testRunner.runPush(expectedTraces.length);
+
+ verifier.verifyTrace(expectedTraces);
+ verifier.verifyTraceCount(0);
+ }
+
+ @Test
+ public void testPull() throws Exception {
+ final String remoteAddress = testRunner.getRemoteAddress();
+
+ Class<?> rabbitTemplateClass = Class.forName("org.springframework.amqp.rabbit.core.RabbitTemplate");
+ // verify queue-initiated traces
+ Method rabbitTemplateConvertAndSend = rabbitTemplateClass.getDeclaredMethod("convertAndSend", String.class, String.class, Object.class);
+ ExpectedTrace rabbitTemplateConvertAndSendTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ rabbitTemplateConvertAndSend); // method
+ // automatic recovery deliberately disabled as Spring has it's own recovery mechanism
+ Class<?> channelNClass = Class.forName("com.rabbitmq.client.impl.ChannelN");
+ Method channelNBasicPublish = channelNClass.getDeclaredMethod("basicPublish", String.class, String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace channelNBasicPublishTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ channelNBasicPublish, // method
+ null, // rpc
+ remoteAddress, // endPoint
+ "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId
+ Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE),
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
+ ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ "RabbitMQ Consumer Invocation", // method
+ "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc
+ null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip)
+ remoteAddress, // remoteAddress
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
+ Class<?> amqChannelClass = Class.forName("com.rabbitmq.client.impl.AMQChannel");
+ Method amqChannelHandleCompleteInboundCommand = amqChannelClass.getDeclaredMethod("handleCompleteInboundCommand", AMQCommand.class);
+ ExpectedTrace amqChannelHandleCompleteInboundCommandTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // method
+ amqChannelHandleCompleteInboundCommand);
+
+ ExpectedTrace[] queueInitiatedTraces = {
+ rabbitTemplateConvertAndSendTrace,
+ channelNBasicPublishTrace,
+ rabbitMqConsumerInvocationTrace,
+ amqChannelHandleCompleteInboundCommandTrace
+ };
+
+ // verify client-initiated traces
+ Method rabbitTemplateReceive = rabbitTemplateClass.getDeclaredMethod("receive", String.class);
+ ExpectedTrace rabbitTemplateReceiveTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ rabbitTemplateReceive); // method
+ Method channelNBasicGet = channelNClass.getDeclaredMethod("basicGet", String.class, boolean.class);
+ ExpectedTrace channelNBasicGetTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL,
+ channelNBasicGet);
+ Class<?> propagationMarkerClass = PropagationMarker.class;
+ Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark");
+ ExpectedTrace markTrace = Expectations.event(
+ ServiceType.INTERNAL_METHOD.getName(),
+ propagationMarkerMark);
+
+ ExpectedTrace[] clientInitiatedTraces = {
+ rabbitTemplateReceiveTrace,
+ channelNBasicGetTrace,
+ markTrace
+ };
+
+ int expectedTraceCount = queueInitiatedTraces.length + clientInitiatedTraces.length;
+ final PluginTestVerifier verifier = testRunner.runPull(expectedTraceCount);
+
+ verifier.verifyDiscreteTrace(queueInitiatedTraces);
+ verifier.verifyDiscreteTrace(clientInitiatedTraces);
+
+ verifier.verifyTraceCount(0);
+ }
+
+ @Test
+ public void testPullWithTimeout() throws Exception {
+ final String remoteAddress = testRunner.getRemoteAddress();
+
+ Class<?> rabbitTemplateClass = Class.forName("org.springframework.amqp.rabbit.core.RabbitTemplate");
+ // verify queue-initiated traces
+ Method rabbitTemplateConvertAndSend = rabbitTemplateClass.getDeclaredMethod("convertAndSend", String.class, String.class, Object.class);
+ ExpectedTrace rabbitTemplateConvertAndSendTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ rabbitTemplateConvertAndSend); // method
+ // automatic recovery deliberately disabled as Spring has it's own recovery mechanism
+ Class<?> channelNClass = Class.forName("com.rabbitmq.client.impl.ChannelN");
+ Method channelNBasicPublish = channelNClass.getDeclaredMethod("basicPublish", String.class, String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace channelNBasicPublishTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ channelNBasicPublish, // method
+ null, // rpc
+ remoteAddress, // endPoint
+ "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId
+ Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE),
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
+ ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(
+ RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
+ "RabbitMQ Consumer Invocation", // method
+ "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc
+ null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip)
+ remoteAddress, // remoteAddress
+ Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
+ Class<?> consumerDispatcherClass = Class.forName("com.rabbitmq.client.impl.ConsumerDispatcher");
+ Method consumerDispatcherHandleDelivery = consumerDispatcherClass.getDeclaredMethod("handleDelivery", Consumer.class, String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace consumerDispatcherHandleDeliveryTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ consumerDispatcherHandleDelivery); // method
+ ExpectedTrace asynchronousInvocationTrace = Expectations.event(
+ ServiceType.ASYNC.getName(),
+ "Asynchronous Invocation");
+ // RabbitTemplate internal consumer implementation - may change in future versions which will cause tests to
+ // fail, in which case the integration test needs to be updated to match code changes
+ Class<?> rabbitTemplateInternalConsumerClass = Class.forName("org.springframework.amqp.rabbit.core.RabbitTemplate$2");
+ Method rabbitTemplateInternalConsumerHandleDelivery = rabbitTemplateInternalConsumerClass.getDeclaredMethod("handleDelivery", String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
+ ExpectedTrace rabbitTemplateInternalConsumerHandleDeliveryTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ rabbitTemplateInternalConsumerHandleDelivery); // method
+ Class<?> deliveryClass = Class.forName("org.springframework.amqp.rabbit.support.Delivery");
+ Constructor<?> deliveryConstructor = deliveryClass.getDeclaredConstructor(String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class, String.class);
+ ExpectedTrace deliveryConstructorTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ deliveryConstructor);
+
+ ExpectedTrace[] queueInitiatedTraces = {
+ rabbitTemplateConvertAndSendTrace,
+ channelNBasicPublishTrace,
+ rabbitMqConsumerInvocationTrace,
+ consumerDispatcherHandleDeliveryTrace,
+ asynchronousInvocationTrace,
+ rabbitTemplateInternalConsumerHandleDeliveryTrace,
+ deliveryConstructorTrace
+ };
+
+ // verify client-initiated traces
+ Method rabbitTemplateReceive = rabbitTemplateClass.getDeclaredMethod("receive", String.class, long.class);
+ ExpectedTrace rabbitTemplateReceiveTrace = Expectations.event(
+ RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
+ rabbitTemplateReceive); // method
+ Class<?> propagationMarkerClass = PropagationMarker.class;
+ Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark");
+ ExpectedTrace markTrace = Expectations.event(
+ ServiceType.INTERNAL_METHOD.getName(),
+ propagationMarkerMark);
+
+ ExpectedTrace[] clientInitiatedTraces = {
+ rabbitTemplateReceiveTrace,
+ markTrace
+ };
+
+ int expectedTraceCount = queueInitiatedTraces.length + clientInitiatedTraces.length;
+ final PluginTestVerifier verifier = testRunner.runPull(expectedTraceCount, 5000L);
+
+ verifier.verifyDiscreteTrace(queueInitiatedTraces);
+ verifier.verifyDiscreteTrace(clientInitiatedTraces);
+
+ verifier.verifyTraceCount(0);
+ }
+}
| test | test | "2018-10-17T08:17:48" | "2018-10-16T09:19:10Z" | Xylus | test |
pinpoint-apm/pinpoint/4798_4799 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4798 | pinpoint-apm/pinpoint/4799 | [
"keyword_pr_to_issue"
] | 6b218601e88cc1795c0ab3b9db5555d59a53e774 | 9b97968a49122284a33daec06cc34ca225eaffe6 | [] | [] | "2018-10-25T06:28:54Z" | [
"enhancement",
"module:plugin"
] | Replace embedded Cassandra with stubbed Cassandra for Datastax plugin integration tests | #### Description
Starting and stopping embedded Cassandra for every Datastax plugin integration test (for every version of Datastax java driver) was a bit too heavy and took too long.
It would also very occasionally hang the forked JVM process if embedded Cassandra was not started up or initialized correctly/promptly.
Replacing this with a more light-weight stubbed Cassandra should shorten test execution times and hopefully eliminate JVM hangs.
Additionally, we can remove references to **StatementWrapper** from the plugin to add support for Cassandra Datastax java driver versions 2.0.0 to 2.0.9, and 2.1.0 to 2.1.5.
(**StatementWrapper** class is not present in these versions) | [
"agent-it/pom.xml",
"plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/CassandraPlugin.java",
"plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/interceptor/CassandraStatementExecuteQueryInterceptor.java"
] | [
"agent-it/pom.xml",
"plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/CassandraPlugin.java",
"plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/field/WrappedStatementGetter.java",
"plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/interceptor/CassandraStatementExecuteQueryInterceptor.java"
] | [
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastaxITBase.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_2_0_x_IT.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_2_1_x_IT.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_2_2_x_IT.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_3_0_x_IT.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraTestHelper.java"
] | diff --git a/agent-it/pom.xml b/agent-it/pom.xml
index 4f49e28169fa..bfd4e9756941 100644
--- a/agent-it/pom.xml
+++ b/agent-it/pom.xml
@@ -207,9 +207,9 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.apache.cassandra</groupId>
- <artifactId>cassandra-all</artifactId>
- <version>2.1.13</version>
+ <groupId>org.scassandra</groupId>
+ <artifactId>java-client</artifactId>
+ <version>1.1.2</version>
<scope>test</scope>
</dependency>
diff --git a/plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/CassandraPlugin.java b/plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/CassandraPlugin.java
index b197d98e168d..73debadb43b2 100644
--- a/plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/CassandraPlugin.java
+++ b/plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/CassandraPlugin.java
@@ -54,11 +54,26 @@ public void setup(ProfilerPluginSetupContext context) {
return;
}
+ addStatementWrapperTransformer();
addDefaultPreparedStatementTransformer();
addSessionTransformer(config);
addClusterTransformer();
}
+ private void addStatementWrapperTransformer() {
+ transformTemplate.transform("com.datastax.driver.core.StatementWrapper", new TransformCallback() {
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className,
+ Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
+ byte[] classfileBuffer) throws InstrumentException {
+
+ InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+ target.addGetter("com.navercorp.pinpoint.plugin.cassandra.field.WrappedStatementGetter", "wrapped");
+ return target.toBytecode();
+ }
+ });
+ }
+
private void addDefaultPreparedStatementTransformer() {
TransformCallback transformer = new TransformCallback() {
diff --git a/plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/field/WrappedStatementGetter.java b/plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/field/WrappedStatementGetter.java
new file mode 100644
index 000000000000..b5424969e0cd
--- /dev/null
+++ b/plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/field/WrappedStatementGetter.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * 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.
+ */
+
+package com.navercorp.pinpoint.plugin.cassandra.field;
+
+import com.datastax.driver.core.Statement;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface WrappedStatementGetter {
+ Statement _$PINPOINT$_getStatement();
+}
diff --git a/plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/interceptor/CassandraStatementExecuteQueryInterceptor.java b/plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/interceptor/CassandraStatementExecuteQueryInterceptor.java
index 8083839541b6..a9e34f4c446f 100644
--- a/plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/interceptor/CassandraStatementExecuteQueryInterceptor.java
+++ b/plugins/cassandra/src/main/java/com/navercorp/pinpoint/plugin/cassandra/interceptor/CassandraStatementExecuteQueryInterceptor.java
@@ -22,7 +22,7 @@
import com.datastax.driver.core.BatchStatement;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.RegularStatement;
-import com.datastax.driver.core.StatementWrapper;
+import com.datastax.driver.core.Statement;
import com.navercorp.pinpoint.bootstrap.context.DatabaseInfo;
import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
import com.navercorp.pinpoint.bootstrap.context.ParsingResult;
@@ -38,6 +38,7 @@
import com.navercorp.pinpoint.bootstrap.plugin.jdbc.UnKnownDatabaseInfo;
import com.navercorp.pinpoint.bootstrap.plugin.jdbc.bindvalue.BindValueUtils;
import com.navercorp.pinpoint.common.util.MapUtils;
+import com.navercorp.pinpoint.plugin.cassandra.field.WrappedStatementGetter;
/**
* @author dawidmalina
@@ -126,9 +127,8 @@ private String retrieveSql(Object args0) {
return ((BoundStatement) args0).preparedStatement().getQueryString();
} else if (args0 instanceof RegularStatement) {
return ((RegularStatement) args0).getQueryString();
- } else if (args0 instanceof StatementWrapper) {
- // method to get wrapped statement is package-private, skip.
- return null;
+ } else if (args0 instanceof WrappedStatementGetter) {
+ return retrieveWrappedStatement((WrappedStatementGetter) args0);
} else if (args0 instanceof BatchStatement) {
// we could unroll all the batched statements and append ; between them if need be but it could be too long.
return null;
@@ -138,6 +138,11 @@ private String retrieveSql(Object args0) {
return null;
}
+ private String retrieveWrappedStatement(WrappedStatementGetter wrappedStatementGetter) {
+ Statement wrappedStatement = wrappedStatementGetter._$PINPOINT$_getStatement();
+ return retrieveSql(wrappedStatement);
+ }
+
private void clean(Object target) {
if (target instanceof BindValueAccessor) {
((BindValueAccessor) target)._$PINPOINT$_setBindValue(new HashMap<Integer, String>());
| diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastaxITBase.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastaxITBase.java
index c0da2aca8637..00b88ce46739 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastaxITBase.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastaxITBase.java
@@ -20,8 +20,6 @@
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.PreparedStatement;
-import com.datastax.driver.core.ResultSet;
-import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
import com.datastax.driver.core.StatementWrapper;
@@ -29,11 +27,18 @@
import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifierHolder;
import com.navercorp.pinpoint.common.util.DefaultSqlParser;
import com.navercorp.pinpoint.common.util.SqlParser;
-import org.junit.Assert;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Test;
+import org.scassandra.Scassandra;
+import org.scassandra.ScassandraFactory;
+import org.scassandra.http.client.ActivityClient;
+import org.scassandra.http.client.CurrentClient;
+import org.scassandra.http.client.PrimingClient;
import java.lang.reflect.Method;
-import java.util.Iterator;
import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.event;
import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.sql;
@@ -44,60 +49,70 @@
public abstract class CassandraDatastaxITBase {
// com.navercorp.pinpoint.plugin.cassandra.CassandraConstants
- protected static final String CASSANDRA = "CASSANDRA";
- protected static final String CASSANDRA_EXECUTE_QUERY = "CASSANDRA_EXECUTE_QUERY";
-
- protected static final String TEST_KEYSPACE = "mykeyspace";
- protected static final String TEST_TABLE = "mytable";
- protected static final String TEST_COL_ID = "id";
- protected static final String TEST_COL_VALUE = "value";
-
- protected static final String CQL_CREATE_KEYSPACE = String.format(
- "CREATE KEYSPACE %s WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };",
- TEST_KEYSPACE);
- protected static final String CQL_CREATE_TABLE = String.format(
- "CREATE TABLE %s ( %s int PRIMARY KEY, %s text );",
- TEST_TABLE, TEST_COL_ID, TEST_COL_VALUE);
- protected static final String CQL_INSERT = String.format(
+ private static final String CASSANDRA = "CASSANDRA";
+ private static final String CASSANDRA_EXECUTE_QUERY = "CASSANDRA_EXECUTE_QUERY";
+
+ private static final String TEST_KEYSPACE = "mykeyspace";
+ private static final String TEST_TABLE = "mytable";
+ private static final String TEST_COL_ID = "id";
+ private static final String TEST_COL_VALUE = "value";
+
+ private static final String CQL_INSERT = String.format(
"INSERT INTO %s (%s, %s) VALUES (?, ?);",
TEST_TABLE, TEST_COL_ID, TEST_COL_VALUE);
// for normalized sql used for sql cache
- protected static final SqlParser SQL_PARSER = new DefaultSqlParser();
+ private static final SqlParser SQL_PARSER = new DefaultSqlParser();
+
+ private static String HOST = "127.0.0.1";
+ private static final int DEFAULT_PORT = 9042;
+ private static final int DEFAULT_ADMIN_PORT = 9043;
+ private static final int PORT = CassandraTestHelper.findAvailablePortOrDefault(DEFAULT_PORT);
+ private static final int ADMIN_PORT = CassandraTestHelper.findAvailablePortOrDefault(DEFAULT_ADMIN_PORT);
+ private static final String CASSANDRA_ADDRESS = HOST + ":" + PORT;
+
+ private static final Scassandra SERVER = ScassandraFactory.createServer(HOST, PORT, HOST, ADMIN_PORT);
- protected static Cluster cluster;
+ private Cluster cluster;
- // see cassandra/cassandra_${cassandraVersion}.yaml
- protected static String HOST;
- protected static int PORT;
- protected static String CASSANDRA_ADDRESS;
+ private final PrimingClient primingClient = SERVER.primingClient();
+ private final ActivityClient activityClient = SERVER.activityClient();
+ private final CurrentClient currentClient = SERVER.currentClient();
- public static void initializeCluster(String cassandraVersion) throws Exception {
- CassandraTestHelper.init(cassandraVersion);
- HOST = CassandraTestHelper.getHost();
- PORT = CassandraTestHelper.getNativeTransportPort();
- CASSANDRA_ADDRESS = HOST + ":" + PORT;
+ @BeforeClass
+ public static void startUpBeforeClass() {
+ SERVER.start();
+ }
+
+ @Before
+ public void setUp() {
cluster = Cluster.builder().addContactPoint(HOST).withPort(PORT).withoutMetrics().build();
- // Create KeySpace
- Session emptySession = null;
- try {
- emptySession = cluster.connect();
- emptySession.execute(CQL_CREATE_KEYSPACE);
- } finally {
- closeSession(emptySession);
+
+ // scassandra uses http client 4 for stub calls
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.ignoreServiceType("HTTP_CLIENT_4", "HTTP_CLIENT_4_INTERNAL");
+ }
+
+ @After
+ public void tearDown() {
+ if (primingClient != null) {
+ primingClient.clearAllPrimes();
}
- // Create Table
- Session myKeyspaceSession = null;
- try {
- myKeyspaceSession = cluster.connect(TEST_KEYSPACE);
- myKeyspaceSession.execute(CQL_CREATE_TABLE);
- } finally {
- closeSession(myKeyspaceSession);
+ if (activityClient != null) {
+ activityClient.clearAllRecordedActivity();
+ }
+ if (cluster != null) {
+ cluster.close();
}
}
+ @AfterClass
+ public static void tearDownAfterClass() {
+ SERVER.stop();
+ }
+
@Test
public void testBoundStatement() throws Exception {
- final int testId = 99;
+ final String testId ="99";
final String testValue = "testValue";
PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
@@ -134,11 +149,9 @@ public void testBoundStatement() throws Exception {
// ====================
// Select Data (String)
- final String cqlSelect = String.format("SELECT %s, %s FROM %s WHERE %s = %d",
+ final String cqlSelect = String.format("SELECT %s, %s FROM %s WHERE %s = %s",
TEST_COL_ID, TEST_COL_VALUE, TEST_TABLE, TEST_COL_ID, testId);
- verifySelect(myKeyspaceSession.execute(cqlSelect), testId, testValue);
-
- verifier.printCache();
+ myKeyspaceSession.execute(cqlSelect);
// SessionManager#execute(String) OR AbstractSession#execute(String)
execute = sessionClass.getDeclaredMethod("execute", String.class);
String normalizedSelectSql = SQL_PARSER.normalizedSql(cqlSelect).getNormalizedSql();
@@ -161,9 +174,9 @@ public void testBoundStatement() throws Exception {
@Test
public void testBatchStatement_and_StatementWrapper() throws Exception {
- final int testId1 = 998;
+ final String testId1 = "998";
final String testValue1 = "testValue998";
- final int testId2 = 999;
+ final String testId2 = "999";
final String testValue2 = "testValue999";
PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
@@ -217,34 +230,16 @@ public void testBatchStatement_and_StatementWrapper() throws Exception {
// SessionManager#prepare(String) OR AbstractSession#prepare(String)
verifier.verifyTrace(event(CASSANDRA, prepare, null, CASSANDRA_ADDRESS, TEST_KEYSPACE, sql(cqlDelete, null)));
// SessionManager#execute(String, Object[]) OR AbstractSession#execute(String, Object[])
- verifier.verifyTrace(event(CASSANDRA_EXECUTE_QUERY, execute, null, CASSANDRA_ADDRESS, TEST_KEYSPACE));
+ verifier.verifyTrace(event(CASSANDRA_EXECUTE_QUERY, execute, null, CASSANDRA_ADDRESS, TEST_KEYSPACE, sql(cqlDelete, null)));
} finally {
closeSession(myKeyspaceSession);
}
}
- private void verifySelect(ResultSet rs, int expectedTestId, String expectedTestValue) {
- int resultCount = 0;
- Iterator<Row> iter = rs.iterator();
- while (iter.hasNext()) {
- Row row = iter.next();
- Assert.assertEquals(expectedTestId, row.getInt(0));
- Assert.assertEquals(expectedTestValue, row.getString(1));
- ++resultCount;
- }
- Assert.assertEquals(1, resultCount);
- }
-
private static void closeSession(Session session) {
if (session != null) {
session.close();
}
}
- public static void cleanUpCluster() {
- if (cluster != null) {
- cluster.close();
- }
- }
-
}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_2_0_x_IT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_2_0_x_IT.java
index af0d3479b13e..a221f6ff4904 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_2_0_x_IT.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_2_0_x_IT.java
@@ -20,32 +20,18 @@
import com.navercorp.pinpoint.test.plugin.Dependency;
import com.navercorp.pinpoint.test.plugin.PinpointAgent;
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.runner.RunWith;
/**
+ * Integration tests require {@link com.datastax.driver.core.StatementWrapper StatementWrapper}, so we
+ * limit datastax driver version to 2.0.10+.
+ *
* @author HyunGil Jeong
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
@Dependency({
- "com.datastax.cassandra:cassandra-driver-core:[2.0.12,2.0.max]",
- "org.apache.cassandra:cassandra-all:2.0.17",
- "com.google.guava:guava:17.0",
- "org.codehaus.plexus:plexus-utils:3.0.22"})
+ "com.datastax.cassandra:cassandra-driver-core:[2.0.10,2.0.max]",
+ "org.scassandra:java-client:1.1.2"})
public class CassandraDatastax_2_0_x_IT extends CassandraDatastaxITBase {
-
- private static final String CASSANDRA_VERSION = "2_0_x";
-
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
- initializeCluster(CASSANDRA_VERSION);
- }
-
- @AfterClass
- public static void tearDownAfterClass() {
- cleanUpCluster();
- }
-
}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_2_1_x_IT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_2_1_x_IT.java
index 7a6ad19c7cc6..81aef4b9ac64 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_2_1_x_IT.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_2_1_x_IT.java
@@ -20,32 +20,18 @@
import com.navercorp.pinpoint.test.plugin.Dependency;
import com.navercorp.pinpoint.test.plugin.PinpointAgent;
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.runner.RunWith;
/**
+ * Integration tests require {@link com.datastax.driver.core.StatementWrapper StatementWrapper}, so we
+ * limit datastax driver version to 2.1.6+.
+ *
* @author HyunGil Jeong
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
@Dependency({
- "com.datastax.cassandra:cassandra-driver-core:[2.1.9,2.1.max]",
- "org.apache.cassandra:cassandra-all:2.1.13",
- "com.google.guava:guava:17.0",
- "org.codehaus.plexus:plexus-utils:3.0.22"})
+ "com.datastax.cassandra:cassandra-driver-core:[2.1.6,2.1.max]",
+ "org.scassandra:java-client:1.1.2"})
public class CassandraDatastax_2_1_x_IT extends CassandraDatastaxITBase {
-
- private static final String CASSANDRA_VERSION = "2_1_x";
-
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
- initializeCluster(CASSANDRA_VERSION);
- }
-
- @AfterClass
- public static void tearDownAfterClass() {
- cleanUpCluster();
- }
-
}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_2_2_x_IT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_2_2_x_IT.java
index 828b922bc97a..6daf92c3cc1d 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_2_2_x_IT.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_2_2_x_IT.java
@@ -20,8 +20,6 @@
import com.navercorp.pinpoint.test.plugin.Dependency;
import com.navercorp.pinpoint.test.plugin.PinpointAgent;
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.runner.RunWith;
/**
@@ -30,22 +28,7 @@
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
@Dependency({
- "com.datastax.cassandra:cassandra-driver-core:[2.2.0-rc3,2.2.max]",
- "org.apache.cassandra:cassandra-all:2.1.13",
- "com.google.guava:guava:17.0",
- "org.codehaus.plexus:plexus-utils:3.0.22"})
+ "com.datastax.cassandra:cassandra-driver-core:[2.2.min,2.2.max]",
+ "org.scassandra:java-client:1.1.2"})
public class CassandraDatastax_2_2_x_IT extends CassandraDatastaxITBase {
-
- private static final String CASSANDRA_VERSION = "2_2_x";
-
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
- initializeCluster(CASSANDRA_VERSION);
- }
-
- @AfterClass
- public static void tearDownAfterClass() {
- cleanUpCluster();
- }
-
}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_3_0_x_IT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_3_0_x_IT.java
index 6568afae08a1..fb7a58f22a4c 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_3_0_x_IT.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraDatastax_3_0_x_IT.java
@@ -20,8 +20,6 @@
import com.navercorp.pinpoint.test.plugin.Dependency;
import com.navercorp.pinpoint.test.plugin.PinpointAgent;
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.runner.RunWith;
/**
@@ -30,22 +28,7 @@
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
@Dependency({
- "com.datastax.cassandra:cassandra-driver-core:[3.0.0,3.0.max]",
- "org.apache.cassandra:cassandra-all:2.1.13",
- "com.google.guava:guava:17.0",
- "org.codehaus.plexus:plexus-utils:3.0.22"})
+ "com.datastax.cassandra:cassandra-driver-core:[3.0.0,)",
+ "org.scassandra:java-client:1.1.2"})
public class CassandraDatastax_3_0_x_IT extends CassandraDatastaxITBase {
-
- private static final String CASSANDRA_VERSION = "3_0_x";
-
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
- initializeCluster(CASSANDRA_VERSION);
- }
-
- @AfterClass
- public static void tearDownAfterClass() {
- cleanUpCluster();
- }
-
}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraTestHelper.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraTestHelper.java
index 592ccd05d6ba..e87290abc89a 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraTestHelper.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/cassandra/CassandraTestHelper.java
@@ -16,64 +16,31 @@
package com.navercorp.pinpoint.plugin.jdk7.cassandra;
-import org.apache.cassandra.config.DatabaseDescriptor;
-import org.apache.cassandra.exceptions.ConfigurationException;
-import org.apache.cassandra.service.EmbeddedCassandraService;
-import org.codehaus.plexus.util.FileUtils;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.HashSet;
-import java.util.Set;
+import java.net.ServerSocket;
/**
* @author HyunGil Jeong
*/
public class CassandraTestHelper {
- private static final String CASSANDRA_HOME = "target/test-classes/cassandra";
-
private CassandraTestHelper() {
}
- public static void init(final String cassandraVersion) throws IOException, ConfigurationException {
- final String cassandraStorageDir = String.format("%s/data_%s", CASSANDRA_HOME, cassandraVersion);
- final String cassandraConfigFile = String.format("cassandra/cassandra_%s.yaml", cassandraVersion);
- System.setProperty("cassandra.storagedir", cassandraStorageDir);
- System.setProperty("cassandra.config", cassandraConfigFile);
- prepareEnvironment();
- EmbeddedCassandraService cassandra = new EmbeddedCassandraService();
- cassandra.start();
- }
-
- public static String getHost() {
- return DatabaseDescriptor.getListenAddress().getHostAddress();
- }
-
- public static int getNativeTransportPort() {
- return DatabaseDescriptor.getNativeTransportPort();
- }
-
- private static void prepareEnvironment() throws IOException {
+ public static int findAvailablePortOrDefault(int defaultPort) {
try {
- cleanUpFiles();
- } catch (IOException e) {
- // ignore - just let the server start
- }
- }
-
- private static void cleanUpFiles() throws IOException {
- Set<String> fileLocations = new HashSet<String>();
- for (String dataFileLocation : DatabaseDescriptor.getAllDataFileLocations()) {
- fileLocations.add(dataFileLocation);
- }
- fileLocations.add(DatabaseDescriptor.getCommitLogLocation());
- fileLocations.add(DatabaseDescriptor.getSavedCachesLocation());
- for (String fileLocation : fileLocations) {
- File location = new File(fileLocation);
- if (location.exists() && location.isDirectory()) {
- FileUtils.deleteDirectory(fileLocation);
+ ServerSocket ss = null;
+ try {
+ ss = new ServerSocket(0);
+ ss.setReuseAddress(true);
+ return ss.getLocalPort();
+ } finally {
+ if (ss != null) {
+ ss.close();
+ }
}
+ } catch (Exception e) {
+ // just ignore and return default
+ return defaultPort;
}
}
}
| test | test | "2018-10-24T09:50:56" | "2018-10-25T06:02:16Z" | Xylus | test |
pinpoint-apm/pinpoint/4367_4805 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4367 | pinpoint-apm/pinpoint/4805 | [
"keyword_pr_to_issue"
] | caa438cab57d5dbfacfec200de12363a5f584d93 | a844abba1f8f4cbd7fe64a7da178e1eef13b7aaf | [
"Hello, @VictorZeng \r\n\r\nWe hope that we can provide all the features. But unfortunately, it's not easy due to lack of time.\r\nIt would be GREAT for Pinpoint Community if you can make Hbase-plugin and share with us:)",
"@RoySRose I will make the Hbase-plugin.",
"@VictorZeng \r\nOh! Perfect~! We are really looking forward to it~!"
] | [] | "2018-10-26T06:08:36Z" | [
"enhancement",
"module:plugin"
] | Why is there no Hbase plugin support? | **Which module is your feature request related to?**
Plugin/Hbase
**Is your feature request related to a problem?**
A clear and concise description of what the problem is.
**Describe the solution you'd like**
Hbase GET/PUT/DELETE/SCAN etc
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
| [
"plugins/hbase/pom.xml",
"plugins/hbase/src/main/java/com/navercorp/pinpoint/plugin/hbase/interceptor/HbaseTableMethodInterceptor.java"
] | [
"plugins/hbase/pom.xml",
"plugins/hbase/src/main/java/com/navercorp/pinpoint/plugin/hbase/interceptor/HbaseTableMethodInterceptor.java"
] | [
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/hbase/HbaseClientIT.java"
] | diff --git a/plugins/hbase/pom.xml b/plugins/hbase/pom.xml
index 43e62534ee35..db1e83651b21 100644
--- a/plugins/hbase/pom.xml
+++ b/plugins/hbase/pom.xml
@@ -27,12 +27,35 @@
<name>pinpoint-hbase-plugin</name>
<packaging>jar</packaging>
+ <properties>
+ <jdk.version>1.6</jdk.version>
+ <jdk.home>${env.JAVA_7_HOME}</jdk.home>
+ <sniffer.artifactid>java17</sniffer.artifactid>
+ </properties>
+
+ <dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>com.navercorp.pinpoint</groupId>
+ <artifactId>pinpoint-plugin-bom</artifactId>
+ <version>${project.version}</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+
<dependencies>
<dependency>
<groupId>com.navercorp.pinpoint</groupId>
<artifactId>pinpoint-bootstrap-core</artifactId>
<scope>provided</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.hbase</groupId>
+ <artifactId>hbase-shaded-client</artifactId>
+ <scope>provided</scope>
+ </dependency>
</dependencies>
</project>
diff --git a/plugins/hbase/src/main/java/com/navercorp/pinpoint/plugin/hbase/interceptor/HbaseTableMethodInterceptor.java b/plugins/hbase/src/main/java/com/navercorp/pinpoint/plugin/hbase/interceptor/HbaseTableMethodInterceptor.java
index 28dffdcc01d4..94832444e438 100644
--- a/plugins/hbase/src/main/java/com/navercorp/pinpoint/plugin/hbase/interceptor/HbaseTableMethodInterceptor.java
+++ b/plugins/hbase/src/main/java/com/navercorp/pinpoint/plugin/hbase/interceptor/HbaseTableMethodInterceptor.java
@@ -19,6 +19,10 @@
import com.navercorp.pinpoint.bootstrap.context.TraceContext;
import com.navercorp.pinpoint.bootstrap.interceptor.SpanEventSimpleAroundInterceptorForPlugin;
import com.navercorp.pinpoint.plugin.hbase.HbasePluginConstants;
+import org.apache.hadoop.hbase.client.Get;
+import org.apache.hadoop.hbase.client.Mutation;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.util.Bytes;
import java.util.List;
@@ -75,27 +79,29 @@ protected String parseAttributes(Object[] args) {
param = args[0];
} else if (args != null && args.length > 1) { // last param
param = args[args.length - 1];
+ } else {
+ return null;
}
- if (param != null) {
- // if param instanceof List.
- if (param instanceof List) {
- List list = (List) param;
- return "size: " + list.size();
- }
- // if has getRow method. e.g. Get/Put/Delete/Append/Increment/...
- try {
- byte[] rowkey = (byte[]) param.getClass().getMethod("getRow").invoke(param);
- return "rowKey: " + new String(rowkey);
- } catch (Exception e) {
- }
- // if has getStartRow and getStopRow method. e.g. Scan
- try {
- byte[] startRowkey = (byte[]) param.getClass().getMethod("getStartRow").invoke(param);
- byte[] stopRowkey = (byte[]) param.getClass().getMethod("getStopRow").invoke(param);
- return "startRowKey: " + new String(startRowkey) + " stopRowKey: " + new String(stopRowkey);
- } catch (Exception e) {
- }
+ // Put/Delete/Append/Increment
+ if (param instanceof Mutation) {
+ Mutation mutation = (Mutation) param;
+ return "rowKey: " + Bytes.toStringBinary(mutation.getRow());
+ }
+ if (param instanceof Get) {
+ Get get = (Get) param;
+ return "rowKey: " + Bytes.toStringBinary(get.getRow());
+ }
+ if (param instanceof Scan) {
+ Scan scan = (Scan) param;
+ String startRowKey = Bytes.toStringBinary(scan.getStartRow());
+ String stopRowKey = Bytes.toStringBinary(scan.getStopRow());
+ return "startRowKey: " + startRowKey + " stopRowKey: " + stopRowKey;
+ }
+ // if param instanceof List.
+ if (param instanceof List) {
+ List list = (List) param;
+ return "size: " + list.size();
}
return null;
}
| diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/hbase/HbaseClientIT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/hbase/HbaseClientIT.java
index f0f57f671ee9..d437fc16f414 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/hbase/HbaseClientIT.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/hbase/HbaseClientIT.java
@@ -20,7 +20,7 @@
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
@JvmVersion(8)
-@Dependency({"org.apache.hbase:hbase-shaded-client:[1.2.6.1]", "org.mockito:mockito-all:1.8.4"})
+@Dependency({"org.apache.hbase:hbase-shaded-client:[1.2.6.1]", "org.mockito:mockito-core:2.7.22"})
@PinpointConfig("hbase/pinpoint-hbase-test.config")
public class HbaseClientIT {
@@ -48,8 +48,8 @@ public void testAdmin() throws Exception {
verifier.printCache();
- verifier.verifyTrace(event("HBASE_ADMIN", HBaseAdmin.class.getDeclaredMethod("tableExists", TableName.class),
- annotation("hbase.params", "[test]")));
+ verifier.verifyTrace(event("HBASE_CLIENT_ADMIN", HBaseAdmin.class.getDeclaredMethod("tableExists", TableName.class),
+ annotation("hbase.client.params", "[test]")));
verifier.verifyTraceCount(0);
}
@@ -72,8 +72,8 @@ public void testTable() throws Exception {
verifier.printCache();
- verifier.verifyTrace(event("HBASE_TABLE", HTable.class.getDeclaredMethod("put", Put.class),
- annotation("hbase.params", "rowKey: row")));
+ verifier.verifyTrace(event("HBASE_CLIENT_TABLE", HTable.class.getDeclaredMethod("put", Put.class),
+ annotation("hbase.client.params", "rowKey: row")));
verifier.verifyTraceCount(0);
}
| train | test | "2018-10-26T08:07:11" | "2018-07-14T01:50:25Z" | VictorZeng | test |
pinpoint-apm/pinpoint/4723_4830 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4723 | pinpoint-apm/pinpoint/4830 | [
"keyword_pr_to_issue"
] | 49a454e165d47e5d7e6fc81c2ba299dc0a8e2f5a | 8a55efc2246d0cbb8f3e9df1fd018598894f4c6a | [
"Hi @pikuzi \r\nAre you using okhttp version 2.7.x?\r\nWe add a getter for `private Connection connection` field in **HttpEngine** to use it in our interceptor but okhttp 2.7.0+ does not have this field. This would have led to your issue.\r\nWe'll try to fix this for 1.8.1 (or you could cook up a fix and throw us a PR which would be superb).\r\n\r\nIn the mean time, the exception shouldn't cause any issue except for okhttp client calls not being traced.",
"@pikuzi \r\nFixed merged to master branch (1.8.1-SNAPSHOT) if you're still around :)"
] | [] | "2018-10-31T09:41:45Z" | [] | com.navercorp.pinpoint.bootstrap.instrument.InstrumentException: Failed to add getter: com.navercorp.pinpoint.plugin.okhttp.v2.ConnectionGetter | **What version of pinpoint are you using?**
v1.7.3
**Describe your problem**
I have one java application which can not post interaction data from pp agent to pp collector.
I can see the agent was registered successfully in the application list from pp web, but there is no any line which connects to other apps.
From the log, i can see the following.
I just mask some of the package name, sorry.
BTW: I tried to disable okhttp from pinpoint.config, "profiler.okhttp.enable=false", there is no exception but still no change to this application in the pp web.
all the others java app work very well, only except this java app, I assume this is something different in this special app which causes this issue, but need your help for thoubleshooting.
thanks a lot.
-------------------
2018-09-30 17:14:41 [ERROR](c.n.p.p.BaseClassFileTransformer ) Transformer:com.navercorp.pinpoint.profiler.plugin.MatchableClassFileTransformerGuardDelegate threw an exception. cl:org.springframework.boot.loader.LaunchedURLClassLoader@6d366c9b ctxCl:org.springframework.boot.loader.LaunchedURLClassLoader@6d366c9b agentCl:com.navercorp.pinpoint.bootstrap.classloader.ParallelCapablePinpointURLClassLoader@2c8d66b2 Cause:com.navercorp.pinpoint.bootstrap.instrument.InstrumentException: Failed to add getter: com.navercorp.pinpoint.plugin.okhttp.v2.ConnectionGetter
com.navercorp.pinpoint.exception.PinpointException: com.navercorp.pinpoint.bootstrap.instrument.InstrumentException: Failed to add getter: com.navercorp.pinpoint.plugin.okhttp.v2.ConnectionGetter
at com.navercorp.pinpoint.profiler.plugin.MatchableClassFileTransformerGuardDelegate.transform(MatchableClassFileTransformerGuardDelegate.java:77)
at com.navercorp.pinpoint.profiler.BaseClassFileTransformer.transform(BaseClassFileTransformer.java:56)
at com.navercorp.pinpoint.profiler.MatchableClassFileTransformerDispatcher.transform(MatchableClassFileTransformerDispatcher.java:131)
at sun.instrument.TransformerManager.transform(TransformerManager.java:188)
at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:428)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:93)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at com.squareup.okhttp.Call.getResponse(Call.java:275)
at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:243)
at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:205)
at com.squareup.okhttp.Call.execute(Call.java:80)
at com.qcloud.image.http.DefaultImageHttpClient.sendPostRequest(DefaultImageHttpClient.java:153)
at com.qcloud.image.http.AbstractImageHttpClient.sendHttpRequest(AbstractImageHttpClient.java:45)
at com.qcloud.image.op.DetectionOp.idcardDetect(DetectionOp.java:192)
at com.qcloud.image.ImageClient.idcardDetect(ImageClient.java:128)
at com.XXXX.ocr.OcrServiceQcloudImpl.idCardOcrPath(OcrServiceQcloudImpl.java:57)
at com.XXXX.ocr.OcrController.idCardOcr(OcrController.java:90)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
at com.codahale.metrics.servlet.AbstractInstrumentedFilter.doFilter(AbstractInstrumentedFilter.java:111)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:158)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:126)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:111)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at com.XXXX.security.jwt.JWTFilter.doFilter(JWTFilter.java:36)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:336)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: com.navercorp.pinpoint.bootstrap.instrument.InstrumentException: Failed to add getter: com.navercorp.pinpoint.plugin.okhttp.v2.ConnectionGetter
at com.navercorp.pinpoint.profiler.instrument.ASMClass.addGetter(ASMClass.java:275)
at com.navercorp.pinpoint.plugin.okhttp.v2.OkHttpPlugin$4.doInTransform(OkHttpPlugin.java:127)
at com.navercorp.pinpoint.profiler.plugin.MatchableClassFileTransformerGuardDelegate.transform(MatchableClassFileTransformerGuardDelegate.java:75)
... 140 more
Caused by: java.lang.IllegalArgumentException: Not found field. name=connection
at com.navercorp.pinpoint.profiler.instrument.ASMClass.addGetter(ASMClass.java:263)
... 142 more
-------------------
| [
"agent-it/pom.xml",
"plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/OkHttpPlugin.java",
"plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/interceptor/HttpEngineReadResponseMethodInterceptor.java",
"plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/interceptor/HttpEngineSendRequestMethodInterceptor.java",
"plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v3/OkHttpPlugin.java"
] | [
"agent-it/pom.xml",
"plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/OkHttpPlugin.java",
"plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/interceptor/HttpEngineConnectMethodFromUserRequestInterceptor.java",
"plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/interceptor/HttpEngineReadResponseMethodInterceptor.java",
"plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/interceptor/HttpEngineSendRequestMethodInterceptor.java",
"plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v3/OkHttpPlugin.java"
] | [
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClient_2_x_IT.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClient_3_0_0_to_3_3_x_IT.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClient_3_4_0_to_3_x_IT.java"
] | diff --git a/agent-it/pom.xml b/agent-it/pom.xml
index bfd4e9756941..a96b3cb54eae 100644
--- a/agent-it/pom.xml
+++ b/agent-it/pom.xml
@@ -188,11 +188,15 @@
<scope>test</scope>
</dependency>
-
<dependency>
<groupId>com.squareup.okhttp</groupId>
<artifactId>okhttp</artifactId>
- <scope>provided</scope>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.squareup.okhttp3</groupId>
+ <artifactId>okhttp</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
diff --git a/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/OkHttpPlugin.java b/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/OkHttpPlugin.java
index 9a57efa4be2f..57acd9f01c9a 100644
--- a/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/OkHttpPlugin.java
+++ b/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/OkHttpPlugin.java
@@ -124,18 +124,34 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
final InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
target.addGetter(OkHttpConstants.USER_REQUEST_GETTER_V2, OkHttpConstants.FIELD_USER_REQUEST);
target.addGetter(OkHttpConstants.USER_RESPONSE_GETTER_V2, OkHttpConstants.FIELD_USER_RESPONSE);
- target.addGetter(OkHttpConstants.CONNECTION_GETTER_V2, OkHttpConstants.FIELD_CONNECTION);
final InstrumentMethod sendRequestMethod = target.getDeclaredMethod("sendRequest");
if (sendRequestMethod != null) {
sendRequestMethod.addScopedInterceptor("com.navercorp.pinpoint.plugin.okhttp.v2.interceptor.HttpEngineSendRequestMethodInterceptor", OkHttpConstants.SEND_REQUEST_SCOPE);
}
- final InstrumentMethod connectMethod = target.getDeclaredMethod("connect");
- if (connectMethod != null) {
- connectMethod.addInterceptor("com.navercorp.pinpoint.plugin.okhttp.v2.interceptor.HttpEngineConnectMethodInterceptor");
+ // pre-2.7.0
+ if (target.hasField("connection", "com.squareup.okhttp.Connection")) {
+ target.addGetter(OkHttpConstants.CONNECTION_GETTER_V2, OkHttpConstants.FIELD_CONNECTION);
+ // 2.3.0+
+ final InstrumentMethod connectMethod = target.getDeclaredMethod("connect");
+ if (connectMethod != null) {
+ connectMethod.addInterceptor("com.navercorp.pinpoint.plugin.okhttp.v2.interceptor.HttpEngineConnectMethodInterceptor");
+ }
+ // pre-2.3.0
+ final InstrumentMethod connectMethodWithParam = target.getDeclaredMethod("connect", "com.squareup.okhttp.Request");
+ if (connectMethodWithParam != null) {
+ connectMethodWithParam.addInterceptor("com.navercorp.pinpoint.plugin.okhttp.v2.interceptor.HttpEngineConnectMethodInterceptor");
+ }
+ } else {
+ // 2.7.0+
+ final InstrumentMethod connectMethod = target.getDeclaredMethod("connect");
+ if (connectMethod != null) {
+ connectMethod.addInterceptor("com.navercorp.pinpoint.plugin.okhttp.v2.interceptor.HttpEngineConnectMethodFromUserRequestInterceptor");
+ }
}
+
final InstrumentMethod readResponseMethod = target.getDeclaredMethod("readResponse");
if (readResponseMethod != null) {
readResponseMethod.addInterceptor("com.navercorp.pinpoint.plugin.okhttp.v2.interceptor.HttpEngineReadResponseMethodInterceptor", va(config.isStatusCode()));
diff --git a/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/interceptor/HttpEngineConnectMethodFromUserRequestInterceptor.java b/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/interceptor/HttpEngineConnectMethodFromUserRequestInterceptor.java
new file mode 100644
index 000000000000..eb103a1fa83d
--- /dev/null
+++ b/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/interceptor/HttpEngineConnectMethodFromUserRequestInterceptor.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * 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.
+ */
+
+package com.navercorp.pinpoint.plugin.okhttp.v2.interceptor;
+
+import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
+import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
+import com.navercorp.pinpoint.bootstrap.context.TraceContext;
+import com.navercorp.pinpoint.bootstrap.interceptor.SpanEventSimpleAroundInterceptorForPlugin;
+import com.navercorp.pinpoint.common.plugin.util.HostAndPort;
+import com.navercorp.pinpoint.common.trace.AnnotationKey;
+import com.navercorp.pinpoint.plugin.okhttp.OkHttpConstants;
+import com.navercorp.pinpoint.plugin.okhttp.v2.UserRequestGetter;
+import com.squareup.okhttp.HttpUrl;
+import com.squareup.okhttp.Request;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class HttpEngineConnectMethodFromUserRequestInterceptor extends SpanEventSimpleAroundInterceptorForPlugin {
+
+ public HttpEngineConnectMethodFromUserRequestInterceptor(TraceContext traceContext, MethodDescriptor descriptor) {
+ super(traceContext, descriptor);
+ }
+
+ @Override
+ protected void doInBeforeTrace(SpanEventRecorder recorder, Object target, Object[] args) {
+ }
+
+ @Override
+ protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
+ recorder.recordApi(methodDescriptor);
+ recorder.recordServiceType(OkHttpConstants.OK_HTTP_CLIENT_INTERNAL);
+ recorder.recordException(throwable);
+
+ if (target instanceof UserRequestGetter) {
+ final Request request = ((UserRequestGetter)target)._$PINPOINT$_getUserRequest();
+ if (request != null && request.httpUrl() != null) {
+ final HttpUrl httpUrl = request.httpUrl();
+ final String hostAndPort = HostAndPort.toHostAndPortString(httpUrl.host(), httpUrl.port());
+ recorder.recordAttribute(AnnotationKey.HTTP_INTERNAL_DISPLAY, hostAndPort);
+ }
+ }
+ }
+}
diff --git a/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/interceptor/HttpEngineReadResponseMethodInterceptor.java b/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/interceptor/HttpEngineReadResponseMethodInterceptor.java
index 5608e4aff40a..3ed4f3e17da0 100644
--- a/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/interceptor/HttpEngineReadResponseMethodInterceptor.java
+++ b/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/interceptor/HttpEngineReadResponseMethodInterceptor.java
@@ -21,7 +21,6 @@
import com.navercorp.pinpoint.bootstrap.logging.PLogger;
import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
import com.navercorp.pinpoint.common.trace.AnnotationKey;
-import com.navercorp.pinpoint.plugin.okhttp.v2.ConnectionGetter;
import com.navercorp.pinpoint.plugin.okhttp.OkHttpConstants;
import com.navercorp.pinpoint.plugin.okhttp.v2.UserRequestGetter;
import com.navercorp.pinpoint.plugin.okhttp.v2.UserResponseGetter;
@@ -78,13 +77,6 @@ private boolean validate(Object target) {
return false;
}
- if (!(target instanceof ConnectionGetter)) {
- if (isDebug) {
- logger.debug("Invalid target object. Need field accessor({}).", OkHttpConstants.FIELD_CONNECTION);
- }
- return false;
- }
-
return true;
}
diff --git a/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/interceptor/HttpEngineSendRequestMethodInterceptor.java b/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/interceptor/HttpEngineSendRequestMethodInterceptor.java
index 318c218a85d1..cf64892c702e 100644
--- a/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/interceptor/HttpEngineSendRequestMethodInterceptor.java
+++ b/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v2/interceptor/HttpEngineSendRequestMethodInterceptor.java
@@ -32,7 +32,6 @@
import com.navercorp.pinpoint.bootstrap.plugin.request.util.CookieExtractor;
import com.navercorp.pinpoint.bootstrap.plugin.request.util.CookieRecorder;
import com.navercorp.pinpoint.bootstrap.plugin.request.util.CookieRecorderFactory;
-import com.navercorp.pinpoint.plugin.okhttp.v2.ConnectionGetter;
import com.navercorp.pinpoint.plugin.okhttp.OkHttpConstants;
import com.navercorp.pinpoint.plugin.okhttp.OkHttpPluginConfig;
import com.navercorp.pinpoint.plugin.okhttp.v2.OkHttpClientRequestAdaptor;
@@ -119,13 +118,6 @@ private boolean validate(Object target) {
return false;
}
- if (!(target instanceof ConnectionGetter)) {
- if (isDebug) {
- logger.debug("Invalid target object. Need field accessor({}).", OkHttpConstants.FIELD_CONNECTION);
- }
- return false;
- }
-
return true;
}
diff --git a/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v3/OkHttpPlugin.java b/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v3/OkHttpPlugin.java
index b314486d679d..22b77a5d1e96 100644
--- a/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v3/OkHttpPlugin.java
+++ b/plugins/okhttp/src/main/java/com/navercorp/pinpoint/plugin/okhttp/v3/OkHttpPlugin.java
@@ -197,10 +197,34 @@ private void addRealConnection() {
public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
final InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
- final InstrumentMethod connectMethod = target.getDeclaredMethod("connect", "int", "int", "int", "boolean");
- if (connectMethod != null) {
+ boolean addRouteGetter = false;
+ // 3.4.x, 3.5.x
+ final InstrumentMethod connectMethod1 = target.getDeclaredMethod("connect", "int", "int", "int", "java.util.List", "boolean");
+ if (connectMethod1 != null) {
+ connectMethod1.addInterceptor("com.navercorp.pinpoint.plugin.okhttp.v3.interceptor.RealConnectionConnectMethodInterceptor");
+ addRouteGetter = true;
+ }
+ // 3.6.x - 3.8.x
+ final InstrumentMethod connectMethod2 = target.getDeclaredMethod("connect", "int", "int", "int", "boolean");
+ if (connectMethod2 != null) {
+ connectMethod2.addInterceptor("com.navercorp.pinpoint.plugin.okhttp.v3.interceptor.RealConnectionConnectMethodInterceptor");
+ addRouteGetter = true;
+ }
+ // 3.9.0
+ final InstrumentMethod connectMethod3 = target.getDeclaredMethod("connect", "int", "int", "int", "boolean", "okhttp3.Call", "okhttp3.EventListener");
+ if (connectMethod3 != null) {
+ connectMethod3.addInterceptor("com.navercorp.pinpoint.plugin.okhttp.v3.interceptor.RealConnectionConnectMethodInterceptor");
+ addRouteGetter = true;
+ }
+ // 3.10.0+
+ final InstrumentMethod connectMethod4 = target.getDeclaredMethod("connect", "int", "int", "int", "int", "boolean", "okhttp3.Call", "okhttp3.EventListener");
+ if (connectMethod4 != null) {
+ connectMethod4.addInterceptor("com.navercorp.pinpoint.plugin.okhttp.v3.interceptor.RealConnectionConnectMethodInterceptor");
+ addRouteGetter = true;
+ }
+
+ if (addRouteGetter) {
target.addGetter("com.navercorp.pinpoint.plugin.okhttp.v3.RouteGetter", "route");
- connectMethod.addInterceptor("com.navercorp.pinpoint.plugin.okhttp.v3.interceptor.RealConnectionConnectMethodInterceptor");
}
return target.toBytecode();
| diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClientBackwardCompatibilityIT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClientBackwardCompatibilityIT.java
deleted file mode 100644
index bd0298537a4e..000000000000
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClientBackwardCompatibilityIT.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright 2018 NAVER Corp.
- *
- * 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.
- */
-package com.navercorp.pinpoint.plugin.jdk7.okhttp;
-
-import com.navercorp.pinpoint.bootstrap.plugin.test.Expectations;
-import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
-import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifierHolder;
-import com.navercorp.pinpoint.plugin.AgentPath;
-import com.navercorp.pinpoint.plugin.WebServer;
-import com.navercorp.pinpoint.test.plugin.Dependency;
-import com.navercorp.pinpoint.test.plugin.PinpointAgent;
-import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
-import com.squareup.okhttp.*;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.lang.reflect.Method;
-
-/**
- * @author jaehong.kim
- */
-@RunWith(PinpointPluginTestSuite.class)
-@PinpointAgent(AgentPath.PATH)
-@Dependency({"com.squareup.okhttp:okhttp:[2.0.0],[2.1.0],[2.2.0],[2.3.0]", "org.nanohttpd:nanohttpd:2.3.1"})
-public class OkHttpClientBackwardCompatibilityIT {
-
- private static WebServer webServer;
-
-
- @BeforeClass
- public static void BeforeClass() throws Exception {
- webServer = WebServer.newTestWebServer();
- }
-
-
- @AfterClass
- public static void AfterClass() throws Exception {
- final WebServer copy = webServer;
- if (copy != null) {
- copy.stop();
- webServer = null;
- }
- }
-
- @Test
- public void execute() throws Exception {
- Request request = new Request.Builder().url(webServer.getCallHttpUrl()).build();
- OkHttpClient client = new OkHttpClient();
- Response response = client.newCall(request).execute();
-
- PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
- verifier.printCache();
-
- Method callMethod = Call.class.getDeclaredMethod("execute");
- verifier.verifyTrace(Expectations.event("OK_HTTP_CLIENT_INTERNAL", callMethod));
- }
-}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClientIT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClientIT.java
deleted file mode 100644
index 807d0db4fe8d..000000000000
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClientIT.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright 2018 NAVER Corp.
- *
- * 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.
- */
-package com.navercorp.pinpoint.plugin.jdk7.okhttp;
-
-import com.navercorp.pinpoint.bootstrap.plugin.test.Expectations;
-import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
-import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifierHolder;
-import com.navercorp.pinpoint.plugin.AgentPath;
-import com.navercorp.pinpoint.plugin.WebServer;
-import com.navercorp.pinpoint.test.plugin.Dependency;
-import com.navercorp.pinpoint.test.plugin.PinpointAgent;
-import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
-import com.squareup.okhttp.*;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.IOException;
-import java.lang.reflect.Method;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-/**
- * @author jaehong.kim
- */
-@RunWith(PinpointPluginTestSuite.class)
-@PinpointAgent(AgentPath.PATH)
-@Dependency({"com.squareup.okhttp:okhttp:[2.4.0],[2.5.0]", "org.nanohttpd:nanohttpd:2.3.1"})
-public class OkHttpClientIT {
-
- private static WebServer webServer;
-
-
- @BeforeClass
- public static void BeforeClass() throws Exception {
- webServer = WebServer.newTestWebServer();
- }
-
-
- @AfterClass
- public static void AfterClass() throws Exception {
- final WebServer copy = webServer;
- if (copy != null) {
- copy.stop();
- webServer = null;
- }
- }
-
- @Test
- public void execute() throws Exception {
- Request request = new Request.Builder().url(webServer.getCallHttpUrl()).build();
- OkHttpClient client = new OkHttpClient();
- Response response = client.newCall(request).execute();
-
- PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
- verifier.printCache();
-
- Method callMethod = Call.class.getDeclaredMethod("execute");
- verifier.verifyTrace(Expectations.event("OK_HTTP_CLIENT_INTERNAL", callMethod));
- }
-
- @Test
- public void enqueue() throws Exception {
- Request request = new Request.Builder().url(webServer.getCallHttpUrl()).build();
- OkHttpClient client = new OkHttpClient();
- final CountDownLatch latch = new CountDownLatch(1);
- client.newCall(request).enqueue(new Callback() {
- @Override
- public void onFailure(Request request, IOException e) {
- latch.countDown();
- }
-
- @Override
- public void onResponse(Response response) throws IOException {
- latch.countDown();
- }
- });
- latch.await(3, TimeUnit.SECONDS);
-
- PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
- verifier.printCache();
-
-
- Method enqueueMethod = Call.class.getDeclaredMethod("enqueue", com.squareup.okhttp.Callback.class);
- verifier.verifyTrace(Expectations.event("OK_HTTP_CLIENT_INTERNAL", enqueueMethod));
- }
-
-}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClient_2_x_IT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClient_2_x_IT.java
new file mode 100644
index 000000000000..e5067b8702c9
--- /dev/null
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClient_2_x_IT.java
@@ -0,0 +1,175 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * 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.
+ */
+package com.navercorp.pinpoint.plugin.jdk7.okhttp;
+
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifierHolder;
+import com.navercorp.pinpoint.common.plugin.util.HostAndPort;
+import com.navercorp.pinpoint.plugin.AgentPath;
+import com.navercorp.pinpoint.plugin.WebServer;
+import com.navercorp.pinpoint.plugin.okhttp.EndPointUtils;
+import com.navercorp.pinpoint.test.plugin.Dependency;
+import com.navercorp.pinpoint.test.plugin.PinpointAgent;
+import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
+import com.squareup.okhttp.*;
+import com.squareup.okhttp.internal.http.HttpEngine;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.annotation;
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.event;
+import static com.navercorp.pinpoint.common.trace.ServiceType.ASYNC;
+import static com.navercorp.pinpoint.plugin.okhttp.OkHttpConstants.OK_HTTP_CLIENT;
+import static com.navercorp.pinpoint.plugin.okhttp.OkHttpConstants.OK_HTTP_CLIENT_INTERNAL;
+
+/**
+ * @author jaehong.kim
+ */
+@RunWith(PinpointPluginTestSuite.class)
+@PinpointAgent(AgentPath.PATH)
+@Dependency({"com.squareup.okhttp:okhttp:[2.0.0,3.0.0)", "org.nanohttpd:nanohttpd:2.3.1"})
+public class OkHttpClient_2_x_IT {
+
+ private static WebServer webServer;
+
+
+ @BeforeClass
+ public static void BeforeClass() throws Exception {
+ webServer = WebServer.newTestWebServer();
+ }
+
+
+ @AfterClass
+ public static void AfterClass() throws Exception {
+ final WebServer copy = webServer;
+ if (copy != null) {
+ copy.stop();
+ webServer = null;
+ }
+ }
+
+ @Test
+ public void execute() throws Exception {
+ Request request = new Request.Builder().url(webServer.getCallHttpUrl()).build();
+ OkHttpClient client = new OkHttpClient();
+ Response response = client.newCall(request).execute();
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+
+ Method executeMethod = Call.class.getDeclaredMethod("execute");
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), executeMethod));
+
+ Method sendRequestMethod = HttpEngine.class.getDeclaredMethod("sendRequest");
+ verifier.verifyTrace(event(OK_HTTP_CLIENT.getName(), sendRequestMethod,
+ null, null, webServer.getHostAndPort(),
+ annotation("http.url", request.urlString())));
+
+ URL url = request.url();
+ int port = EndPointUtils.getPort(url.getPort(), url.getDefaultPort());
+ String hostAndPort = HostAndPort.toHostAndPortString(url.getHost(), port);
+ Method connectMethod = getConnectMethod();
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), connectMethod,
+ annotation("http.internal.display", hostAndPort)));
+
+ Method readResponseMethod = HttpEngine.class.getDeclaredMethod("readResponse");
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), readResponseMethod,
+ annotation("http.status.code", response.code())));
+
+ verifier.verifyTraceCount(0);
+ }
+
+ @Test
+ public void enqueue() throws Exception {
+ Request request = new Request.Builder().url(webServer.getCallHttpUrl()).build();
+ OkHttpClient client = new OkHttpClient();
+ final CountDownLatch latch = new CountDownLatch(1);
+ final AtomicReference<Response> responseRef = new AtomicReference<Response>(null);
+ client.newCall(request).enqueue(new Callback() {
+ @Override
+ public void onFailure(Request request, IOException e) {
+ latch.countDown();
+ }
+
+ @Override
+ public void onResponse(Response response) throws IOException {
+ responseRef.set(response);
+ latch.countDown();
+ }
+ });
+ latch.await(3, TimeUnit.SECONDS);
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+
+
+ Method callEnqueueMethod = Call.class.getDeclaredMethod("enqueue", com.squareup.okhttp.Callback.class);
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), callEnqueueMethod));
+
+ Method dispatcherEnqueueMethod = Dispatcher.class.getDeclaredMethod("enqueue", Class.forName("com.squareup.okhttp.Call$AsyncCall"));
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), dispatcherEnqueueMethod));
+
+ verifier.verifyTrace(event(ASYNC.getName(), "Asynchronous Invocation"));
+
+ Method executeMethod = Class.forName("com.squareup.okhttp.Call$AsyncCall").getDeclaredMethod("execute");
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), executeMethod));
+
+ Method sendRequestMethod = HttpEngine.class.getDeclaredMethod("sendRequest");
+ verifier.verifyTrace(event(OK_HTTP_CLIENT.getName(), sendRequestMethod,
+ null, null, webServer.getHostAndPort(),
+ annotation("http.url", request.urlString())));
+
+ URL url = request.url();
+ int port = EndPointUtils.getPort(url.getPort(), url.getDefaultPort());
+ String hostAndPort = HostAndPort.toHostAndPortString(url.getHost(), port);
+ Method connectMethod = getConnectMethod();
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), connectMethod,
+ annotation("http.internal.display", hostAndPort)));
+
+ Response response = responseRef.get();
+ Assert.assertNotNull("response is null", response);
+ Method readResponseMethod = HttpEngine.class.getDeclaredMethod("readResponse");
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), readResponseMethod,
+ annotation("http.status.code", response.code())));
+
+ verifier.verifyTraceCount(0);
+ }
+
+ private Method getConnectMethod() {
+ try {
+ // [2.3.0,)
+ return HttpEngine.class.getDeclaredMethod("connect");
+ } catch (NoSuchMethodException e) {
+ try {
+ // [2.0.0,2.2.max]
+ return HttpEngine.class.getDeclaredMethod("connect", Request.class);
+ } catch (NoSuchMethodException e1) {
+ throw new AssertionError("Expected methods connect() / connect(com.squareup.okhttp.Request) not found in HttpEngine class");
+ }
+ }
+ }
+
+}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClient_3_0_0_to_3_3_x_IT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClient_3_0_0_to_3_3_x_IT.java
new file mode 100644
index 000000000000..6b410faac961
--- /dev/null
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClient_3_0_0_to_3_3_x_IT.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * 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.
+ */
+package com.navercorp.pinpoint.plugin.jdk7.okhttp;
+
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifierHolder;
+import com.navercorp.pinpoint.common.plugin.util.HostAndPort;
+import com.navercorp.pinpoint.plugin.AgentPath;
+import com.navercorp.pinpoint.plugin.WebServer;
+import com.navercorp.pinpoint.test.plugin.Dependency;
+import com.navercorp.pinpoint.test.plugin.PinpointAgent;
+import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
+import okhttp3.Call;
+import okhttp3.Callback;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.annotation;
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.event;
+import static com.navercorp.pinpoint.common.trace.ServiceType.ASYNC;
+import static com.navercorp.pinpoint.plugin.okhttp.OkHttpConstants.OK_HTTP_CLIENT;
+import static com.navercorp.pinpoint.plugin.okhttp.OkHttpConstants.OK_HTTP_CLIENT_INTERNAL;
+
+/**
+ * @author HyunGil Jeong
+ */
+@RunWith(PinpointPluginTestSuite.class)
+@PinpointAgent(AgentPath.PATH)
+@Dependency({"com.squareup.okhttp3:okhttp:[3.0.0,3.3.max]", "org.nanohttpd:nanohttpd:2.3.1"})
+public class OkHttpClient_3_0_0_to_3_3_x_IT {
+
+ private static WebServer webServer;
+
+
+ @BeforeClass
+ public static void BeforeClass() throws Exception {
+ webServer = WebServer.newTestWebServer();
+ }
+
+
+ @AfterClass
+ public static void AfterClass() throws Exception {
+ final WebServer copy = webServer;
+ if (copy != null) {
+ copy.stop();
+ webServer = null;
+ }
+ }
+
+ @Test
+ public void execute() throws Exception {
+ Request request = new Request.Builder().url(webServer.getCallHttpUrl()).build();
+ OkHttpClient client = new OkHttpClient();
+ Response response = client.newCall(request).execute();
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+
+ Method executeMethod = Class.forName("okhttp3.RealCall").getDeclaredMethod("execute");
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), executeMethod));
+
+ Method sendRequestMethod = Class.forName("okhttp3.internal.http.HttpEngine").getDeclaredMethod("sendRequest");
+ verifier.verifyTrace(event(OK_HTTP_CLIENT.getName(), sendRequestMethod,
+ null, null, webServer.getHostAndPort(),
+ annotation("http.url", request.url().toString())));
+
+ String hostAndPort = HostAndPort.toHostAndPortString(request.url().host(), request.url().port());
+ Method connectMethod = Class.forName("okhttp3.internal.http.HttpEngine").getDeclaredMethod("connect");
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), connectMethod,
+ annotation("http.internal.display", hostAndPort)));
+
+ Method readResponseMethod = Class.forName("okhttp3.internal.http.HttpEngine").getDeclaredMethod("readResponse");
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), readResponseMethod,
+ annotation("http.status.code", response.code())));
+
+ verifier.verifyTraceCount(0);
+ }
+
+ @Test
+ public void enqueue() throws Exception {
+ Request request = new Request.Builder().url(webServer.getCallHttpUrl()).build();
+ OkHttpClient client = new OkHttpClient();
+ final CountDownLatch latch = new CountDownLatch(1);
+ final AtomicReference<Response> responseRef = new AtomicReference<Response>(null);
+ client.newCall(request).enqueue(new Callback() {
+ @Override
+ public void onFailure(Call call, IOException e) {
+ latch.countDown();
+ }
+
+ @Override
+ public void onResponse(Call call, Response response) throws IOException {
+ responseRef.set(response);
+ latch.countDown();
+ }
+ });
+ latch.await(3, TimeUnit.SECONDS);
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+
+ Method realCallEnqueueMethod = Class.forName("okhttp3.RealCall").getDeclaredMethod("enqueue", Class.forName("okhttp3.Callback"));
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), realCallEnqueueMethod));
+
+ Method dispatcherEnqueueMethod = Class.forName("okhttp3.Dispatcher").getDeclaredMethod("enqueue", Class.forName("okhttp3.RealCall$AsyncCall"));
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), dispatcherEnqueueMethod));
+
+ verifier.verifyTrace(event(ASYNC.getName(), "Asynchronous Invocation"));
+
+ Method executeMethod = Class.forName("okhttp3.RealCall$AsyncCall").getDeclaredMethod("execute");
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), executeMethod));
+
+ Method sendRequestMethod = Class.forName("okhttp3.internal.http.HttpEngine").getDeclaredMethod("sendRequest");
+ verifier.verifyTrace(event(OK_HTTP_CLIENT.getName(), sendRequestMethod,
+ null, null, webServer.getHostAndPort(),
+ annotation("http.url", request.url().toString())));
+
+ String hostAndPort = HostAndPort.toHostAndPortString(request.url().host(), request.url().port());
+ Method connectMethod = Class.forName("okhttp3.internal.http.HttpEngine").getDeclaredMethod("connect");
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), connectMethod,
+ annotation("http.internal.display", hostAndPort)));
+
+ Response response = responseRef.get();
+ Method readResponseMethod = Class.forName("okhttp3.internal.http.HttpEngine").getDeclaredMethod("readResponse");
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), readResponseMethod,
+ annotation("http.status.code", response.code())));
+
+ verifier.verifyTraceCount(0);
+ }
+
+}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClient_3_4_0_to_3_x_IT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClient_3_4_0_to_3_x_IT.java
new file mode 100644
index 000000000000..cf6fe90c35b2
--- /dev/null
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/jdk7/okhttp/OkHttpClient_3_4_0_to_3_x_IT.java
@@ -0,0 +1,176 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * 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.
+ */
+package com.navercorp.pinpoint.plugin.jdk7.okhttp;
+
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifierHolder;
+import com.navercorp.pinpoint.common.plugin.util.HostAndPort;
+import com.navercorp.pinpoint.plugin.AgentPath;
+import com.navercorp.pinpoint.plugin.WebServer;
+import com.navercorp.pinpoint.test.plugin.Dependency;
+import com.navercorp.pinpoint.test.plugin.PinpointAgent;
+import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
+import okhttp3.Call;
+import okhttp3.Callback;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.annotation;
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.event;
+import static com.navercorp.pinpoint.common.trace.ServiceType.ASYNC;
+import static com.navercorp.pinpoint.plugin.okhttp.OkHttpConstants.OK_HTTP_CLIENT;
+import static com.navercorp.pinpoint.plugin.okhttp.OkHttpConstants.OK_HTTP_CLIENT_INTERNAL;
+
+/**
+ * @author HyunGil Jeong
+ */
+@RunWith(PinpointPluginTestSuite.class)
+@PinpointAgent(AgentPath.PATH)
+@Dependency({"com.squareup.okhttp3:okhttp:[3.4.0,)", "org.nanohttpd:nanohttpd:2.3.1"})
+public class OkHttpClient_3_4_0_to_3_x_IT {
+
+ private static WebServer webServer;
+
+
+ @BeforeClass
+ public static void BeforeClass() throws Exception {
+ webServer = WebServer.newTestWebServer();
+ }
+
+
+ @AfterClass
+ public static void AfterClass() throws Exception {
+ final WebServer copy = webServer;
+ if (copy != null) {
+ copy.stop();
+ webServer = null;
+ }
+ }
+
+ @Test
+ public void execute() throws Exception {
+ Request request = new Request.Builder().url(webServer.getCallHttpUrl()).build();
+ OkHttpClient client = new OkHttpClient();
+ Response response = client.newCall(request).execute();
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+
+ Method executeMethod = Class.forName("okhttp3.RealCall").getDeclaredMethod("execute");
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), executeMethod));
+
+ Method interceptMethod = Class.forName("okhttp3.internal.http.BridgeInterceptor").getDeclaredMethod("intercept", Class.forName("okhttp3.Interceptor$Chain"));
+ verifier.verifyTrace(event(OK_HTTP_CLIENT.getName(), interceptMethod,
+ null, null, webServer.getHostAndPort(),
+ annotation("http.url", request.url().toString()),
+ annotation("http.status.code", response.code())));
+
+ String hostAndPort = HostAndPort.toHostAndPortString(request.url().host(), request.url().port());
+ Method connectMethod = getConnectMethod(Class.forName("okhttp3.internal.connection.RealConnection"));
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), connectMethod,
+ annotation("http.internal.display", hostAndPort)));
+
+ verifier.verifyTraceCount(0);
+ }
+
+ @Test
+ public void enqueue() throws Exception {
+ Request request = new Request.Builder().url(webServer.getCallHttpUrl()).build();
+ OkHttpClient client = new OkHttpClient();
+ final CountDownLatch latch = new CountDownLatch(1);
+ final AtomicReference<Response> responseRef = new AtomicReference<Response>(null);
+ client.newCall(request).enqueue(new Callback() {
+ @Override
+ public void onFailure(Call call, IOException e) {
+ latch.countDown();
+ }
+
+ @Override
+ public void onResponse(Call call, Response response) throws IOException {
+ responseRef.set(response);
+ latch.countDown();
+ }
+ });
+ latch.await(3, TimeUnit.SECONDS);
+
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ verifier.printCache();
+
+ Method realCallEnqueueMethod = Class.forName("okhttp3.RealCall").getDeclaredMethod("enqueue", Class.forName("okhttp3.Callback"));
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), realCallEnqueueMethod));
+
+ Method dispatcherEnqueueMethod = Class.forName("okhttp3.Dispatcher").getDeclaredMethod("enqueue", Class.forName("okhttp3.RealCall$AsyncCall"));
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), dispatcherEnqueueMethod));
+
+ verifier.verifyTrace(event(ASYNC.getName(), "Asynchronous Invocation"));
+
+ Method executeMethod = Class.forName("okhttp3.RealCall$AsyncCall").getDeclaredMethod("execute");
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), executeMethod));
+
+ Response response = responseRef.get();
+ Method interceptMethod = Class.forName("okhttp3.internal.http.BridgeInterceptor").getDeclaredMethod("intercept", Class.forName("okhttp3.Interceptor$Chain"));
+ verifier.verifyTrace(event(OK_HTTP_CLIENT.getName(), interceptMethod,
+ null, null, webServer.getHostAndPort(),
+ annotation("http.url", request.url().toString()),
+ annotation("http.status.code", response.code())));
+
+ String hostAndPort = HostAndPort.toHostAndPortString(request.url().host(), request.url().port());
+ Method connectMethod = getConnectMethod(Class.forName("okhttp3.internal.connection.RealConnection"));
+ verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), connectMethod,
+ annotation("http.internal.display", hostAndPort)));
+
+ verifier.verifyTraceCount(0);
+ }
+
+ private Method getConnectMethod(Class<?> realConnectionClass) throws ClassNotFoundException {
+ // [3.4.0,3.5.max]
+ try {
+ return realConnectionClass.getDeclaredMethod("connect", int.class, int.class, int.class, List.class, boolean.class);
+ } catch (NoSuchMethodException e) {
+ try {
+ // [3.6.0,3.8.max]
+ return realConnectionClass.getDeclaredMethod("connect", int.class, int.class, int.class, boolean.class);
+ } catch (NoSuchMethodException e1) {
+ try {
+ // [3.9.0,3.9.max]
+ return realConnectionClass.getDeclaredMethod("connect", int.class, int.class, int.class, boolean.class,
+ Class.forName("okhttp3.Call"), Class.forName("okhttp3.EventListener"));
+ } catch (NoSuchMethodException e2) {
+ try {
+ // [3.10.0,)
+ return realConnectionClass.getDeclaredMethod("connect", int.class, int.class, int.class, int.class, boolean.class,
+ Class.forName("okhttp3.Call"), Class.forName("okhttp3.EventListener"));
+ } catch (NoSuchMethodException e3) {
+ throw new AssertionError("Expected methods connect(...) not found in RealConnection class");
+ }
+ }
+ }
+ }
+ }
+
+}
| val | test | "2018-10-31T09:09:34" | "2018-10-11T09:13:24Z" | pikuzi | test |
pinpoint-apm/pinpoint/4873_4880 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4873 | pinpoint-apm/pinpoint/4880 | [
"keyword_pr_to_issue"
] | 6ba94ec415c54382d3939810649e31f03a2fabe9 | 987c2e61b7996e5f3e2915852347ff821878a587 | [] | [] | "2018-11-09T09:11:06Z" | [
"enhancement",
"module:plugin"
] | Add trace support when using Thrift over HTTP | #### Description
When using Thrift over HTTP (using **THttpClient** and **TServlet**), jdk/apache http client is used internally to send HTTP request client side. Similarly, **TServlet** operates inside a servlet container, and the container will process these requests first.
We have plugins for both of these, so the Thrift plugin should not be the one doing trace propagation. | [
"agent-it/pom.xml",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftClientCallContext.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftTypeProvider.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/TServiceClientSendBaseInterceptor.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/TBaseProcessorProcessInterceptor.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/tprotocol/server/TProtocolReadMessageEndInterceptor.java"
] | [
"agent-it/pom.xml",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftClientCallContext.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftTypeProvider.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/field/getter/UrlFieldGetter.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/TServiceClientSendBaseInterceptor.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/TBaseProcessorProcessInterceptor.java",
"plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/tprotocol/server/TProtocolReadMessageEndInterceptor.java"
] | [
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/TestEnvironment.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/HttpEchoTestClient.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/SyncEchoTestClient.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/AsyncEchoTestServer.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/EchoTestServer.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/HttpEchoTestServer.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/SyncEchoTestServer.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/ThriftEchoTestServer.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/EchoTestRunner.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftHalfSyncHalfAsyncServerAsyncIT.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftNonblockingServerAsyncIT.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftThreadedSelectorServerAsyncIT.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/http/ThriftHttpIT.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftHalfSyncHalfAsyncServerIT.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftNonblockingServerIT.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftSimpleServerIT.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadPoolServerIT.java",
"agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadedSelectorServerIT.java"
] | diff --git a/agent-it/pom.xml b/agent-it/pom.xml
index 12c67cd20112..618c0d830418 100644
--- a/agent-it/pom.xml
+++ b/agent-it/pom.xml
@@ -365,6 +365,13 @@
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.eclipse.jetty</groupId>
+ <artifactId>jetty-server</artifactId>
+ <version>9.2.11.v20150529</version>
+ <scope>test</scope>
+ </dependency>
+
</dependencies>
<build>
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftClientCallContext.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftClientCallContext.java
index 482a87550770..2a3217372795 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftClientCallContext.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftClientCallContext.java
@@ -25,6 +25,8 @@ public class ThriftClientCallContext {
public static final ThriftHeader NONE = null;
private final String methodName;
+
+ private boolean isEntryPoint;
private ThriftHeader traceHeaderToBeRead;
@@ -37,7 +39,15 @@ public ThriftClientCallContext(String methodName) {
public String getMethodName() {
return methodName;
}
-
+
+ public boolean isEntryPoint() {
+ return isEntryPoint;
+ }
+
+ public void setEntryPoint(boolean entryPoint) {
+ isEntryPoint = entryPoint;
+ }
+
public ThriftHeader getTraceHeaderToBeRead() {
return traceHeaderToBeRead;
}
@@ -56,14 +66,12 @@ public void setTraceHeader(ThriftRequestProperty traceHeader) {
@Override
public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("ThriftClientCallContext={methodName=").append(this.methodName);
- sb.append(", traceHeaderToBeRead=").append(this.traceHeaderToBeRead.name());
- sb.append(", traceHeader=").append(this.traceHeader.toString());
- sb.append("}");
+ final StringBuilder sb = new StringBuilder("ThriftClientCallContext{");
+ sb.append("methodName='").append(methodName).append('\'');
+ sb.append(", isEntryPoint=").append(isEntryPoint);
+ sb.append(", traceHeaderToBeRead=").append(traceHeaderToBeRead);
+ sb.append(", traceHeader=").append(traceHeader);
+ sb.append('}');
return sb.toString();
}
-
-
-
}
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java
index ca70c0df91b0..d52d92d1c708 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftConstants.java
@@ -55,6 +55,7 @@ private ThriftConstants() {
public static final String T_ASYNC_METHOD_CALL_FIELD_TRANSPORT = "transport";
public static final String FRAME_BUFFER_FIELD_TRANS_ = "trans_";
public static final String FRAME_BUFFER_FIELD_IN_TRANS_ = "inTrans_";
+ public static final String T_HTTP_CLIENT_FIELD_URL_ = "url_";
// custom field injector (accessor) FQCN
private static final String FIELD_ACCESSOR_BASE = "com.navercorp.pinpoint.plugin.thrift.field.accessor.";
@@ -68,4 +69,5 @@ private ThriftConstants() {
public static final String FIELD_GETTER_T_NON_BLOCKING_TRANSPORT = FIELD_GETTER_BASE + "TNonblockingTransportFieldGetter";
public static final String FIELD_GETTER_T_TRANSPORT = FIELD_GETTER_BASE + "TTransportFieldGetter";
public static final String FIELD_GETTER_T_PROTOCOL = FIELD_GETTER_BASE + "TProtocolFieldGetter";
+ public static final String FIELD_GETTER_URL = FIELD_GETTER_BASE + "UrlFieldGetter";
}
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java
index 6260d49bdbfd..c310113801f6 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftPlugin.java
@@ -54,6 +54,7 @@ public void setup(ProfilerPluginSetupContext context) {
if (traceClient) {
addInterceptorsForSynchronousClients(config);
+ addTHttpClientEditor();
if (traceClientAsync) {
addInterceptorsForAsynchronousClients();
}
@@ -274,6 +275,19 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
});
}
+ // THttpClient
+
+ private void addTHttpClientEditor() {
+ transformTemplate.transform("org.apache.thrift.transport.THttpClient", new TransformCallback() {
+ @Override
+ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
+ final InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
+ target.addGetter(ThriftConstants.FIELD_GETTER_URL, ThriftConstants.T_HTTP_CLIENT_FIELD_URL_);
+ return target.toBytecode();
+ }
+ });
+ }
+
// Common
private void addInterceptorsForRetrievingSocketAddresses() {
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftTypeProvider.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftTypeProvider.java
index 96ba3d159592..c61e2ba68f0e 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftTypeProvider.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftTypeProvider.java
@@ -29,8 +29,8 @@ public class ThriftTypeProvider implements TraceMetadataProvider {
public void setup(TraceMetadataSetupContext context) {
context.addServiceType(ThriftConstants.THRIFT_SERVER);
context.addServiceType(ThriftConstants.THRIFT_CLIENT, AnnotationKeyMatchers.exact(ThriftConstants.THRIFT_URL));
- context.addServiceType(ThriftConstants.THRIFT_SERVER_INTERNAL, AnnotationKeyMatchers.ARGS_MATCHER);
- context.addServiceType(ThriftConstants.THRIFT_CLIENT_INTERNAL, AnnotationKeyMatchers.ARGS_MATCHER);
+ context.addServiceType(ThriftConstants.THRIFT_SERVER_INTERNAL, AnnotationKeyMatchers.exact(ThriftConstants.THRIFT_URL));
+ context.addServiceType(ThriftConstants.THRIFT_CLIENT_INTERNAL, AnnotationKeyMatchers.exact(ThriftConstants.THRIFT_URL));
context.addAnnotationKey(ThriftConstants.THRIFT_URL);
context.addAnnotationKey(ThriftConstants.THRIFT_ARGS);
context.addAnnotationKey(ThriftConstants.THRIFT_RESULT);
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java
index 6276cf4e46cf..1a6afb7bd2e3 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/ThriftUtils.java
@@ -76,7 +76,14 @@ public static String getClientServiceName(TServiceClient client) {
*/
public static String getAsyncMethodCallName(TAsyncMethodCall<?> asyncMethodCall) {
String asyncMethodCallClassName = asyncMethodCall.getClass().getName();
- return convertDotPathToUriPath(ThriftConstants.ASYNC_METHOD_CALL_PATTERN.matcher(asyncMethodCallClassName).replaceAll("."));
+ String convertedMethodCallName = convertDotPathToUriPath(ThriftConstants.ASYNC_METHOD_CALL_PATTERN.matcher(asyncMethodCallClassName).replaceAll("."));
+ // thrift java generator appends "_call" to the method name when naming the function class
+ // https://github.com/apache/thrift/blob/master/compiler/cpp/src/thrift/generate/t_java_generator.cc#L3151
+ final String callSuffix = "_call";
+ if (convertedMethodCallName.endsWith(callSuffix)) {
+ return convertedMethodCallName.substring(0, convertedMethodCallName.length() - callSuffix.length());
+ }
+ return convertedMethodCallName;
}
/**
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/field/getter/UrlFieldGetter.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/field/getter/UrlFieldGetter.java
new file mode 100644
index 000000000000..5109fb7fe843
--- /dev/null
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/field/getter/UrlFieldGetter.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * 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.
+ */
+
+package com.navercorp.pinpoint.plugin.thrift.field.getter;
+
+import java.net.URL;
+
+/**
+ * @author HyunGil Jeong
+ */
+public interface UrlFieldGetter {
+ URL _$PINPOINT$_getUrl();
+}
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/TServiceClientSendBaseInterceptor.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/TServiceClientSendBaseInterceptor.java
index a421db1c6546..61370df0384e 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/TServiceClientSendBaseInterceptor.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/client/TServiceClientSendBaseInterceptor.java
@@ -17,12 +17,16 @@
package com.navercorp.pinpoint.plugin.thrift.interceptor.client;
import java.net.Socket;
+import java.net.URL;
import com.navercorp.pinpoint.bootstrap.interceptor.scope.InterceptorScope;
+import com.navercorp.pinpoint.common.plugin.util.HostAndPort;
import com.navercorp.pinpoint.common.util.StringUtils;
+import com.navercorp.pinpoint.plugin.thrift.field.getter.UrlFieldGetter;
import org.apache.thrift.TBase;
import org.apache.thrift.TServiceClient;
import org.apache.thrift.protocol.TProtocol;
+import org.apache.thrift.transport.THttpClient;
import org.apache.thrift.transport.TTransport;
import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
@@ -84,43 +88,39 @@ public void before(Object target, Object[] args) {
if (trace == null) {
return;
}
- ThriftRequestProperty parentTraceInfo = new ThriftRequestProperty();
+
final boolean shouldSample = trace.canSampled();
if (!shouldSample) {
+ if (transport instanceof THttpClient) {
+ return;
+ }
+ ThriftRequestProperty parentTraceInfo = new ThriftRequestProperty();
if (isDebug) {
logger.debug("set Sampling flag=false");
}
- parentTraceInfo.setShouldSample(shouldSample);
+ parentTraceInfo.setShouldSample(false);
+ InterceptorScopeInvocation currentTransaction = this.scope.getCurrentInvocation();
+ currentTransaction.setAttachment(parentTraceInfo);
+ return;
+ }
+
+ SpanEventRecorder recorder = trace.traceBlockBegin();
+ String remoteAddress = ThriftConstants.UNKNOWN_ADDRESS;
+
+ // If we're writing to THttpClient, http client plugin will handle trace propagation.
+ // We simply record as basic method.
+ if (transport instanceof THttpClient) {
+ recorder.recordServiceType(ThriftConstants.THRIFT_CLIENT_INTERNAL);
+ remoteAddress = getRemoteAddressForTHttpClient((THttpClient) transport);
} else {
- SpanEventRecorder recorder = trace.traceBlockBegin();
recorder.recordServiceType(ThriftConstants.THRIFT_CLIENT);
-
- // retrieve connection information
- String remoteAddress = ThriftConstants.UNKNOWN_ADDRESS;
- if (transport instanceof SocketFieldAccessor) {
- Socket socket = ((SocketFieldAccessor)transport)._$PINPOINT$_getSocket();
- if (socket != null) {
- remoteAddress = ThriftUtils.getHostPort(socket.getRemoteSocketAddress());
- }
- } else {
- if (isDebug) {
- logger.debug("Invalid target object. Need field accessor({}).", SocketFieldAccessor.class.getName());
- }
- }
+ remoteAddress = getRemoteAddress(transport);
recorder.recordDestinationId(remoteAddress);
- String methodName = ThriftConstants.UNKNOWN_METHOD_NAME;
- if (args[0] instanceof String) {
- methodName = (String)args[0];
- }
- String serviceName = ThriftUtils.getClientServiceName(client);
-
- String thriftUrl = getServiceUrl(remoteAddress, serviceName, methodName);
- recorder.recordAttribute(ThriftConstants.THRIFT_URL, thriftUrl);
-
TraceId nextId = trace.getTraceId().getNextTraceId();
recorder.recordNextSpanId(nextId.getSpanId());
+ ThriftRequestProperty parentTraceInfo = new ThriftRequestProperty();
parentTraceInfo.setTraceId(nextId.getTransactionId());
parentTraceInfo.setSpanId(nextId.getSpanId());
parentTraceInfo.setParentSpanId(nextId.getParentSpanId());
@@ -129,10 +129,49 @@ public void before(Object target, Object[] args) {
parentTraceInfo.setParentApplicationName(traceContext.getApplicationName());
parentTraceInfo.setParentApplicationType(traceContext.getServerTypeCode());
parentTraceInfo.setAcceptorHost(remoteAddress);
+
+ InterceptorScopeInvocation currentTransaction = this.scope.getCurrentInvocation();
+ currentTransaction.setAttachment(parentTraceInfo);
+
+ }
+
+ String methodName = ThriftConstants.UNKNOWN_METHOD_NAME;
+ if (args[0] instanceof String) {
+ methodName = (String)args[0];
+ }
+ String serviceName = ThriftUtils.getClientServiceName(client);
+ String thriftUrl = getServiceUrl(remoteAddress, serviceName, methodName);
+ recorder.recordAttribute(ThriftConstants.THRIFT_URL, thriftUrl);
+ }
+ }
+
+ private String getRemoteAddressForTHttpClient(THttpClient tHttpClient) {
+ if (tHttpClient instanceof UrlFieldGetter) {
+ URL url = ((UrlFieldGetter) tHttpClient)._$PINPOINT$_getUrl();
+ if (url == null) {
+ return ThriftConstants.UNKNOWN_ADDRESS;
+ }
+ return HostAndPort.toHostAndPortString(url.getHost(), url.getPort());
+ }
+ if (isDebug) {
+ logger.debug("Invalid oprot transport object. Need field getter({}).", UrlFieldGetter.class.getName());
+ }
+ return ThriftConstants.UNKNOWN_ADDRESS;
+ }
+
+ private String getRemoteAddress(TTransport transport) {
+ if (transport instanceof SocketFieldAccessor) {
+ Socket socket = ((SocketFieldAccessor)transport)._$PINPOINT$_getSocket();
+ if (socket == null) {
+ return ThriftConstants.UNKNOWN_ADDRESS;
+ }
+ return ThriftUtils.getHostPort(socket.getRemoteSocketAddress());
+ } else {
+ if (isDebug) {
+ logger.debug("Invalid oprot transport object. Need field accessor({}).", SocketFieldAccessor.class.getName());
}
- InterceptorScopeInvocation currentTransaction = this.scope.getCurrentInvocation();
- currentTransaction.setAttachment(parentTraceInfo);
}
+ return ThriftConstants.UNKNOWN_ADDRESS;
}
private String getServiceUrl(String url, String serviceName, String methodName) {
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/TBaseProcessorProcessInterceptor.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/TBaseProcessorProcessInterceptor.java
index a29a9710d1ac..634b51683f83 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/TBaseProcessorProcessInterceptor.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/server/TBaseProcessorProcessInterceptor.java
@@ -94,41 +94,61 @@ public void after(Object target, Object[] args, Object result, Throwable throwab
if (trace == null) {
return;
}
+
+ InterceptorScopeInvocation currentTransaction = this.scope.getCurrentInvocation();
+ Object attachment = currentTransaction.getAttachment();
+ if (!(attachment instanceof ThriftClientCallContext)) {
+ return;
+ }
+
// logging here as some Thrift servers depend on TTransportException being thrown for normal operations.
// log only when current transaction is being traced.
if (isDebug) {
logger.afterInterceptor(target, args, result, throwable);
}
- this.traceContext.removeTraceObject();
+
+ ThriftClientCallContext clientCallContext = (ThriftClientCallContext) attachment;
+ if (clientCallContext.isEntryPoint()) {
+ traceContext.removeTraceObject();
+ }
+
if (trace.canSampled()) {
- try {
- processTraceObject(trace, target, args, throwable);
- } catch (Throwable t) {
- logger.warn("Error processing trace object. Cause:{}", t.getMessage(), t);
- } finally {
- trace.close();
+ String methodUri = getMethodUri(target);
+ if (clientCallContext.isEntryPoint()) {
+ finalizeSpan(trace, methodUri, throwable);
+ } else {
+ finalizeSpanEvent(trace, methodUri, throwable);
}
}
}
- private void processTraceObject(final Trace trace, Object target, Object[] args, Throwable throwable) {
- // end spanEvent
+ private void finalizeSpan(final Trace trace, String methodUri, Throwable throwable) {
+ try {
+ finalizeSpanEvent(trace, null, throwable);
+ SpanRecorder recorder = trace.getSpanRecorder();
+ recorder.recordRpcName(methodUri);
+ } catch (Throwable t) {
+ logger.warn("Error processing trace object. Cause:{}", t.getMessage(), t);
+ } finally {
+ trace.close();
+ }
+ }
+
+ private void finalizeSpanEvent(final Trace trace, String methodUri, Throwable throwable) {
try {
SpanEventRecorder recorder = trace.currentSpanEventRecorder();
// TODO Might need a way to collect and record method arguments
// trace.recordAttribute(...);
recorder.recordException(throwable);
recorder.recordApi(this.descriptor);
+ if (methodUri != null) {
+ recorder.recordAttribute(ThriftConstants.THRIFT_URL, methodUri);
+ }
} catch (Throwable t) {
logger.warn("Error processing trace object. Cause:{}", t.getMessage(), t);
} finally {
trace.traceBlockEnd();
}
-
- // end root span
- SpanRecorder recorder = trace.getSpanRecorder();
- String methodUri = getMethodUri(target);
- recorder.recordRpcName(methodUri);
}
private String getMethodUri(Object target) {
diff --git a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/tprotocol/server/TProtocolReadMessageEndInterceptor.java b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/tprotocol/server/TProtocolReadMessageEndInterceptor.java
index 4e2d43fed7bd..54a3148beae6 100644
--- a/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/tprotocol/server/TProtocolReadMessageEndInterceptor.java
+++ b/plugins/thrift/src/main/java/com/navercorp/pinpoint/plugin/thrift/interceptor/tprotocol/server/TProtocolReadMessageEndInterceptor.java
@@ -99,12 +99,9 @@ public void after(Object target, Object[] args, Object result, Throwable throwab
InterceptorScopeInvocation currentTransaction = this.scope.getCurrentInvocation();
Object attachment = currentTransaction.getAttachment();
if (attachment instanceof ThriftClientCallContext) {
- ThriftClientCallContext clientCallContext = (ThriftClientCallContext)attachment;
- String methodName = clientCallContext.getMethodName();
- ThriftRequestProperty parentTraceInfo = clientCallContext.getTraceHeader();
+ ThriftClientCallContext clientCallContext = (ThriftClientCallContext) attachment;
try {
- this.logger.debug("parentTraceInfo : {}", parentTraceInfo);
- recordTrace(target, parentTraceInfo, methodName);
+ recordTrace(target, clientCallContext);
} catch (Throwable t) {
logger.warn("Error creating trace object. Cause:{}", t.getMessage(), t);
}
@@ -132,8 +129,17 @@ private boolean validate(Object target) {
return true;
}
- private void recordTrace(Object target, ThriftRequestProperty parentTraceInfo, String methodName) {
- final Trace trace = createTrace(target, parentTraceInfo, methodName);
+ private void recordTrace(Object target, ThriftClientCallContext clientCallContext) {
+ String methodName = clientCallContext.getMethodName();
+ // Check if there is an active trace first for cases such as TServlet, which one of the WAS plugins would
+ // have created one already.
+ Trace trace = traceContext.currentRawTraceObject();
+ if (trace == null) {
+ ThriftRequestProperty parentTraceInfo = clientCallContext.getTraceHeader();
+ this.logger.debug("parentTraceInfo : {}", parentTraceInfo);
+ trace = createTrace(target, parentTraceInfo, methodName);
+ clientCallContext.setEntryPoint(true);
+ }
if (trace == null) {
return;
}
| diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/TestEnvironment.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/TestEnvironment.java
index 21b2c1274117..80ec15f2ecdc 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/TestEnvironment.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/TestEnvironment.java
@@ -29,14 +29,23 @@ public class TestEnvironment {
private static final int MIN_SERVER_PORT = 9091;
private static final int MAX_SERVER_PORT = 9099;
+ private static final String SERVER_HOST = "localhost";
private static final String SERVER_IP = "127.0.0.1";
private static final TProtocolFactory PROTOCOL_FACTORY = new TBinaryProtocol.Factory();
+ private static final String HTTP_PATH = "/thrift";
+ private final String serverHost = SERVER_HOST;
private final String serverIp = SERVER_IP;
private final int port = MIN_SERVER_PORT + (int)(Math.random() * (MAX_SERVER_PORT - MIN_SERVER_PORT) + 1);
+ private final String httpPath = HTTP_PATH;
+ private final String httpUrl = "http://" + serverHost + ":" + port + httpPath;
private final InetSocketAddress serverAddress = new InetSocketAddress(SERVER_IP, this.port);
private final TProtocolFactory protocolFactory = PROTOCOL_FACTORY;
+ public String getServerHost() {
+ return this.serverHost;
+ }
+
public String getServerIp() {
return this.serverIp;
}
@@ -45,6 +54,14 @@ public int getPort() {
return this.port;
}
+ public String getHttpPath() {
+ return this.httpPath;
+ }
+
+ public String getHttpUrl() {
+ return this.httpUrl;
+ }
+
public InetSocketAddress getServerAddress() {
return this.serverAddress;
}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java
index 5349eb6f4014..90dcdf13370f 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/AsyncEchoTestClient.java
@@ -107,7 +107,7 @@ public void verifyTraces(PluginTestVerifier verifier, String expectedMessage) th
// SpanEvent - TAsyncClientManager.call
Method call = TAsyncClientManager.class.getDeclaredMethod("call", TAsyncMethodCall.class);
ExpectedAnnotation thriftUrl = Expectations.annotation("thrift.url",
- remoteAddress + "/com/navercorp/pinpoint/plugin/thrift/dto/EchoService/echo_call");
+ remoteAddress + "/com/navercorp/pinpoint/plugin/thrift/dto/EchoService/echo");
ExpectedTrace callTrace = event("THRIFT_CLIENT", // ServiceType
call, // Method
null, // rpc
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/HttpEchoTestClient.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/HttpEchoTestClient.java
new file mode 100644
index 000000000000..18e9b62680bb
--- /dev/null
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/HttpEchoTestClient.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * 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.
+ */
+
+package com.navercorp.pinpoint.plugin.thrift.common.client;
+
+import com.navercorp.pinpoint.bootstrap.plugin.test.Expectations;
+import com.navercorp.pinpoint.bootstrap.plugin.test.ExpectedAnnotation;
+import com.navercorp.pinpoint.bootstrap.plugin.test.ExpectedTrace;
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
+import com.navercorp.pinpoint.common.plugin.util.HostAndPort;
+import com.navercorp.pinpoint.plugin.thrift.common.TestEnvironment;
+import com.navercorp.pinpoint.plugin.thrift.dto.EchoService;
+import org.apache.thrift.TBase;
+import org.apache.thrift.TException;
+import org.apache.thrift.TServiceClient;
+import org.apache.thrift.protocol.TProtocol;
+import org.apache.thrift.transport.THttpClient;
+import org.apache.thrift.transport.TTransportException;
+
+import java.lang.reflect.Method;
+import java.net.URL;
+
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.event;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class HttpEchoTestClient implements EchoTestClient {
+
+ private final TestEnvironment environment;
+ private final THttpClient httpClient;
+
+ private HttpEchoTestClient(TestEnvironment environment, THttpClient httpClient) throws TTransportException {
+ this.environment = environment;
+ this.httpClient = httpClient;
+ }
+
+ @Override
+ public String echo(String message) throws TException {
+ TProtocol protocol = environment.getProtocolFactory().getProtocol(httpClient);
+ EchoService.Client client = new EchoService.Client(protocol);
+ return client.echo(message);
+ }
+
+ @Override
+ public void verifyTraces(PluginTestVerifier verifier, String expectedMessage) throws Exception {
+ // ignore jdk http url connector traces
+ verifier.ignoreServiceType("JDK_HTTPURLCONNECTOR");
+
+ // refer to TServiceClientSendBaseInterceptor.getRemoteAddressForTHttpClient(...)
+ URL url = new URL(environment.getHttpUrl());
+ String hostAndPort = HostAndPort.toHostAndPortString(url.getHost(), url.getPort());
+
+ // SpanEvent - TServiceClient.sendBase
+ Method sendBaseMethod = TServiceClient.class.getDeclaredMethod("sendBase", String.class, TBase.class);
+ ExpectedAnnotation thriftUrl = Expectations.annotation("thrift.url",
+ hostAndPort + "/com/navercorp/pinpoint/plugin/thrift/dto/EchoService/echo");
+ ExpectedAnnotation thriftArgs = Expectations.annotation("thrift.args",
+ "echo_args(message:" + expectedMessage + ")");
+ ExpectedTrace tServiceClientSendBaseTrace = event(
+ "THRIFT_CLIENT_INTERNAL",
+ sendBaseMethod,
+ thriftUrl, thriftArgs);
+
+ // SpanEvent - HttpURLConnection.connect (ignore)
+
+ // SpanEvent - TServiceClient.receiveBase
+ Method receiveBaseMethod = TServiceClient.class.getDeclaredMethod("receiveBase", TBase.class, String.class);
+ ExpectedAnnotation thriftResult = Expectations.annotation(
+ "thrift.result", "echo_result(success:" + expectedMessage + ")");
+ ExpectedTrace tServiceClientReceiveBaseTrace = event(
+ "THRIFT_CLIENT_INTERNAL",
+ receiveBaseMethod,
+ thriftResult);
+
+ verifier.verifyDiscreteTrace(
+ tServiceClientSendBaseTrace,
+ tServiceClientReceiveBaseTrace);
+ }
+
+ @Override
+ public void close() {
+ httpClient.close();
+ }
+
+ public static HttpEchoTestClient create(TestEnvironment environment) throws TTransportException {
+ return new HttpEchoTestClient(environment, new THttpClient(environment.getHttpUrl()));
+ }
+}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/SyncEchoTestClient.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/SyncEchoTestClient.java
index 5749e6a3287a..8f9734da0dc1 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/SyncEchoTestClient.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/client/SyncEchoTestClient.java
@@ -61,13 +61,14 @@ public final String echo(String message) throws TException {
@Override
public void verifyTraces(PluginTestVerifier verifier, String expectedMessage) throws Exception {
+ // refer to TServiceClientSendBaseInterceptor.getRemoteAddress(...)
final InetSocketAddress socketAddress = this.environment.getServerAddress();
final String hostName = SocketAddressUtils.getHostNameFirst(socketAddress);
- // refer to com.navercorp.pinpoint.plugin.thrift.ThriftUtils#getHostPort
final String remoteAddress = HostAndPort.toHostAndPortString(hostName, socketAddress.getPort());
+
// SpanEvent - TServiceClient.sendBase
Method sendBase = TServiceClient.class.getDeclaredMethod("sendBase", String.class, TBase.class);
- // refer to com.navercorp.pinpoint.plugin.thrift.ThriftUtils#getClientServiceName
+
ExpectedAnnotation thriftUrl = Expectations.annotation("thrift.url",
remoteAddress + "/com/navercorp/pinpoint/plugin/thrift/dto/EchoService/echo");
ExpectedAnnotation thriftArgs = Expectations.annotation("thrift.args",
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/AsyncEchoTestServer.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/AsyncEchoTestServer.java
index 68ab6d616ebd..25240f7e2fb0 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/AsyncEchoTestServer.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/AsyncEchoTestServer.java
@@ -25,7 +25,9 @@
import com.navercorp.pinpoint.bootstrap.plugin.util.SocketAddressUtils;
import com.navercorp.pinpoint.common.plugin.util.HostAndPort;
import org.apache.thrift.TBaseAsyncProcessor;
+import org.apache.thrift.TException;
import org.apache.thrift.TProcessor;
+import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer;
import org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer;
import org.apache.thrift.server.THsHaServer;
@@ -43,9 +45,9 @@
/**
* @author HyunGil Jeong
*/
-public abstract class AsyncEchoTestServer<T extends AbstractNonblockingServer> extends EchoTestServer<T> {
+public abstract class AsyncEchoTestServer<T extends AbstractNonblockingServer> extends ThriftEchoTestServer<T> {
- protected AsyncEchoTestServer(T server, TestEnvironment environment) throws TTransportException {
+ protected AsyncEchoTestServer(T server, TestEnvironment environment) {
super(server, environment);
}
@@ -64,13 +66,17 @@ public void verifyServerTraces(PluginTestVerifier verifier) throws Exception {
));
// SpanEvent - TBaseAsyncProcessor.process
verifier.verifyTrace(event("THRIFT_SERVER_INTERNAL", process));
- verifier.verifyTraceCount(0);
}
public static class AsyncEchoTestServerFactory {
private static TProcessor getAsyncProcessor() {
- return new EchoService.AsyncProcessor<EchoService.AsyncIface>(new EchoServiceAsyncHandler());
+ return new EchoService.AsyncProcessor<EchoService.AsyncIface>(new EchoService.AsyncIface() {
+ @Override
+ public void echo(String message, AsyncMethodCallback<String> resultHandler) throws TException {
+ resultHandler.onComplete(message);
+ }
+ });
}
public static AsyncEchoTestServer<TThreadedSelectorServer> threadedSelectorServer(
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/EchoTestServer.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/EchoTestServer.java
index 8f461aea02a0..4bb87e17a8a9 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/EchoTestServer.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/EchoTestServer.java
@@ -5,7 +5,7 @@
* 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
+ * 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,
@@ -17,123 +17,17 @@
package com.navercorp.pinpoint.plugin.thrift.common.server;
import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
-import com.navercorp.pinpoint.plugin.thrift.common.TestEnvironment;
-import com.navercorp.pinpoint.plugin.thrift.common.client.AsyncEchoTestClient;
-import com.navercorp.pinpoint.plugin.thrift.common.client.SyncEchoTestClient;
-import com.navercorp.pinpoint.plugin.thrift.dto.EchoService;
-import org.apache.thrift.TException;
-import org.apache.thrift.async.AsyncMethodCallback;
-import org.apache.thrift.protocol.TProtocol;
-import org.apache.thrift.server.ServerContext;
-import org.apache.thrift.server.TServer;
-import org.apache.thrift.server.TServerEventHandler;
-import org.apache.thrift.transport.TTransport;
-import org.apache.thrift.transport.TTransportException;
-import java.io.IOException;
-import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
/**
* @author HyunGil Jeong
*/
-public abstract class EchoTestServer<T extends TServer> {
+public interface EchoTestServer {
- protected static class EchoServiceHandler implements EchoService.Iface {
- @Override
- public String echo(String message) throws TException {
- return message;
- }
- }
+ void start(ExecutorService executorService);
- protected static class EchoServiceAsyncHandler implements EchoService.AsyncIface {
-
- private final EchoServiceHandler syncHandler = new EchoServiceHandler();
-
- @SuppressWarnings("unchecked")
- @Override
- public void echo(String message, AsyncMethodCallback resultHandler) throws TException {
- try {
- final String echo = this.syncHandler.echo(message);
- resultHandler.onComplete(echo);
- } catch (Exception e) {
- resultHandler.onError(e);
- }
- }
- }
-
- private final T server;
-
- protected final TestEnvironment environment;
-
- protected EchoTestServer(T server, TestEnvironment environment) throws TTransportException {
- if (server == null) {
- throw new IllegalArgumentException("server cannot be null");
- }
- this.server = server;
- this.environment = environment;
- }
-
- public void start(ExecutorService executor) throws TTransportException, InterruptedException {
- if (this.server.isServing()) {
- return;
- }
-
- CountDownLatch waitToServeLatch = new CountDownLatch(1);
- server.setServerEventHandler(new WaitToServeHandler(waitToServeLatch));
-
- executor.execute(new Runnable() {
- @Override
- public void run() {
- server.serve();
- }
- });
-
- waitToServeLatch.await();
- }
-
- public void stop() {
- this.server.stop();
- }
-
- public void verifyTraces(PluginTestVerifier verifier) throws Exception {
- this.verifyServerTraces(verifier);
- }
-
- protected abstract void verifyServerTraces(PluginTestVerifier verifier) throws Exception;
-
- public abstract SyncEchoTestClient getSynchronousClient() throws TTransportException;
-
- public abstract AsyncEchoTestClient getAsynchronousClient() throws IOException;
-
-
- private class WaitToServeHandler implements TServerEventHandler {
-
- private final CountDownLatch waitToServeLatch;
-
- public WaitToServeHandler(CountDownLatch waitToServeLatch) {
- this.waitToServeLatch = waitToServeLatch;
- }
-
- @Override
- public void preServe() {
- waitToServeLatch.countDown();
- }
-
- @Override
- public ServerContext createContext(TProtocol tProtocol, TProtocol tProtocol1) {
- return null;
- }
-
- @Override
- public void deleteContext(ServerContext serverContext, TProtocol tProtocol, TProtocol tProtocol1) {
-
- }
-
- @Override
- public void processContext(ServerContext serverContext, TTransport tTransport, TTransport tTransport1) {
-
- }
- }
+ void stop();
+ void verifyTraces(PluginTestVerifier verifier) throws Exception;
}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/HttpEchoTestServer.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/HttpEchoTestServer.java
new file mode 100644
index 000000000000..a3b9f8fdd6c8
--- /dev/null
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/HttpEchoTestServer.java
@@ -0,0 +1,147 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * 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.
+ */
+
+package com.navercorp.pinpoint.plugin.thrift.common.server;
+
+import com.navercorp.pinpoint.bootstrap.plugin.test.Expectations;
+import com.navercorp.pinpoint.bootstrap.plugin.test.ExpectedAnnotation;
+import com.navercorp.pinpoint.bootstrap.plugin.test.ExpectedTrace;
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
+import com.navercorp.pinpoint.plugin.thrift.common.TestEnvironment;
+import com.navercorp.pinpoint.plugin.thrift.common.client.HttpEchoTestClient;
+import com.navercorp.pinpoint.plugin.thrift.dto.EchoService;
+import org.apache.thrift.TBaseProcessor;
+import org.apache.thrift.TException;
+import org.apache.thrift.TProcessor;
+import org.apache.thrift.protocol.TProtocol;
+import org.apache.thrift.protocol.TProtocolFactory;
+import org.apache.thrift.server.TServlet;
+import org.apache.thrift.transport.TTransportException;
+import org.eclipse.jetty.http.HttpStatus;
+import org.eclipse.jetty.server.Request;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.handler.AbstractHandler;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.util.concurrent.ExecutorService;
+
+import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.event;
+
+/**
+ * @author HyunGil Jeong
+ */
+public abstract class HttpEchoTestServer implements EchoTestServer {
+
+ private final TestEnvironment environment;
+ private final Server server;
+
+ protected HttpEchoTestServer(TestEnvironment environment, TProcessor processor) {
+ this.environment = environment;
+ int port = this.environment.getPort();
+ String path = this.environment.getHttpPath();
+ TProtocolFactory protocolFactory = this.environment.getProtocolFactory();
+ this.server = new Server(port);
+ this.server.setHandler(new EchoHttpServerHandler(path, processor, protocolFactory));
+ }
+
+ public abstract HttpEchoTestClient getHttpClient() throws TTransportException;
+
+ @Override
+ public void start(ExecutorService executorService) {
+ try {
+ server.start();
+ } catch (Exception e) {
+ throw new IllegalStateException("Failed to start EchoHttpServer.", e);
+ }
+ }
+
+ @Override
+ public void stop() {
+ if (server.isStarted()) {
+ try {
+ server.stop();
+ } catch (Exception e) {
+ throw new IllegalStateException("Failed to stop EchoHttpServer.", e);
+ }
+ }
+ }
+
+ @Override
+ public void verifyTraces(PluginTestVerifier verifier) throws Exception {
+ // ignore Jetty traces
+ verifier.ignoreServiceType("JETTY", "JETTY_METHOD");
+
+ // RootSpan - Jetty Servlet Process (ignore)
+
+ // SpanEvent - (Jetty) Server.handle (ignore)
+
+ // SpanEvent - TBaseProcessor.process
+ // refer to TBaseProcessorProcessInterceptor.finalizeSpanEvent(...)
+ Method processMethod = TBaseProcessor.class.getDeclaredMethod("process", TProtocol.class, TProtocol.class);
+ ExpectedAnnotation thriftUrl = Expectations.annotation(
+ "thrift.url", "com/navercorp/pinpoint/plugin/thrift/dto/EchoService/echo");
+ ExpectedTrace tBaseProcessorProcessTrace = event(
+ "THRIFT_SERVER_INTERNAL",
+ processMethod,
+ thriftUrl);
+
+ verifier.verifyDiscreteTrace(tBaseProcessorProcessTrace);
+ }
+
+ public static HttpEchoTestServer createServer(final TestEnvironment environment) {
+ TProcessor processor = new EchoService.Processor<EchoService.Iface>(new EchoService.Iface() {
+ @Override
+ public String echo(String message) throws TException {
+ return message;
+ }
+ });
+ return new HttpEchoTestServer(environment, processor) {
+ @Override
+ public HttpEchoTestClient getHttpClient() throws TTransportException {
+ return HttpEchoTestClient.create(environment);
+ }
+ };
+ }
+
+ private class EchoHttpServerHandler extends AbstractHandler {
+
+ private final String path;
+ private final TServlet servlet;
+
+ private EchoHttpServerHandler(String path, TProcessor processor, TProtocolFactory protocolFactory) {
+ this.path = path;
+ this.servlet = new TServlet(processor, protocolFactory) {
+ @Override
+ protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+ super.service(req, resp);
+ }
+ };
+ }
+
+ @Override
+ public void handle(String target, Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
+ if (path.equals(target)) {
+ servlet.service(httpServletRequest, httpServletResponse);
+ } else {
+ httpServletResponse.sendError(HttpStatus.NOT_FOUND_404, target + " is not available.");
+ }
+ }
+ }
+}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/SyncEchoTestServer.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/SyncEchoTestServer.java
index bc258236a01b..224e6fb7ade3 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/SyncEchoTestServer.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/SyncEchoTestServer.java
@@ -25,6 +25,7 @@
import com.navercorp.pinpoint.bootstrap.plugin.util.SocketAddressUtils;
import com.navercorp.pinpoint.common.plugin.util.HostAndPort;
import org.apache.thrift.TBaseProcessor;
+import org.apache.thrift.TException;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.server.THsHaServer;
@@ -46,9 +47,9 @@
/**
* @author HyunGil Jeong
*/
-public abstract class SyncEchoTestServer<T extends TServer> extends EchoTestServer<T> {
+public abstract class SyncEchoTestServer<T extends TServer> extends ThriftEchoTestServer<T> {
- protected SyncEchoTestServer(T server, TestEnvironment environment) throws TTransportException {
+ protected SyncEchoTestServer(T server, TestEnvironment environment) {
super(server, environment);
}
@@ -59,7 +60,8 @@ public void verifyServerTraces(PluginTestVerifier verifier) throws Exception {
verifier.verifyTraceCount(2);
Method process = TBaseProcessor.class.getDeclaredMethod("process", TProtocol.class, TProtocol.class);
verifier.verifyDiscreteTrace(
- // RootSpan - Thrift Server Invocation
+ // RootSpan - Thrift Server Invocation
+ // refer to TBaseProcessorProcessInterceptor.finalizeSpan(...)
root("THRIFT_SERVER", // ServiceType,
"Thrift Server Invocation", // Method
"com/navercorp/pinpoint/plugin/thrift/dto/EchoService/echo", // rpc
@@ -67,13 +69,17 @@ public void verifyServerTraces(PluginTestVerifier verifier) throws Exception {
address), // remoteAddress
// SpanEvent - TBaseProcessor.process
event("THRIFT_SERVER_INTERNAL", process));
- verifier.verifyTraceCount(0);
}
public static class SyncEchoTestServerFactory {
private static TProcessor getProcessor() {
- return new EchoService.Processor<EchoService.Iface>(new EchoServiceHandler());
+ return new EchoService.Processor<EchoService.Iface>(new EchoService.Iface() {
+ @Override
+ public String echo(String message) throws TException {
+ return message;
+ }
+ });
}
public static SyncEchoTestServer<TSimpleServer> simpleServer(final TestEnvironment environment)
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/ThriftEchoTestServer.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/ThriftEchoTestServer.java
new file mode 100644
index 000000000000..d5d63bd8496f
--- /dev/null
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/common/server/ThriftEchoTestServer.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * 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.
+ */
+
+package com.navercorp.pinpoint.plugin.thrift.common.server;
+
+import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
+import com.navercorp.pinpoint.plugin.thrift.common.TestEnvironment;
+import com.navercorp.pinpoint.plugin.thrift.common.client.AsyncEchoTestClient;
+import com.navercorp.pinpoint.plugin.thrift.common.client.SyncEchoTestClient;
+import org.apache.thrift.protocol.TProtocol;
+import org.apache.thrift.server.ServerContext;
+import org.apache.thrift.server.TServer;
+import org.apache.thrift.server.TServerEventHandler;
+import org.apache.thrift.transport.TTransport;
+import org.apache.thrift.transport.TTransportException;
+
+import java.io.IOException;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @author HyunGil Jeong
+ */
+public abstract class ThriftEchoTestServer<T extends TServer> implements EchoTestServer {
+
+ private final T server;
+
+ protected final TestEnvironment environment;
+
+ protected ThriftEchoTestServer(T server, TestEnvironment environment) {
+ if (server == null) {
+ throw new IllegalArgumentException("server cannot be null");
+ }
+ this.server = server;
+ this.environment = environment;
+ }
+
+ @Override
+ public void start(ExecutorService executor) {
+ if (this.server.isServing()) {
+ return;
+ }
+
+ CountDownLatch waitToServeLatch = new CountDownLatch(1);
+ server.setServerEventHandler(new WaitToServeHandler(waitToServeLatch));
+
+ executor.execute(new Runnable() {
+ @Override
+ public void run() {
+ server.serve();
+ }
+ });
+
+ boolean started = false;
+ try {
+ started = waitToServeLatch.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ if (!started) {
+ throw new IllegalStateException("Failed to start EchoThriftServer.");
+ }
+ }
+
+ @Override
+ public void stop() {
+ this.server.stop();
+ }
+
+ @Override
+ public void verifyTraces(PluginTestVerifier verifier) throws Exception {
+ this.verifyServerTraces(verifier);
+ }
+
+ protected abstract void verifyServerTraces(PluginTestVerifier verifier) throws Exception;
+
+ public abstract SyncEchoTestClient getSynchronousClient() throws TTransportException;
+
+ public abstract AsyncEchoTestClient getAsynchronousClient() throws IOException;
+
+
+ private class WaitToServeHandler implements TServerEventHandler {
+
+ private final CountDownLatch waitToServeLatch;
+
+ public WaitToServeHandler(CountDownLatch waitToServeLatch) {
+ this.waitToServeLatch = waitToServeLatch;
+ }
+
+ @Override
+ public void preServe() {
+ waitToServeLatch.countDown();
+ }
+
+ @Override
+ public ServerContext createContext(TProtocol tProtocol, TProtocol tProtocol1) {
+ return null;
+ }
+
+ @Override
+ public void deleteContext(ServerContext serverContext, TProtocol tProtocol, TProtocol tProtocol1) {
+
+ }
+
+ @Override
+ public void processContext(ServerContext serverContext, TTransport tTransport, TTransport tTransport1) {
+
+ }
+ }
+
+}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/EchoTestRunner.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/EchoTestRunner.java
index 9a293cd0bf4c..0863134e5c4e 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/EchoTestRunner.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/EchoTestRunner.java
@@ -19,7 +19,6 @@
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
-import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TTransportException;
import org.junit.After;
import org.junit.AfterClass;
@@ -35,21 +34,21 @@
/**
* @author HyunGil Jeong
*/
-public abstract class EchoTestRunner<T extends TServer> {
+public abstract class EchoTestRunner<T extends EchoTestServer> {
private static ExecutorService SERVER_EXECUTOR;
- private EchoTestServer<T> echoServer;
+ private T echoServer;
PluginTestVerifier verifier;
@BeforeClass
- public static void setUpBeforeClass() throws InterruptedException {
+ public static void setUpBeforeClass() {
SERVER_EXECUTOR = Executors.newSingleThreadExecutor();
}
@Before
- public void setUp() throws TTransportException, InterruptedException {
+ public void setUp() throws TTransportException {
this.echoServer = createEchoServer(new TestEnvironment());
this.verifier = PluginTestVerifierHolder.getInstance();
this.echoServer.start(SERVER_EXECUTOR);
@@ -67,17 +66,11 @@ public static void tearDownAfterClass() {
SERVER_EXECUTOR.shutdown();
}
- protected String invokeEcho(String message) throws Exception {
- final EchoTestClient echoClient = this.echoServer.getSynchronousClient();
- return invokeAndVerify(echoClient, message);
+ protected T getServer() {
+ return echoServer;
}
- protected String invokeEchoAsync(String message) throws Exception {
- final EchoTestClient echoClient = this.echoServer.getAsynchronousClient();
- return invokeAndVerify(echoClient, message);
- }
-
- private String invokeAndVerify(EchoTestClient echoClient, String message) throws Exception {
+ protected String invokeAndVerify(EchoTestClient echoClient, String message) throws Exception {
try {
return echoClient.echo(message);
} finally {
@@ -88,12 +81,13 @@ private String invokeAndVerify(EchoTestClient echoClient, String message) throws
}
}
- protected abstract EchoTestServer<T> createEchoServer(TestEnvironment environment) throws TTransportException;
+ protected abstract T createEchoServer(TestEnvironment environment) throws TTransportException;
private void verifyTraces(EchoTestClient echoClient, String expectedMessage) throws Exception {
this.verifier.printCache(System.out);
echoClient.verifyTraces(this.verifier, expectedMessage);
this.echoServer.verifyTraces(this.verifier);
+ this.verifier.verifyTraceCount(0);
}
}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftHalfSyncHalfAsyncServerAsyncIT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftHalfSyncHalfAsyncServerAsyncIT.java
index 99a8078aecc3..b206fd80b5e4 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftHalfSyncHalfAsyncServerAsyncIT.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftHalfSyncHalfAsyncServerAsyncIT.java
@@ -19,13 +19,15 @@
import static org.junit.Assert.assertEquals;
import com.navercorp.pinpoint.plugin.AgentPath;
+import com.navercorp.pinpoint.plugin.thrift.common.client.AsyncEchoTestClient;
+import com.navercorp.pinpoint.plugin.thrift.common.client.SyncEchoTestClient;
+import com.navercorp.pinpoint.plugin.thrift.common.server.ThriftEchoTestServer;
import org.apache.thrift.server.THsHaServer;
import org.apache.thrift.transport.TTransportException;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.navercorp.pinpoint.plugin.thrift.common.TestEnvironment;
-import com.navercorp.pinpoint.plugin.thrift.common.server.EchoTestServer;
import com.navercorp.pinpoint.plugin.thrift.common.server.AsyncEchoTestServer.AsyncEchoTestServerFactory;
import com.navercorp.pinpoint.plugin.thrift.it.EchoTestRunner;
import com.navercorp.pinpoint.test.plugin.Dependency;
@@ -42,11 +44,12 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
-@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
-public class ThriftHalfSyncHalfAsyncServerAsyncIT extends EchoTestRunner<THsHaServer> {
+@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)",
+ "org.slf4j:slf4j-simple:1.6.6", "org.slf4j:log4j-over-slf4j:1.6.6", "org.slf4j:slf4j-api:1.6.6" })
+public class ThriftHalfSyncHalfAsyncServerAsyncIT extends EchoTestRunner<ThriftEchoTestServer<THsHaServer>> {
@Override
- protected EchoTestServer<THsHaServer> createEchoServer(TestEnvironment environment) throws TTransportException {
+ protected ThriftEchoTestServer<THsHaServer> createEchoServer(TestEnvironment environment) throws TTransportException {
return AsyncEchoTestServerFactory.halfSyncHalfAsyncServer(environment);
}
@@ -55,7 +58,8 @@ public void testSynchronousRpcCall() throws Exception {
// Given
final String expectedMessage = "TEST_MESSAGE";
// When
- final String result = super.invokeEcho(expectedMessage);
+ final SyncEchoTestClient client = getServer().getSynchronousClient();
+ final String result = invokeAndVerify(client, expectedMessage);
// Then
assertEquals(expectedMessage, result);
}
@@ -65,7 +69,8 @@ public void testAsynchronousRpcCall() throws Exception {
// Given
final String expectedMessage = "TEST_MESSAGE";
// When
- final String result = super.invokeEchoAsync(expectedMessage);
+ final AsyncEchoTestClient client = getServer().getAsynchronousClient();
+ final String result = invokeAndVerify(client, expectedMessage);
// Then
assertEquals(expectedMessage, result);
}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftNonblockingServerAsyncIT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftNonblockingServerAsyncIT.java
index aa1ebdbd3583..f7cb6165ed6c 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftNonblockingServerAsyncIT.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftNonblockingServerAsyncIT.java
@@ -19,13 +19,15 @@
import static org.junit.Assert.assertEquals;
import com.navercorp.pinpoint.plugin.AgentPath;
+import com.navercorp.pinpoint.plugin.thrift.common.client.AsyncEchoTestClient;
+import com.navercorp.pinpoint.plugin.thrift.common.client.SyncEchoTestClient;
+import com.navercorp.pinpoint.plugin.thrift.common.server.ThriftEchoTestServer;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.transport.TTransportException;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.navercorp.pinpoint.plugin.thrift.common.TestEnvironment;
-import com.navercorp.pinpoint.plugin.thrift.common.server.EchoTestServer;
import com.navercorp.pinpoint.plugin.thrift.common.server.AsyncEchoTestServer.AsyncEchoTestServerFactory;
import com.navercorp.pinpoint.plugin.thrift.it.EchoTestRunner;
import com.navercorp.pinpoint.test.plugin.Dependency;
@@ -42,11 +44,12 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
-@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
-public class ThriftNonblockingServerAsyncIT extends EchoTestRunner<TNonblockingServer> {
+@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)",
+ "org.slf4j:slf4j-simple:1.6.6", "org.slf4j:log4j-over-slf4j:1.6.6", "org.slf4j:slf4j-api:1.6.6" })
+public class ThriftNonblockingServerAsyncIT extends EchoTestRunner<ThriftEchoTestServer<TNonblockingServer>> {
@Override
- protected EchoTestServer<TNonblockingServer> createEchoServer(TestEnvironment environment)
+ protected ThriftEchoTestServer<TNonblockingServer> createEchoServer(TestEnvironment environment)
throws TTransportException {
return AsyncEchoTestServerFactory.nonblockingServer(environment);
}
@@ -56,7 +59,8 @@ public void testSynchronousRpcCall() throws Exception {
// Given
final String expectedMessage = "TEST_MESSAGE";
// When
- final String result = super.invokeEcho(expectedMessage);
+ final SyncEchoTestClient client = getServer().getSynchronousClient();
+ final String result = invokeAndVerify(client, expectedMessage);
// Then
assertEquals(expectedMessage, result);
}
@@ -66,7 +70,8 @@ public void testAsynchronousRpcCall() throws Exception {
// Given
final String expectedMessage = "TEST_MESSAGE";
// When
- final String result = super.invokeEchoAsync(expectedMessage);
+ final AsyncEchoTestClient client = getServer().getAsynchronousClient();
+ final String result = invokeAndVerify(client, expectedMessage);
// Then
assertEquals(expectedMessage, result);
}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftThreadedSelectorServerAsyncIT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftThreadedSelectorServerAsyncIT.java
index 2dd4088a3b08..188ac280845e 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftThreadedSelectorServerAsyncIT.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/asynchronous/ThriftThreadedSelectorServerAsyncIT.java
@@ -19,13 +19,15 @@
import static org.junit.Assert.assertEquals;
import com.navercorp.pinpoint.plugin.AgentPath;
+import com.navercorp.pinpoint.plugin.thrift.common.client.AsyncEchoTestClient;
+import com.navercorp.pinpoint.plugin.thrift.common.client.SyncEchoTestClient;
+import com.navercorp.pinpoint.plugin.thrift.common.server.ThriftEchoTestServer;
import org.apache.thrift.server.TThreadedSelectorServer;
import org.apache.thrift.transport.TTransportException;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.navercorp.pinpoint.plugin.thrift.common.TestEnvironment;
-import com.navercorp.pinpoint.plugin.thrift.common.server.EchoTestServer;
import com.navercorp.pinpoint.plugin.thrift.common.server.AsyncEchoTestServer.AsyncEchoTestServerFactory;
import com.navercorp.pinpoint.plugin.thrift.it.EchoTestRunner;
import com.navercorp.pinpoint.test.plugin.Dependency;
@@ -42,11 +44,12 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
-@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
-public class ThriftThreadedSelectorServerAsyncIT extends EchoTestRunner<TThreadedSelectorServer> {
+@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)",
+ "org.slf4j:slf4j-simple:1.6.6", "org.slf4j:log4j-over-slf4j:1.6.6", "org.slf4j:slf4j-api:1.6.6" })
+public class ThriftThreadedSelectorServerAsyncIT extends EchoTestRunner<ThriftEchoTestServer<TThreadedSelectorServer>> {
@Override
- protected EchoTestServer<TThreadedSelectorServer> createEchoServer(TestEnvironment environment)
+ protected ThriftEchoTestServer<TThreadedSelectorServer> createEchoServer(TestEnvironment environment)
throws TTransportException {
return AsyncEchoTestServerFactory.threadedSelectorServer(environment);
}
@@ -56,7 +59,8 @@ public void testSynchronousRpcCall() throws Exception {
// Given
final String expectedMessage = "TEST_MESSAGE";
// When
- final String result = super.invokeEcho(expectedMessage);
+ final SyncEchoTestClient client = getServer().getSynchronousClient();
+ final String result = invokeAndVerify(client, expectedMessage);
// Then
assertEquals(expectedMessage, result);
}
@@ -66,7 +70,8 @@ public void testAsynchronousRpcCall() throws Exception {
// Given
final String expectedMessage = "TEST_MESSAGE";
// When
- final String result = super.invokeEchoAsync(expectedMessage);
+ final AsyncEchoTestClient client = getServer().getAsynchronousClient();
+ final String result = invokeAndVerify(client, expectedMessage);
// Then
assertEquals(expectedMessage, result);
}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/http/ThriftHttpIT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/http/ThriftHttpIT.java
new file mode 100644
index 000000000000..df3b3b738eb9
--- /dev/null
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/http/ThriftHttpIT.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ *
+ * 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.
+ */
+
+package com.navercorp.pinpoint.plugin.thrift.it.http;
+
+import com.navercorp.pinpoint.plugin.AgentPath;
+import com.navercorp.pinpoint.plugin.thrift.common.TestEnvironment;
+import com.navercorp.pinpoint.plugin.thrift.common.client.HttpEchoTestClient;
+import com.navercorp.pinpoint.plugin.thrift.common.server.HttpEchoTestServer;
+import com.navercorp.pinpoint.plugin.thrift.it.EchoTestRunner;
+import com.navercorp.pinpoint.test.plugin.Dependency;
+import com.navercorp.pinpoint.test.plugin.JvmVersion;
+import com.navercorp.pinpoint.test.plugin.PinpointAgent;
+import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
+import org.apache.thrift.transport.TTransportException;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * @author HyunGil Jeong
+ */
+@RunWith(PinpointPluginTestSuite.class)
+@PinpointAgent(AgentPath.PATH)
+@JvmVersion(8)
+@Dependency({ "org.apache.thrift:libthrift:[0.9.1,)", "org.eclipse.jetty:jetty-server:9.2.11.v20150529",
+ "org.slf4j:slf4j-simple:1.6.6", "org.slf4j:log4j-over-slf4j:1.6.6", "org.slf4j:slf4j-api:1.6.6" })
+public class ThriftHttpIT extends EchoTestRunner<HttpEchoTestServer> {
+
+ @Override
+ protected HttpEchoTestServer createEchoServer(TestEnvironment environment) throws TTransportException {
+ return HttpEchoTestServer.createServer(environment);
+ }
+
+ @Test
+ public void testThriftHttpCall() throws Exception {
+ // Given
+ final String expectedMessage = "TEST_MESSAGE";
+ // When
+ final HttpEchoTestClient client = getServer().getHttpClient();
+ final String result = invokeAndVerify(client, expectedMessage);
+ // Then
+ assertEquals(expectedMessage, result);
+ }
+}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftHalfSyncHalfAsyncServerIT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftHalfSyncHalfAsyncServerIT.java
index ccf410aa0ae3..56016c3ed036 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftHalfSyncHalfAsyncServerIT.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftHalfSyncHalfAsyncServerIT.java
@@ -19,13 +19,15 @@
import static org.junit.Assert.assertEquals;
import com.navercorp.pinpoint.plugin.AgentPath;
+import com.navercorp.pinpoint.plugin.thrift.common.client.AsyncEchoTestClient;
+import com.navercorp.pinpoint.plugin.thrift.common.client.SyncEchoTestClient;
+import com.navercorp.pinpoint.plugin.thrift.common.server.ThriftEchoTestServer;
import org.apache.thrift.server.THsHaServer;
import org.apache.thrift.transport.TTransportException;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.navercorp.pinpoint.plugin.thrift.common.TestEnvironment;
-import com.navercorp.pinpoint.plugin.thrift.common.server.EchoTestServer;
import com.navercorp.pinpoint.plugin.thrift.common.server.SyncEchoTestServer.SyncEchoTestServerFactory;
import com.navercorp.pinpoint.plugin.thrift.it.EchoTestRunner;
import com.navercorp.pinpoint.test.plugin.Dependency;
@@ -42,11 +44,12 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
-@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
-public class ThriftHalfSyncHalfAsyncServerIT extends EchoTestRunner<THsHaServer> {
+@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)",
+ "org.slf4j:slf4j-simple:1.6.6", "org.slf4j:log4j-over-slf4j:1.6.6", "org.slf4j:slf4j-api:1.6.6" })
+public class ThriftHalfSyncHalfAsyncServerIT extends EchoTestRunner<ThriftEchoTestServer<THsHaServer>> {
@Override
- protected EchoTestServer<THsHaServer> createEchoServer(TestEnvironment environment) throws TTransportException {
+ protected ThriftEchoTestServer<THsHaServer> createEchoServer(TestEnvironment environment) throws TTransportException {
return SyncEchoTestServerFactory.halfSyncHalfAsyncServer(environment);
}
@@ -55,7 +58,8 @@ public void testSynchronousRpcCall() throws Exception {
// Given
final String expectedMessage = "TEST_MESSAGE";
// When
- final String result = super.invokeEcho(expectedMessage);
+ final SyncEchoTestClient client = getServer().getSynchronousClient();
+ final String result = invokeAndVerify(client, expectedMessage);
// Then
assertEquals(expectedMessage, result);
}
@@ -65,7 +69,8 @@ public void testAsynchronousRpcCall() throws Exception {
// Given
final String expectedMessage = "TEST_MESSAGE";
// When
- final String result = super.invokeEchoAsync(expectedMessage);
+ final AsyncEchoTestClient client = getServer().getAsynchronousClient();
+ final String result = invokeAndVerify(client, expectedMessage);
// Then
assertEquals(expectedMessage, result);
}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftNonblockingServerIT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftNonblockingServerIT.java
index 1843c26f8ec4..4cdd9a152167 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftNonblockingServerIT.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftNonblockingServerIT.java
@@ -19,13 +19,15 @@
import static org.junit.Assert.assertEquals;
import com.navercorp.pinpoint.plugin.AgentPath;
+import com.navercorp.pinpoint.plugin.thrift.common.client.AsyncEchoTestClient;
+import com.navercorp.pinpoint.plugin.thrift.common.client.SyncEchoTestClient;
+import com.navercorp.pinpoint.plugin.thrift.common.server.ThriftEchoTestServer;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.transport.TTransportException;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.navercorp.pinpoint.plugin.thrift.common.TestEnvironment;
-import com.navercorp.pinpoint.plugin.thrift.common.server.EchoTestServer;
import com.navercorp.pinpoint.plugin.thrift.common.server.SyncEchoTestServer.SyncEchoTestServerFactory;
import com.navercorp.pinpoint.plugin.thrift.it.EchoTestRunner;
import com.navercorp.pinpoint.test.plugin.Dependency;
@@ -42,11 +44,12 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
-@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
-public class ThriftNonblockingServerIT extends EchoTestRunner<TNonblockingServer> {
+@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)",
+ "org.slf4j:slf4j-simple:1.6.6", "org.slf4j:log4j-over-slf4j:1.6.6", "org.slf4j:slf4j-api:1.6.6" })
+public class ThriftNonblockingServerIT extends EchoTestRunner<ThriftEchoTestServer<TNonblockingServer>> {
@Override
- protected EchoTestServer<TNonblockingServer> createEchoServer(TestEnvironment environment)
+ protected ThriftEchoTestServer<TNonblockingServer> createEchoServer(TestEnvironment environment)
throws TTransportException {
return SyncEchoTestServerFactory.nonblockingServer(environment);
}
@@ -56,7 +59,8 @@ public void testSynchronousRpcCall() throws Exception {
// Given
final String expectedMessage = "TEST_MESSAGE";
// When
- final String result = super.invokeEcho(expectedMessage);
+ final SyncEchoTestClient client = getServer().getSynchronousClient();
+ final String result = invokeAndVerify(client, expectedMessage);
// Then
assertEquals(expectedMessage, result);
}
@@ -66,7 +70,8 @@ public void testAsynchronousRpcCall() throws Exception {
// Given
final String expectedMessage = "TEST_MESSAGE";
// When
- final String result = super.invokeEchoAsync(expectedMessage);
+ final AsyncEchoTestClient client = getServer().getAsynchronousClient();
+ final String result = invokeAndVerify(client, expectedMessage);
// Then
assertEquals(expectedMessage, result);
}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftSimpleServerIT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftSimpleServerIT.java
index 3fb02bce8c51..a71aef4ed0d6 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftSimpleServerIT.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftSimpleServerIT.java
@@ -19,13 +19,14 @@
import static org.junit.Assert.*;
import com.navercorp.pinpoint.plugin.AgentPath;
+import com.navercorp.pinpoint.plugin.thrift.common.client.SyncEchoTestClient;
+import com.navercorp.pinpoint.plugin.thrift.common.server.ThriftEchoTestServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TTransportException;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.navercorp.pinpoint.plugin.thrift.common.TestEnvironment;
-import com.navercorp.pinpoint.plugin.thrift.common.server.EchoTestServer;
import com.navercorp.pinpoint.plugin.thrift.common.server.SyncEchoTestServer.SyncEchoTestServerFactory;
import com.navercorp.pinpoint.plugin.thrift.it.EchoTestRunner;
import com.navercorp.pinpoint.test.plugin.Dependency;
@@ -41,11 +42,12 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
-@Dependency({ "org.apache.thrift:libthrift:[0.9.1,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
-public class ThriftSimpleServerIT extends EchoTestRunner<TSimpleServer> {
+@Dependency({ "org.apache.thrift:libthrift:[0.9.1,)",
+ "org.slf4j:slf4j-simple:1.6.6", "org.slf4j:log4j-over-slf4j:1.6.6", "org.slf4j:slf4j-api:1.6.6" })
+public class ThriftSimpleServerIT extends EchoTestRunner<ThriftEchoTestServer<TSimpleServer>> {
@Override
- protected EchoTestServer<TSimpleServer> createEchoServer(TestEnvironment environment) throws TTransportException {
+ protected ThriftEchoTestServer<TSimpleServer> createEchoServer(TestEnvironment environment) throws TTransportException {
return SyncEchoTestServerFactory.simpleServer(environment);
}
@@ -54,7 +56,8 @@ public void testSynchronousRpcCall() throws Exception {
// Given
final String expectedMessage = "TEST_MESSAGE";
// When
- final String result = super.invokeEcho(expectedMessage);
+ final SyncEchoTestClient client = getServer().getSynchronousClient();
+ final String result = invokeAndVerify(client, expectedMessage);
// Then
assertEquals(expectedMessage, result);
}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadPoolServerIT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadPoolServerIT.java
index d7117679a19d..7216ea4073d8 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadPoolServerIT.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadPoolServerIT.java
@@ -19,13 +19,14 @@
import static org.junit.Assert.assertEquals;
import com.navercorp.pinpoint.plugin.AgentPath;
+import com.navercorp.pinpoint.plugin.thrift.common.client.SyncEchoTestClient;
+import com.navercorp.pinpoint.plugin.thrift.common.server.ThriftEchoTestServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TTransportException;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.navercorp.pinpoint.plugin.thrift.common.TestEnvironment;
-import com.navercorp.pinpoint.plugin.thrift.common.server.EchoTestServer;
import com.navercorp.pinpoint.plugin.thrift.common.server.SyncEchoTestServer.SyncEchoTestServerFactory;
import com.navercorp.pinpoint.plugin.thrift.it.EchoTestRunner;
import com.navercorp.pinpoint.test.plugin.Dependency;
@@ -41,11 +42,12 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
-@Dependency({ "org.apache.thrift:libthrift:[0.9.1,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
-public class ThriftThreadPoolServerIT extends EchoTestRunner<TThreadPoolServer> {
+@Dependency({ "org.apache.thrift:libthrift:[0.9.1,)",
+ "org.slf4j:slf4j-simple:1.6.6", "org.slf4j:log4j-over-slf4j:1.6.6", "org.slf4j:slf4j-api:1.6.6" })
+public class ThriftThreadPoolServerIT extends EchoTestRunner<ThriftEchoTestServer<TThreadPoolServer>> {
@Override
- protected EchoTestServer<TThreadPoolServer> createEchoServer(TestEnvironment environment)
+ protected ThriftEchoTestServer<TThreadPoolServer> createEchoServer(TestEnvironment environment)
throws TTransportException {
return SyncEchoTestServerFactory.threadedPoolServer(environment);
}
@@ -55,7 +57,8 @@ public void testSynchronousRpcCall() throws Exception {
// Given
final String expectedMessage = "TEST_MESSAGE";
// When
- final String result = super.invokeEcho(expectedMessage);
+ final SyncEchoTestClient client = getServer().getSynchronousClient();
+ final String result = invokeAndVerify(client, expectedMessage);
// Then
assertEquals(expectedMessage, result);
}
diff --git a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadedSelectorServerIT.java b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadedSelectorServerIT.java
index 652722c620ec..c08c3dae00b7 100644
--- a/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadedSelectorServerIT.java
+++ b/agent-it/src/test/java/com/navercorp/pinpoint/plugin/thrift/it/synchronous/ThriftThreadedSelectorServerIT.java
@@ -19,13 +19,15 @@
import static org.junit.Assert.assertEquals;
import com.navercorp.pinpoint.plugin.AgentPath;
+import com.navercorp.pinpoint.plugin.thrift.common.client.AsyncEchoTestClient;
+import com.navercorp.pinpoint.plugin.thrift.common.client.SyncEchoTestClient;
+import com.navercorp.pinpoint.plugin.thrift.common.server.ThriftEchoTestServer;
import org.apache.thrift.server.TThreadedSelectorServer;
import org.apache.thrift.transport.TTransportException;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.navercorp.pinpoint.plugin.thrift.common.TestEnvironment;
-import com.navercorp.pinpoint.plugin.thrift.common.server.EchoTestServer;
import com.navercorp.pinpoint.plugin.thrift.common.server.SyncEchoTestServer.SyncEchoTestServerFactory;
import com.navercorp.pinpoint.plugin.thrift.it.EchoTestRunner;
import com.navercorp.pinpoint.test.plugin.Dependency;
@@ -42,11 +44,12 @@
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
-@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)", "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.22" })
-public class ThriftThreadedSelectorServerIT extends EchoTestRunner<TThreadedSelectorServer> {
+@Dependency({ "org.apache.thrift:libthrift:[0.10.0,)",
+ "org.slf4j:slf4j-simple:1.6.6", "org.slf4j:log4j-over-slf4j:1.6.6", "org.slf4j:slf4j-api:1.6.6" })
+public class ThriftThreadedSelectorServerIT extends EchoTestRunner<ThriftEchoTestServer<TThreadedSelectorServer>> {
@Override
- protected EchoTestServer<TThreadedSelectorServer> createEchoServer(TestEnvironment environment)
+ protected ThriftEchoTestServer<TThreadedSelectorServer> createEchoServer(TestEnvironment environment)
throws TTransportException {
return SyncEchoTestServerFactory.threadedSelectorServer(environment);
}
@@ -56,7 +59,8 @@ public void testSynchronousRpcCall() throws Exception {
// Given
final String expectedMessage = "TEST_MESSAGE";
// When
- final String result = super.invokeEcho(expectedMessage);
+ final SyncEchoTestClient client = getServer().getSynchronousClient();
+ final String result = invokeAndVerify(client, expectedMessage);
// Then
assertEquals(expectedMessage, result);
}
@@ -66,7 +70,8 @@ public void testAsynchronousRpcCall() throws Exception {
// Given
final String expectedMessage = "TEST_MESSAGE";
// When
- final String result = super.invokeEchoAsync(expectedMessage);
+ final AsyncEchoTestClient client = getServer().getAsynchronousClient();
+ final String result = invokeAndVerify(client, expectedMessage);
// Then
assertEquals(expectedMessage, result);
}
| test | test | "2018-11-09T07:57:55" | "2018-11-09T02:22:24Z" | Xylus | test |
pinpoint-apm/pinpoint/4970_4972 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/4970 | pinpoint-apm/pinpoint/4972 | [
"keyword_pr_to_issue"
] | 4026eab38232d4c116748c56df5b61ff5e207610 | 07e21a66298e74f4759cde3ec23b808ed8bf51c9 | [] | [] | "2018-12-06T07:33:38Z" | [
"enhancement",
"module:plugin"
] | Add support for MySQL java connector 8+ | #### Description
Add trace support for MySQL java connector 8.
related issue - #4958 | [
"plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java"
] | [
"plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java"
] | [] | diff --git a/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java b/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java
index c40113ddd0c8..ed952dad2f90 100644
--- a/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java
+++ b/plugins/mysql-jdbc/src/main/java/com/navercorp/pinpoint/plugin/jdbc/mysql/MySqlPlugin.java
@@ -93,6 +93,10 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
// 6.0.4+
constructor_6_X = target.getConstructor("com.mysql.cj.core.conf.url.HostInfo");
}
+ if (constructor_6_X == null) {
+ // 8.x+
+ constructor_6_X = target.getConstructor("com.mysql.cj.conf.HostInfo");
+ }
if (constructor_6_X != null) {
target.addGetter("com.navercorp.pinpoint.plugin.jdbc.mysql.interceptor.getter.OrigHostToConnectToGetter", "origHostToConnectTo");
target.addGetter("com.navercorp.pinpoint.plugin.jdbc.mysql.interceptor.getter.OrigPortToConnectToGetter", "origPortToConnectTo");
@@ -214,6 +218,9 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
transformTemplate.transform("com.mysql.jdbc.PreparedStatement", transformCallback);
// 6.x+
transformTemplate.transform("com.mysql.cj.jdbc.PreparedStatement", transformCallback);
+ // 8.0.11+
+ transformTemplate.transform("com.mysql.cj.jdbc.ClientPreparedStatement", transformCallback);
+ transformTemplate.transform("com.mysql.cj.jdbc.ServerPreparedStatement", transformCallback);
}
private void addCallableStatementTransformer(final MySqlConfig config) {
| null | train | test | "2018-12-06T06:34:08" | "2018-12-06T05:22:11Z" | Xylus | test |
pinpoint-apm/pinpoint/5026_5134 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/5026 | pinpoint-apm/pinpoint/5134 | [
"keyword_pr_to_issue"
] | 18ac6db340a3e9e5207ad6ae79e9bebaeebe9826 | 08cbfd2ba90abedc08801e9daa7b81a5e77665f1 | [] | [] | "2019-01-14T10:49:56Z" | [
"enhancement",
"module:web"
] | Sort agent ids in containers by start timestamp in descending order | #### Description
Sort container agent ids in Inspector View's agent list by their start timestamp in descending order. | [
"web/src/main/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsList.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsList.java"
] | [
"web/src/test/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsListTest.java"
] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsList.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsList.java
index 62529b25c1bc..2b12a9184c02 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsList.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsList.java
@@ -22,6 +22,7 @@
import java.util.ArrayList;
import java.util.Collections;
+import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -41,17 +42,48 @@ public enum GroupBy {
protected GroupingKey extractKey(AgentInfo agentInfo) {
return new StringGroupingKey(agentInfo.getApplicationName());
}
+
+ @Override
+ protected Comparator<AgentInfo> getComparator() {
+ return AgentInfo.AGENT_NAME_ASC_COMPARATOR;
+ }
},
HOST_NAME {
@Override
protected GroupingKey extractKey(AgentInfo agentInfo) {
return new HostNameContainerGroupingKey(agentInfo.getHostName(), agentInfo.isContainer());
}
+
+ @Override
+ protected Comparator<AgentInfo> getComparator() {
+ return (agentInfo1, agentInfo2) -> {
+ if (agentInfo1.isContainer() && agentInfo2.isContainer()) {
+ // reverse start time order if both are containers
+ return Long.compare(agentInfo2.getStartTimestamp(), agentInfo1.getStartTimestamp());
+ }
+ if (agentInfo1.isContainer()) {
+ return -1;
+ }
+ if (agentInfo2.isContainer()) {
+ return 1;
+ }
+ // agent id order if both are not containers
+ return AgentInfo.AGENT_NAME_ASC_COMPARATOR.compare(agentInfo1, agentInfo2);
+ };
+ }
};
protected abstract GroupingKey extractKey(AgentInfo agentInfo);
+
+ /**
+ * Do not use this for sorted set and maps.
+ */
+ protected abstract Comparator<AgentInfo> getComparator();
}
+ /**
+ * Implementations not consistent with <code>equals</code>, for internal use only.
+ */
private interface GroupingKey<T extends GroupingKey<T>> extends Comparable<T> {
String value();
}
@@ -104,7 +136,7 @@ public List<ApplicationAgentList> getApplicationAgentLists() {
for (Map.Entry<GroupingKey, List<AgentInfo>> e : agentsMap.entrySet()) {
GroupingKey groupingKey = e.getKey();
List<AgentInfo> applicationAgents = new ArrayList<>(e.getValue());
- applicationAgents.sort(AgentInfo.AGENT_NAME_ASC_COMPARATOR);
+ applicationAgents.sort(groupBy.getComparator());
applicationAgentLists.add(new ApplicationAgentList(groupingKey.value(), applicationAgents));
}
return applicationAgentLists;
@@ -175,10 +207,10 @@ public int compareTo(HostNameContainerGroupingKey o) {
return 0;
}
if (isContainer) {
- return 1;
+ return -1;
}
if (o.isContainer) {
- return -1;
+ return 1;
}
return hostNameGroupingKey.compareTo(o.hostNameGroupingKey);
}
| diff --git a/web/src/test/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsListTest.java b/web/src/test/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsListTest.java
index db813b604f05..a05f62b51b1b 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsListTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/vo/ApplicationAgentsListTest.java
@@ -57,44 +57,44 @@ public void groupByApplicationName() {
}
@Test
- public void groupByHostNameShouldHaveContainersLastAndGroupedSeparately() {
+ public void groupByHostNameShouldHaveContainersFirstAndGroupedSeparatelyByAgentStartTimestampDescendingOrder() {
ApplicationAgentsList applicationAgentsList = new ApplicationAgentsList(ApplicationAgentsList.GroupBy.HOST_NAME, ApplicationAgentsList.Filter.NONE);
AgentInfo host1Agent1 = createAgentInfo("APP_1", "host1-agent1", "Host1", false);
AgentInfo host2Agent1 = createAgentInfo("APP_1", "host2-agent1", "Host2", false);
- AgentInfo containerAgent1 = createAgentInfo("APP_1", "container-agent1", "Host3", true);
- AgentInfo containerAgent2 = createAgentInfo("APP_1", "container-agent2", "Host4", true);
+ AgentInfo containerAgent1 = createAgentInfo("APP_1", "container-agent1", "Host3", true, 1);
+ AgentInfo containerAgent2 = createAgentInfo("APP_1", "container-agent2", "Host4", true, 2);
applicationAgentsList.addAll(shuffleAgentInfos(containerAgent1, host1Agent1, host2Agent1, containerAgent2));
List<ApplicationAgentList> applicationAgentLists = applicationAgentsList.getApplicationAgentLists();
Assert.assertEquals(3, applicationAgentLists.size());
- ApplicationAgentList host1AgentList = applicationAgentLists.get(0);
+ ApplicationAgentList containerAgentList = applicationAgentLists.get(0);
+ Assert.assertEquals(ApplicationAgentsList.HostNameContainerGroupingKey.CONTAINER, containerAgentList.getGroupName());
+ List<AgentInfo> containerAgents = containerAgentList.getAgentInfos();
+ Assert.assertEquals(2, containerAgents.size());
+ Assert.assertEquals(containerAgent2, containerAgents.get(0));
+ Assert.assertEquals(containerAgent1, containerAgents.get(1));
+
+ ApplicationAgentList host1AgentList = applicationAgentLists.get(1);
Assert.assertEquals("Host1", host1AgentList.getGroupName());
List<AgentInfo> host1Agents = host1AgentList.getAgentInfos();
Assert.assertEquals(1, host1Agents.size());
Assert.assertEquals(host1Agent1, host1Agents.get(0));
- ApplicationAgentList host2AgentList = applicationAgentLists.get(1);
+ ApplicationAgentList host2AgentList = applicationAgentLists.get(2);
Assert.assertEquals("Host2", host2AgentList.getGroupName());
List<AgentInfo> host2Agents = host2AgentList.getAgentInfos();
Assert.assertEquals(1, host2Agents.size());
Assert.assertEquals(host2Agent1, host2Agents.get(0));
-
- ApplicationAgentList containerAgentList = applicationAgentLists.get(2);
- Assert.assertEquals(ApplicationAgentsList.HostNameContainerGroupingKey.CONTAINER, containerAgentList.getGroupName());
- List<AgentInfo> containerAgents = containerAgentList.getAgentInfos();
- Assert.assertEquals(2, containerAgents.size());
- Assert.assertEquals(containerAgent1, containerAgents.get(0));
- Assert.assertEquals(containerAgent2, containerAgents.get(1));
}
@Test
public void mergeLists() {
AgentInfo host1Agent1 = createAgentInfo("APP_1", "host1-agent1", "Host1", false);
AgentInfo host2Agent1 = createAgentInfo("APP_1", "host2-agent1", "Host2", false);
- AgentInfo containerAgent1 = createAgentInfo("APP_1", "container-agent1", "Host3", true);
- AgentInfo containerAgent2 = createAgentInfo("APP_1", "container-agent2", "Host4", true);
+ AgentInfo containerAgent1 = createAgentInfo("APP_1", "container-agent1", "Host3", true, 1);
+ AgentInfo containerAgent2 = createAgentInfo("APP_1", "container-agent2", "Host4", true, 2);
List<AgentInfo> agentInfos = shuffleAgentInfos(containerAgent1, host1Agent1, host2Agent1, containerAgent2);
ApplicationAgentsList applicationAgentsList = new ApplicationAgentsList(ApplicationAgentsList.GroupBy.HOST_NAME, ApplicationAgentsList.Filter.NONE);
@@ -107,24 +107,24 @@ public void mergeLists() {
Assert.assertEquals(3, applicationAgentLists.size());
- ApplicationAgentList host1AgentList = applicationAgentLists.get(0);
+ ApplicationAgentList containerAgentList = applicationAgentLists.get(0);
+ Assert.assertEquals(ApplicationAgentsList.HostNameContainerGroupingKey.CONTAINER, containerAgentList.getGroupName());
+ List<AgentInfo> containerAgents = containerAgentList.getAgentInfos();
+ Assert.assertEquals(2, containerAgents.size());
+ Assert.assertEquals(containerAgent2, containerAgents.get(0));
+ Assert.assertEquals(containerAgent1, containerAgents.get(1));
+
+ ApplicationAgentList host1AgentList = applicationAgentLists.get(1);
Assert.assertEquals("Host1", host1AgentList.getGroupName());
List<AgentInfo> host1Agents = host1AgentList.getAgentInfos();
Assert.assertEquals(1, host1Agents.size());
Assert.assertEquals(host1Agent1, host1Agents.get(0));
- ApplicationAgentList host2AgentList = applicationAgentLists.get(1);
+ ApplicationAgentList host2AgentList = applicationAgentLists.get(2);
Assert.assertEquals("Host2", host2AgentList.getGroupName());
List<AgentInfo> host2Agents = host2AgentList.getAgentInfos();
Assert.assertEquals(1, host2Agents.size());
Assert.assertEquals(host2Agent1, host2Agents.get(0));
-
- ApplicationAgentList containerAgentList = applicationAgentLists.get(2);
- Assert.assertEquals(ApplicationAgentsList.HostNameContainerGroupingKey.CONTAINER, containerAgentList.getGroupName());
- List<AgentInfo> containerAgents = containerAgentList.getAgentInfos();
- Assert.assertEquals(2, containerAgents.size());
- Assert.assertEquals(containerAgent1, containerAgents.get(0));
- Assert.assertEquals(containerAgent2, containerAgents.get(1));
}
@Test
@@ -143,23 +143,23 @@ public void mergeListsGroupedDifferently() {
Assert.assertEquals(3, applicationAgentLists.size());
- ApplicationAgentList host1AgentList = applicationAgentLists.get(0);
+ ApplicationAgentList containerAgentList = applicationAgentLists.get(0);
+ Assert.assertEquals(ApplicationAgentsList.HostNameContainerGroupingKey.CONTAINER, containerAgentList.getGroupName());
+ List<AgentInfo> containerAgents = containerAgentList.getAgentInfos();
+ Assert.assertEquals(1, containerAgents.size());
+ Assert.assertEquals(agent3, containerAgents.get(0));
+
+ ApplicationAgentList host1AgentList = applicationAgentLists.get(1);
Assert.assertEquals("Host1", host1AgentList.getGroupName());
List<AgentInfo> host1Agents = host1AgentList.getAgentInfos();
Assert.assertEquals(1, host1Agents.size());
Assert.assertEquals(agent1, host1Agents.get(0));
- ApplicationAgentList host2AgentList = applicationAgentLists.get(1);
+ ApplicationAgentList host2AgentList = applicationAgentLists.get(2);
Assert.assertEquals("Host2", host2AgentList.getGroupName());
List<AgentInfo> host2Agents = host2AgentList.getAgentInfos();
Assert.assertEquals(1, host2Agents.size());
Assert.assertEquals(agent2, host2Agents.get(0));
-
- ApplicationAgentList containerAgentList = applicationAgentLists.get(2);
- Assert.assertEquals(ApplicationAgentsList.HostNameContainerGroupingKey.CONTAINER, containerAgentList.getGroupName());
- List<AgentInfo> containerAgents = containerAgentList.getAgentInfos();
- Assert.assertEquals(1, containerAgents.size());
- Assert.assertEquals(agent3, containerAgents.get(0));
}
private static List<AgentInfo> shuffleAgentInfos(AgentInfo... agentInfos) {
@@ -169,11 +169,16 @@ private static List<AgentInfo> shuffleAgentInfos(AgentInfo... agentInfos) {
}
private static AgentInfo createAgentInfo(String applicationName, String agentId, String hostname, boolean container) {
+ return createAgentInfo(applicationName, agentId, hostname, container, System.currentTimeMillis());
+ }
+
+ private static AgentInfo createAgentInfo(String applicationName, String agentId, String hostname, boolean container, long startTimestamp) {
AgentInfo agentInfo = new AgentInfo();
agentInfo.setApplicationName(applicationName);
agentInfo.setAgentId(agentId);
agentInfo.setHostName(hostname);
agentInfo.setContainer(container);
+ agentInfo.setStartTimestamp(startTimestamp);
return agentInfo;
}
}
| train | test | "2019-01-14T06:37:54" | "2018-12-19T05:42:29Z" | Xylus | test |
pinpoint-apm/pinpoint/5274_5278 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/5274 | pinpoint-apm/pinpoint/5278 | [
"keyword_pr_to_issue"
] | 3dac9297635315914a7933b27d7e1a32aa189586 | 14d970d743d27c9d3196ae11c294f1979da0ecd3 | [] | [] | "2019-02-26T06:30:29Z" | [
"bug",
"module:agent"
] | Parent application namespace header is not set correctly | #### What version of pinpoint are you using?
Affects 1.8.0, 1.8.1, 1.8.2
#### Describe the bug
Value set for `profiler.application.namespace` in *pinpoint.config*, is not propagated to a remote node via **Pinpoint-pAppNamespace**. Instead, the application name is propagated over to a remote node.
If both sender and receiver set `profiler.application.namespace` to the same value, it will not work as intended, and the receiver will start a new trace.
The bug has no affect if `profiler.application.namespace` option is not set.
#### What did you do to trigger the bug?
Steps to reproduce, for example:
1. Set `profiler.application.namespace` option to some value for sender and receiver.
2. Send HTTP calls from sender to receiver.
#### Expected behavior
The call between the sender and receiver is traced as a single transaction.
#### Screenshots
N/A
#### Logs
N/A
#### Additional context
`profiler.application.namespace` must be set and be the same value for both sender/receiver.
| [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/request/DefaultRequestTraceWriter.java"
] | [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/request/DefaultRequestTraceWriter.java"
] | [] | diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/request/DefaultRequestTraceWriter.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/request/DefaultRequestTraceWriter.java
index b37e3c97d9af..93e8988fc82e 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/request/DefaultRequestTraceWriter.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/plugin/request/DefaultRequestTraceWriter.java
@@ -23,11 +23,15 @@
import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
import com.navercorp.pinpoint.bootstrap.sampler.SamplingFlagUtils;
import com.navercorp.pinpoint.common.util.Assert;
+import com.navercorp.pinpoint.common.util.StringUtils;
/**
* @author jaehong.kim
*/
public class DefaultRequestTraceWriter<T> implements RequestTraceWriter<T> {
+
+ private static final String NOT_SET = null;
+
private final PLogger logger = PLoggerFactory.getLogger(this.getClass());
private final boolean isDebug = logger.isDebugEnabled();
private final ClientHeaderAdaptor<T> clientHeaderAdaptor;
@@ -36,7 +40,7 @@ public class DefaultRequestTraceWriter<T> implements RequestTraceWriter<T> {
private final String applicationNamespace;
public DefaultRequestTraceWriter(ClientHeaderAdaptor<T> clientHeaderAdaptor, TraceContext traceContext) {
- this(clientHeaderAdaptor, traceContext.getApplicationName(), traceContext.getServerTypeCode(), traceContext.getApplicationName());
+ this(clientHeaderAdaptor, traceContext.getApplicationName(), traceContext.getServerTypeCode(), traceContext.getProfilerConfig().getApplicationNamespace());
}
public DefaultRequestTraceWriter(ClientHeaderAdaptor<T> clientHeaderAdaptor, String applicationName, short serverTypeCode, String applicationNamespace) {
@@ -44,7 +48,11 @@ public DefaultRequestTraceWriter(ClientHeaderAdaptor<T> clientHeaderAdaptor, Str
this.applicationName = Assert.requireNonNull(applicationName, "applicationName must not be null");
this.serverTypeCode = serverTypeCode;
- this.applicationNamespace = Assert.requireNonNull(applicationNamespace, "applicationNamespace must not be null");
+ if (StringUtils.isEmpty(applicationNamespace)) {
+ this.applicationNamespace = NOT_SET;
+ } else {
+ this.applicationNamespace = applicationNamespace;
+ }
}
@Override
@@ -70,7 +78,7 @@ public void write(T header, final TraceId traceId, final String host) {
clientHeaderAdaptor.setHeader(header, Header.HTTP_PARENT_APPLICATION_NAME.toString(), applicationName);
clientHeaderAdaptor.setHeader(header, Header.HTTP_PARENT_APPLICATION_TYPE.toString(), Short.toString(serverTypeCode));
- if (applicationNamespace != null) {
+ if (applicationNamespace != NOT_SET) {
clientHeaderAdaptor.setHeader(header, Header.HTTP_PARENT_APPLICATION_NAMESPACE.toString(), applicationNamespace);
}
| null | train | test | "2019-02-25T11:21:33" | "2019-02-25T08:17:01Z" | Xylus | test |
pinpoint-apm/pinpoint/5297_5328 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/5297 | pinpoint-apm/pinpoint/5328 | [
"keyword_issue_to_pr"
] | 01cc80190727e3afe037a948b1e825249f410cdd | e16e39cf4da395b4d15a1dc7b481e53218ddb095 | [
"@jicai There isn't any yet.",
"Please replace the driver with hbase-2.0.\r\n\r\nIt will probably work normally.",
"@RoySRose @emeroad \r\nThank you for your reply.",
"https://hbase.apache.org/book.html#hbase.versioning\r\n> Client-Server wire protocol compatibility\r\nAllows updating client and server out of sync.\r\n> We could only allow upgrading the server first. I.e. the server would be backward compatible to an old client, that way new APIs are OK.\r\n> Example: A user should be able to use an old client to connect to an upgraded cluster.\r\n\r\n~~The hbase version policy is the same as above, but it does not know whether it will actually work.~~\r\n\r\nMajor | Minor | Patch\r\n-- | -- | --\r\nClient-Server wire Compatibility | N | Y | Y\r\n\r\nMajor version upgrades do not guarantee wire-protocol compatibility.",
"Hello, @jicai \r\n\r\nHbase2 support #5328 has been merged.\r\ntake a look at the [guide](https://naver.github.io/pinpoint/hbaseupgrade.html)\r\n\r\nLove to hear your feedback\r\n\r\n"
] | [] | "2019-03-11T10:24:51Z" | [
"question"
] | support for hbase 2.x | Are there any plans to support HBase 2.x ? thank you!
| [
"agent-it/pom.xml",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ParallelResultScanner.java",
"doc/compatibilityHbase.md",
"doc/faq.md",
"plugins/hbase/pom.xml",
"pom.xml"
] | [
"agent-it/pom.xml",
"commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ParallelResultScanner.java",
"doc/compatibilityHbase.md",
"doc/faq.md",
"doc/hbase-upgrade.md",
"plugins/hbase/pom.xml",
"pom.xml"
] | [
"web/src/test/java/com/navercorp/pinpoint/web/filter/AcceptUrlFilterTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/filter/Base64.java",
"web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java",
"web/src/test/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilterTest.java"
] | diff --git a/agent-it/pom.xml b/agent-it/pom.xml
index e9be76f4d79a..15f2d273faa4 100644
--- a/agent-it/pom.xml
+++ b/agent-it/pom.xml
@@ -367,6 +367,7 @@
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-shaded-client</artifactId>
+ <version>1.2.6.1</version>
<scope>test</scope>
</dependency>
diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ParallelResultScanner.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ParallelResultScanner.java
index 2bb2f16c2725..db10d8e744d1 100644
--- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ParallelResultScanner.java
+++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/parallel/ParallelResultScanner.java
@@ -23,6 +23,7 @@
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
@@ -178,6 +179,14 @@ public void close() {
}
}
+ public boolean renewLease() {
+ return false;
+ }
+
+ public ScanMetrics getScanMetrics() {
+ return null;
+ }
+
@Override
public Iterator<Result> iterator() {
// Identical to HTable.ClientScanner implementation
diff --git a/doc/compatibilityHbase.md b/doc/compatibilityHbase.md
index ebcdf14fa60a..a070a8059a35 100755
--- a/doc/compatibilityHbase.md
+++ b/doc/compatibilityHbase.md
@@ -1,8 +1,9 @@
-Pinpoint Version | HBase 0.94.x | HBase 0.98.x | HBase 1.0.x | HBase 1.2.x
----------------- | ------------ | ------------ | ----------- | -----------
-1.0.x | yes | no | no | no
-1.1.x | no | not tested | yes | not tested
-1.5.x | no | not tested | yes | not tested
-1.6.x | no | not tested | not tested | yes
-1.7.x | no | not tested | not tested | yes
-1.8.x | no | not tested | not tested | yes
+Pinpoint Version | HBase 0.94.x | HBase 0.98.x | HBase 1.0.x | HBase 1.2.x | HBase 2.x.x (BETA)
+---------------- | ------------ | ------------ | ----------- | ----------- | -----------
+1.0.x | yes | no | no | no | not tested
+1.1.x | no | not tested | yes | not tested | not tested
+1.5.x | no | not tested | yes | not tested | not tested
+1.6.x | no | not tested | not tested | yes | not tested
+1.7.x | no | not tested | not tested | yes | not tested
+1.8.x | no | not tested | not tested | yes | not tested
+1.9.x | no | not tested | not tested | yes | yes
\ No newline at end of file
diff --git a/doc/faq.md b/doc/faq.md
index c8419fbe0568..814b4a60d873 100755
--- a/doc/faq.md
+++ b/doc/faq.md
@@ -62,3 +62,7 @@ This data is used to better understand how users interact with the Web UI which
config.sendUsage=false
```
+### I'd like to use Hbase 2.x for Pinpoint.
+If you'd like to use Hbase 2.x for Pinpoint database, check out [Hbase upgrade guide](https://naver.github.io/pinpoint/plugindevguide.html).
+
+
diff --git a/doc/hbase-upgrade.md b/doc/hbase-upgrade.md
new file mode 100755
index 000000000000..fc53f0e06329
--- /dev/null
+++ b/doc/hbase-upgrade.md
@@ -0,0 +1,33 @@
+---
+title: Hbase Upgrade
+keywords: hbase, upgrade
+last_updated: Mar 8, 2019
+sidebar: mydoc_sidebar
+permalink: hbaseupgrade.html
+disqus: false
+---
+
+## Do you like to use Hbase 2.x for Pinpoint?
+
+Default settings of current releases are for Hbase 1.x.
+
+If you'd like to use Hbase 2.x for Pinpoint database,
+You have to recompile Pinpoint. Version of `hbase-shaded-client` library need to be changed to 2.x.
+(recommend v2.1.1, tested)
+
+You can recompile
+
+with `hbase2` profile added
+
+`mvn clean install -P hbase2,release -DskipTests=true`
+
+or with command (replacing version)
+
+`mvn clean install -Dhbase.shaded.client.version=2.1.1 -DskipTests=true`
+
+or after changing the version directly from pom.xml
+
+```java
+<!-- hbase -->
+<hbase.shaded.client.version>1.2.6.1</hbase.shaded.client.version>
+```
diff --git a/plugins/hbase/pom.xml b/plugins/hbase/pom.xml
index 993065ff5880..345fb15365e0 100644
--- a/plugins/hbase/pom.xml
+++ b/plugins/hbase/pom.xml
@@ -41,6 +41,7 @@
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-shaded-client</artifactId>
+ <version>1.2.6.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
diff --git a/pom.xml b/pom.xml
index 0af908907a82..9aa9c07e3ef2 100644
--- a/pom.xml
+++ b/pom.xml
@@ -95,6 +95,9 @@
<jdk.home>${env.JAVA_6_HOME}</jdk.home>
<test.jdk.home>${jdk.home}</test.jdk.home>
+ <!-- hbase -->
+ <hbase.shaded.client.version>1.2.6.1</hbase.shaded.client.version>
+
<!-- library -->
<slf4j.version>1.7.21</slf4j.version>
<metrics.version>3.1.2</metrics.version>
@@ -400,7 +403,7 @@
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-shaded-client</artifactId>
- <version>1.2.6.1</version>
+ <version>${hbase.shaded.client.version}</version>
</dependency>
<dependency>
@@ -1032,6 +1035,14 @@
</reporting>
<profiles>
+ <!-- for Hbase2 -->
+ <profile>
+ <id>hbase2</id>
+ <properties>
+ <hbase.shaded.client.version>2.1.1</hbase.shaded.client.version>
+ </properties>
+ </profile>
+
<!-- for Local (Development) -->
<profile>
<id>local</id>
| diff --git a/web/src/test/java/com/navercorp/pinpoint/web/filter/AcceptUrlFilterTest.java b/web/src/test/java/com/navercorp/pinpoint/web/filter/AcceptUrlFilterTest.java
index 1bdf41cc5022..5e3351508cbf 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/filter/AcceptUrlFilterTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/filter/AcceptUrlFilterTest.java
@@ -17,7 +17,6 @@
package com.navercorp.pinpoint.web.filter;
import com.navercorp.pinpoint.common.server.bo.SpanBo;
-import org.apache.hadoop.hbase.util.Base64;
import org.junit.Assert;
import org.junit.Test;
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/filter/Base64.java b/web/src/test/java/com/navercorp/pinpoint/web/filter/Base64.java
new file mode 100644
index 000000000000..bae6291d70f9
--- /dev/null
+++ b/web/src/test/java/com/navercorp/pinpoint/web/filter/Base64.java
@@ -0,0 +1,446 @@
+package com.navercorp.pinpoint.web.filter;
+/*
+ * Copyright 2019 NAVER Corp.
+ *
+ * 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.
+ */
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+import java.io.Serializable;
+import java.io.UnsupportedEncodingException;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.GZIPOutputStream;
+
+/**
+ * copy org.apache.hadoop.hbase.util.Base64
+ *
+ */
+
+public class Base64 {
+ private static final Log LOG = LogFactory.getLog(Base64.class);
+ private static final byte[] _STANDARD_ALPHABET = new byte[]{65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47};
+ private static final byte[] _STANDARD_DECODABET = new byte[]{-9, -9, -9, -9, -9, -9, -9, -9, -9, -5, -5, -9, -9, -5, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -5, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, 62, -9, -9, -9, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -9, -9, -9, -1, -9, -9, -9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -9, -9, -9, -9, -9, -9, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -9, -9, -9, -9};
+ private static final byte[] _URL_SAFE_ALPHABET = new byte[]{65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 45, 95};
+ private static final byte[] _URL_SAFE_DECODABET = new byte[]{-9, -9, -9, -9, -9, -9, -9, -9, -9, -5, -5, -9, -9, -5, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -5, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, 62, -9, -9, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -9, -9, -9, -1, -9, -9, -9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -9, -9, -9, -9, 63, -9, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -9, -9, -9, -9};
+ private static final byte[] _ORDERED_ALPHABET = new byte[]{45, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 95, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122};
+ private static final byte[] _ORDERED_DECODABET = new byte[]{-9, -9, -9, -9, -9, -9, -9, -9, -9, -5, -5, -9, -9, -5, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -5, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, 0, -9, -9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -9, -9, -9, -1, -9, -9, -9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -9, -9, -9, -9, 37, -9, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, -9, -9, -9, -9};
+
+ protected static byte[] getAlphabet(int options) {
+ if ((options & 16) == 16) {
+ return _URL_SAFE_ALPHABET;
+ } else {
+ return (options & 32) == 32 ? _ORDERED_ALPHABET : _STANDARD_ALPHABET;
+ }
+ }
+
+ protected static byte[] getDecodabet(int options) {
+ if ((options & 16) == 16) {
+ return _URL_SAFE_DECODABET;
+ } else {
+ return (options & 32) == 32 ? _ORDERED_DECODABET : _STANDARD_DECODABET;
+ }
+ }
+
+ private Base64() {
+ }
+
+ private static void usage(String msg) {
+ System.err.println(msg);
+ System.err.println("Usage: java Base64 -e|-d inputfile outputfile");
+ }
+
+ protected static byte[] encode3to4(byte[] b4, byte[] threeBytes, int numSigBytes, int options) {
+ encode3to4(threeBytes, 0, numSigBytes, b4, 0, options);
+ return b4;
+ }
+
+ protected static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, int options) {
+ byte[] ALPHABET = getAlphabet(options);
+ int inBuff = (numSigBytes > 0 ? source[srcOffset] << 24 >>> 8 : 0) | (numSigBytes > 1 ? source[srcOffset + 1] << 24 >>> 16 : 0) | (numSigBytes > 2 ? source[srcOffset + 2] << 24 >>> 24 : 0);
+ switch(numSigBytes) {
+ case 1:
+ destination[destOffset] = ALPHABET[inBuff >>> 18];
+ destination[destOffset + 1] = ALPHABET[inBuff >>> 12 & 63];
+ destination[destOffset + 2] = 61;
+ destination[destOffset + 3] = 61;
+ return destination;
+ case 2:
+ destination[destOffset] = ALPHABET[inBuff >>> 18];
+ destination[destOffset + 1] = ALPHABET[inBuff >>> 12 & 63];
+ destination[destOffset + 2] = ALPHABET[inBuff >>> 6 & 63];
+ destination[destOffset + 3] = 61;
+ return destination;
+ case 3:
+ destination[destOffset] = ALPHABET[inBuff >>> 18];
+ destination[destOffset + 1] = ALPHABET[inBuff >>> 12 & 63];
+ destination[destOffset + 2] = ALPHABET[inBuff >>> 6 & 63];
+ destination[destOffset + 3] = ALPHABET[inBuff & 63];
+ return destination;
+ default:
+ return destination;
+ }
+ }
+
+ public static String encodeObject(Serializable serializableObject) {
+ return encodeObject(serializableObject, 0);
+ }
+
+ public static String encodeObject(Serializable serializableObject, int options) {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ OutputStream b64os = null;
+ ObjectOutputStream oos = null;
+
+ String var6;
+ try {
+ b64os = new Base64.Base64OutputStream(baos, 1 | options);
+ oos = (options & 2) == 2 ? new ObjectOutputStream(new GZIPOutputStream(b64os)) : new ObjectOutputStream(b64os);
+ oos.writeObject(serializableObject);
+ String var5 = new String(baos.toByteArray(), "UTF-8");
+ return var5;
+ } catch (UnsupportedEncodingException var28) {
+ var6 = new String(baos.toByteArray());
+ return var6;
+ } catch (IOException var29) {
+ LOG.error("error encoding object", var29);
+ var6 = null;
+ } finally {
+ if (oos != null) {
+ try {
+ oos.close();
+ } catch (Exception var27) {
+ LOG.error("error closing ObjectOutputStream", var27);
+ }
+ }
+
+ if (b64os != null) {
+ try {
+ b64os.close();
+ } catch (Exception var26) {
+ LOG.error("error closing Base64OutputStream", var26);
+ }
+ }
+
+ try {
+ baos.close();
+ } catch (Exception var25) {
+ LOG.error("error closing ByteArrayOutputStream", var25);
+ }
+
+ }
+
+ return var6;
+ }
+
+ public static String encodeBytes(byte[] source) {
+ return encodeBytes(source, 0, source.length, 0);
+ }
+
+ public static String encodeBytes(byte[] source, int options) {
+ return encodeBytes(source, 0, source.length, options);
+ }
+
+ public static String encodeBytes(byte[] source, int off, int len) {
+ return encodeBytes(source, off, len, 0);
+ }
+
+ public static String encodeBytes(byte[] source, int off, int len, int options) {
+ if ((options & 2) == 2) {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ GZIPOutputStream gzos = null;
+
+ String var33;
+ try {
+ gzos = new GZIPOutputStream(new Base64.Base64OutputStream(baos, 1 | options));
+ gzos.write(source, off, len);
+ gzos.close();
+ gzos = null;
+ String var32 = new String(baos.toByteArray(), "UTF-8");
+ return var32;
+ } catch (UnsupportedEncodingException var27) {
+ var33 = new String(baos.toByteArray());
+ } catch (IOException var28) {
+ LOG.error("error encoding byte array", var28);
+ var33 = null;
+ return var33;
+ } finally {
+ if (gzos != null) {
+ try {
+ gzos.close();
+ } catch (Exception var25) {
+ LOG.error("error closing GZIPOutputStream", var25);
+ }
+ }
+
+ try {
+ baos.close();
+ } catch (Exception var24) {
+ LOG.error("error closing ByteArrayOutputStream", var24);
+ }
+
+ }
+
+ return var33;
+ } else {
+ boolean breakLines = (options & 8) == 0;
+ int len43 = len * 4 / 3;
+ byte[] outBuff = new byte[len43 + (len % 3 > 0 ? 4 : 0) + (breakLines ? len43 / 76 : 0)];
+ int d = 0;
+ int e = 0;
+ int len2 = len - 2;
+
+ for(int lineLength = 0; d < len2; e += 4) {
+ encode3to4(source, d + off, 3, outBuff, e, options);
+ lineLength += 4;
+ if (breakLines && lineLength == 76) {
+ outBuff[e + 4] = 10;
+ ++e;
+ lineLength = 0;
+ }
+
+ d += 3;
+ }
+
+ if (d < len) {
+ encode3to4(source, d + off, len - d, outBuff, e, options);
+ e += 4;
+ }
+
+ try {
+ return new String(outBuff, 0, e, "UTF-8");
+ } catch (UnsupportedEncodingException var26) {
+ return new String(outBuff, 0, e);
+ }
+ }
+ }
+
+ protected static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset, int options) {
+ byte[] DECODABET = getDecodabet(options);
+ int outBuff;
+ if (source[srcOffset + 2] == 61) {
+ outBuff = (DECODABET[source[srcOffset]] & 255) << 18 | (DECODABET[source[srcOffset + 1]] & 255) << 12;
+ destination[destOffset] = (byte)(outBuff >>> 16);
+ return 1;
+ } else if (source[srcOffset + 3] == 61) {
+ outBuff = (DECODABET[source[srcOffset]] & 255) << 18 | (DECODABET[source[srcOffset + 1]] & 255) << 12 | (DECODABET[source[srcOffset + 2]] & 255) << 6;
+ destination[destOffset] = (byte)(outBuff >>> 16);
+ destination[destOffset + 1] = (byte)(outBuff >>> 8);
+ return 2;
+ } else {
+ try {
+ outBuff = (DECODABET[source[srcOffset]] & 255) << 18 | (DECODABET[source[srcOffset + 1]] & 255) << 12 | (DECODABET[source[srcOffset + 2]] & 255) << 6 | DECODABET[source[srcOffset + 3]] & 255;
+ destination[destOffset] = (byte)(outBuff >> 16);
+ destination[destOffset + 1] = (byte)(outBuff >> 8);
+ destination[destOffset + 2] = (byte)outBuff;
+ return 3;
+ } catch (Exception var7) {
+ LOG.error("error decoding bytes at " + source[srcOffset] + ": " + DECODABET[source[srcOffset]] + ", " + source[srcOffset + 1] + ": " + DECODABET[source[srcOffset + 1]] + ", " + source[srcOffset + 2] + ": " + DECODABET[source[srcOffset + 2]] + ", " + source[srcOffset + 3] + ": " + DECODABET[source[srcOffset + 3]], var7);
+ return -1;
+ }
+ }
+ }
+
+ public static byte[] decode(byte[] source, int off, int len, int options) {
+ byte[] DECODABET = getDecodabet(options);
+ int len34 = len * 3 / 4;
+ byte[] outBuff = new byte[len34];
+ int outBuffPosn = 0;
+ byte[] b4 = new byte[4];
+ int b4Posn = 0;
+
+ for(int i = off; i < off + len; ++i) {
+ byte sbiCrop = (byte)(source[i] & 127);
+ byte sbiDecode = DECODABET[sbiCrop];
+ if (sbiDecode < -5) {
+ LOG.error("Bad Base64 input character at " + i + ": " + source[i] + "(decimal)");
+ return null;
+ }
+
+ if (sbiDecode >= -1) {
+ b4[b4Posn++] = sbiCrop;
+ if (b4Posn > 3) {
+ outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, options);
+ b4Posn = 0;
+ if (sbiCrop == 61) {
+ break;
+ }
+ }
+ }
+ }
+
+ byte[] out = new byte[outBuffPosn];
+ System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
+ return out;
+ }
+
+ public static byte[] decode(String s) {
+ return decode(s, 0);
+ }
+
+ public static byte[] decode(String s, int options) {
+ byte[] bytes;
+ try {
+ bytes = s.getBytes("UTF-8");
+ } catch (UnsupportedEncodingException var21) {
+ bytes = s.getBytes();
+ }
+
+ bytes = decode(bytes, 0, bytes.length, options);
+ if (bytes != null && bytes.length >= 4) {
+ int head = bytes[0] & 255 | bytes[1] << 8 & '\uff00';
+ if (35615 == head) {
+ GZIPInputStream gzis = null;
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+ try {
+ gzis = new GZIPInputStream(new ByteArrayInputStream(bytes));
+ byte[] buffer = new byte[2048];
+
+ int length;
+ while((length = gzis.read(buffer)) >= 0) {
+ baos.write(buffer, 0, length);
+ }
+
+ bytes = baos.toByteArray();
+ } catch (IOException var22) {
+ ;
+ } finally {
+ try {
+ baos.close();
+ } catch (Exception var20) {
+ LOG.error("error closing ByteArrayOutputStream", var20);
+ }
+
+ if (gzis != null) {
+ try {
+ gzis.close();
+ } catch (Exception var19) {
+ LOG.error("error closing GZIPInputStream", var19);
+ }
+ }
+
+ }
+ }
+ }
+
+ return bytes;
+ }
+
+ public static class Base64OutputStream extends FilterOutputStream {
+ private boolean encode;
+ private int position;
+ private byte[] buffer;
+ private int bufferLength;
+ private int lineLength;
+ private boolean breakLines;
+ private byte[] b4;
+ private boolean suspendEncoding;
+ private int options;
+ private byte[] decodabet;
+
+ public Base64OutputStream(OutputStream out) {
+ this(out, 1);
+ }
+
+ public Base64OutputStream(OutputStream out, int options) {
+ super(out);
+ this.breakLines = (options & 8) != 8;
+ this.encode = (options & 1) == 1;
+ this.bufferLength = this.encode ? 3 : 4;
+ this.buffer = new byte[this.bufferLength];
+ this.position = 0;
+ this.lineLength = 0;
+ this.suspendEncoding = false;
+ this.b4 = new byte[4];
+ this.options = options;
+ this.decodabet = Base64.getDecodabet(options);
+ }
+
+ public void write(int theByte) throws IOException {
+ if (this.suspendEncoding) {
+ super.out.write(theByte);
+ } else {
+ if (this.encode) {
+ this.buffer[this.position++] = (byte)theByte;
+ if (this.position >= this.bufferLength) {
+ this.out.write(Base64.encode3to4(this.b4, this.buffer, this.bufferLength, this.options));
+ this.lineLength += 4;
+ if (this.breakLines && this.lineLength >= 76) {
+ this.out.write(10);
+ this.lineLength = 0;
+ }
+
+ this.position = 0;
+ }
+ } else if (this.decodabet[theByte & 127] > -5) {
+ this.buffer[this.position++] = (byte)theByte;
+ if (this.position >= this.bufferLength) {
+ int len = Base64.decode4to3(this.buffer, 0, this.b4, 0, this.options);
+ this.out.write(this.b4, 0, len);
+ this.position = 0;
+ }
+ } else if (this.decodabet[theByte & 127] != -5) {
+ throw new IOException("Invalid character in Base64 data.");
+ }
+
+ }
+ }
+
+ public void write(byte[] theBytes, int off, int len) throws IOException {
+ if (this.suspendEncoding) {
+ super.out.write(theBytes, off, len);
+ } else {
+ for(int i = 0; i < len; ++i) {
+ this.write(theBytes[off + i]);
+ }
+
+ }
+ }
+
+ public void flushBase64() throws IOException {
+ if (this.position > 0) {
+ if (!this.encode) {
+ throw new IOException("Base64 input not properly padded.");
+ }
+
+ this.out.write(Base64.encode3to4(this.b4, this.buffer, this.position, this.options));
+ this.position = 0;
+ }
+
+ }
+
+ public void close() throws IOException {
+ this.flushBase64();
+ super.close();
+ this.buffer = null;
+ this.out = null;
+ }
+
+ public void suspendEncoding() throws IOException {
+ this.flushBase64();
+ this.suspendEncoding = true;
+ }
+
+ public void resumeEncoding() {
+ this.suspendEncoding = false;
+ }
+ }
+
+}
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java b/web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java
index 9cb3b334b228..d93333fcaf22 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java
@@ -9,7 +9,6 @@
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.common.server.bo.SpanBo;
import com.navercorp.pinpoint.web.TestTraceUtils;
-import org.apache.hadoop.hbase.util.Base64;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
diff --git a/web/src/test/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilterTest.java b/web/src/test/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilterTest.java
index 25bcd1b9eb33..d33148b17f74 100644
--- a/web/src/test/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilterTest.java
+++ b/web/src/test/java/com/navercorp/pinpoint/web/filter/RpcURLPatternFilterTest.java
@@ -26,7 +26,6 @@
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.common.trace.ServiceTypeFactory;
import com.navercorp.pinpoint.common.trace.ServiceTypeProperty;
-import org.apache.hadoop.hbase.util.Base64;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
| train | test | "2019-03-11T07:11:50" | "2019-03-05T05:59:12Z" | jicai | test |
pinpoint-apm/pinpoint/5445_5447 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/5445 | pinpoint-apm/pinpoint/5447 | [
"keyword_pr_to_issue"
] | 23f5c145bffac8a53c2769801a1d19ff8b1eb364 | 4ce5976eec1a2e72176a8e41f3ad39e719bcf3a4 | [] | [] | "2019-04-02T05:28:43Z" | [
"bug",
"module:web"
] | Running container agents may be missing in Inspector View agent list when queried for less than 5 minutes | #### What version of pinpoint are you using?
master
#### Describe the bug
Some agents with `pinpoint.container` option are missing from the agent list in Inspector View even if they are alive. This is because the agent list currently filters out any agents that do not have any events (such as ping, or connected) in between the search period.
So if the agent has sent pings in time 1 and time 6, and the search period is set from time 2 to time 5, the agent will be filtered out even if it is currently running.
#### What did you do to trigger the bug?
Steps to reproduce, for example:
1. Ran an agent with`-Dpinpoint.container` option.
2. Query for the agent in Inspector View, with search period set to not include any events from the agent. (ie in between agent pings)
#### Expected behavior
Running agents with `pinpoint.container` option should be displayed in the agent list, and not be filtered out even if there were no events from the agent during the search period.
| [
"web/src/main/java/com/navercorp/pinpoint/web/controller/AgentInfoController.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/controller/AgentInfoController.java"
] | [] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/controller/AgentInfoController.java b/web/src/main/java/com/navercorp/pinpoint/web/controller/AgentInfoController.java
index 56ae264db941..907ad3d59575 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/controller/AgentInfoController.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/controller/AgentInfoController.java
@@ -94,13 +94,20 @@ public ApplicationAgentsList getAgentList(
@RequestParam("from") long from,
@RequestParam("to") long to) {
ApplicationAgentsList.Filter containerFilter = agentInfo -> {
- if (agentInfo.isContainer()) {
- AgentStatus agentStatus = agentInfo.getStatus();
- if (agentStatus == null || agentStatus.getEventTimestamp() < from) {
- return ApplicationAgentsList.Filter.REJECT;
- }
+ if (!agentInfo.isContainer()) {
+ return ApplicationAgentsList.Filter.ACCEPT;
}
- return ApplicationAgentsList.Filter.ACCEPT;
+ AgentStatus agentStatus = agentInfo.getStatus();
+ if (agentStatus == null) {
+ return ApplicationAgentsList.Filter.REJECT;
+ }
+ if (agentStatus.getState() == AgentLifeCycleState.RUNNING) {
+ return ApplicationAgentsList.Filter.ACCEPT;
+ }
+ if (agentStatus.getEventTimestamp() >= from) {
+ return ApplicationAgentsList.Filter.ACCEPT;
+ }
+ return ApplicationAgentsList.Filter.REJECT;
};
long timestamp = to;
return this.agentInfoService.getApplicationAgentsList(ApplicationAgentsList.GroupBy.HOST_NAME, containerFilter, applicationName, timestamp);
@@ -113,13 +120,17 @@ public ApplicationAgentsList getAgentList(
@RequestParam("application") String applicationName,
@RequestParam("timestamp") long timestamp) {
ApplicationAgentsList.Filter runningContainerFilter = agentInfo -> {
- if (agentInfo.isContainer()) {
- AgentStatus agentStatus = agentInfo.getStatus();
- if (agentStatus == null || agentStatus.getState() != AgentLifeCycleState.RUNNING) {
- return ApplicationAgentsList.Filter.REJECT;
- }
+ if (!agentInfo.isContainer()) {
+ return ApplicationAgentsList.Filter.ACCEPT;
+ }
+ AgentStatus agentStatus = agentInfo.getStatus();
+ if (agentStatus == null) {
+ return ApplicationAgentsList.Filter.REJECT;
+ }
+ if (agentStatus.getState() == AgentLifeCycleState.RUNNING) {
+ return ApplicationAgentsList.Filter.ACCEPT;
}
- return ApplicationAgentsList.Filter.ACCEPT;
+ return ApplicationAgentsList.Filter.REJECT;
};
return this.agentInfoService.getApplicationAgentsList(ApplicationAgentsList.GroupBy.HOST_NAME, runningContainerFilter, applicationName, timestamp);
}
| null | test | test | "2019-04-02T07:17:44" | "2019-04-02T04:56:04Z" | Xylus | test |
pinpoint-apm/pinpoint/5523_5524 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/5523 | pinpoint-apm/pinpoint/5524 | [
"keyword_pr_to_issue"
] | f5876b638ffaf615ffcb57cf4fe95f8ea607f02a | b4f696f2748c39815b15ea938818ea3ca2d4c2b7 | [] | [] | "2019-04-25T06:27:10Z" | [
"bug",
"module:agent"
] | Agent cannot send traces over TCP to the collector | #### What version of pinpoint are you using?
1.8.1, 1.8.2, 1.8.3
#### Describe the bug
Agent cannot send traces over to the collector when using TCP to send spans.
The default UDP works fine.
#### What did you do to trigger the bug?
Steps to reproduce, for example:
1. Configure collector and agent to send spans over TCP.
2. Trigger a trace.
#### Expected behavior
Spans should be sent successfully.
| [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/SpanDataSenderProvider.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/StatDataSenderProvider.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java"
] | [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/SpanDataSenderProvider.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/StatDataSenderProvider.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java"
] | [] | diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/SpanDataSenderProvider.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/SpanDataSenderProvider.java
index d487bfdcfb05..4e2f0e435a90 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/SpanDataSenderProvider.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/SpanDataSenderProvider.java
@@ -24,7 +24,9 @@
import com.navercorp.pinpoint.profiler.context.module.SpanStatClientFactory;
import com.navercorp.pinpoint.profiler.context.thrift.MessageConverter;
import com.navercorp.pinpoint.profiler.sender.DataSender;
+import com.navercorp.pinpoint.profiler.sender.MessageSerializer;
import com.navercorp.pinpoint.profiler.sender.TcpDataSender;
+import com.navercorp.pinpoint.profiler.sender.ThriftMessageSerializer;
import com.navercorp.pinpoint.profiler.sender.UdpDataSenderFactory;
import com.navercorp.pinpoint.rpc.client.PinpointClientFactory;
import org.apache.thrift.TBase;
@@ -75,7 +77,8 @@ public DataSender get() {
}
PinpointClientFactory pinpointClientFactory = clientFactoryProvider.get();
- return new TcpDataSender("SpanDataSender", ip, port, pinpointClientFactory);
+ MessageSerializer<byte[]> messageSerializer = new ThriftMessageSerializer(messageConverter);
+ return new TcpDataSender("SpanDataSender", ip, port, pinpointClientFactory, messageSerializer);
} else {
UdpDataSenderFactory factory = new UdpDataSenderFactory(ip, port, UDP_EXECUTOR_NAME, writeQueueSize, timeout, sendBufferSize, messageConverter);
return factory.create(ioType);
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/StatDataSenderProvider.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/StatDataSenderProvider.java
index aab1c5993830..9df3301f1dbd 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/StatDataSenderProvider.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/StatDataSenderProvider.java
@@ -24,7 +24,9 @@
import com.navercorp.pinpoint.profiler.context.thrift.BypassMessageConverter;
import com.navercorp.pinpoint.profiler.context.thrift.MessageConverter;
import com.navercorp.pinpoint.profiler.sender.DataSender;
+import com.navercorp.pinpoint.profiler.sender.MessageSerializer;
import com.navercorp.pinpoint.profiler.sender.TcpDataSender;
+import com.navercorp.pinpoint.profiler.sender.ThriftMessageSerializer;
import com.navercorp.pinpoint.profiler.sender.UdpDataSenderFactory;
import com.navercorp.pinpoint.rpc.client.PinpointClientFactory;
import org.apache.thrift.TBase;
@@ -77,7 +79,8 @@ public DataSender get() {
}
PinpointClientFactory pinpointClientFactory = clientFactoryProvider.get();
- return new TcpDataSender("StatDataSender", ip, port, pinpointClientFactory);
+ MessageSerializer<byte[]> messageSerializer = new ThriftMessageSerializer(messageConverter);
+ return new TcpDataSender("StatDataSender", ip, port, pinpointClientFactory, messageSerializer);
} else {
UdpDataSenderFactory factory = new UdpDataSenderFactory(ip, port, UDP_EXECUTOR_NAME, writeQueueSize, timeout, sendBufferSize, messageConverter);
return factory.create(ioType);
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java
index 78d7549f0fdf..94c0986ce780 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java
@@ -194,24 +194,20 @@ public void stop() {
protected void sendPacket(Object message) {
try {
- if (message instanceof TBase<?, ?>) {
- final byte[] copy = messageSerializer.serializer(message);
- if (copy == null) {
- return;
- }
- doSend(copy);
- return;
- }
-
if (message instanceof RequestMessage<?>) {
final RequestMessage<?> requestMessage = (RequestMessage<?>) message;
if (doRequest(requestMessage)) {
return;
}
- } else {
+ }
+
+ final byte[] copy = messageSerializer.serializer(message);
+ if (copy == null) {
logger.error("sendPacket fail. invalid dto type:{}", message.getClass());
return;
}
+ doSend(copy);
+
} catch (Exception e) {
logger.warn("tcp send fail. Caused:{}", e.getMessage(), e);
}
| null | test | test | "2019-04-04T07:40:33" | "2019-04-25T06:18:50Z" | Xylus | test |
pinpoint-apm/pinpoint/5878_5885 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/5878 | pinpoint-apm/pinpoint/5885 | [
"keyword_issue_to_pr"
] | 88dc111fdcd87257e1cb86f2c602358be082e471 | 443a9ddb73d97e29941e13b275138f3e3418567b | [
"hi @gwagdalf \r\n\r\nI make plugins, but sometimes I am not expert, so I might miss out on what real users need. \r\n\r\nI checked your offer. \r\nI think it's a very good solution. \r\n\r\nBased on the following method. Could you make code and send me pull request. \r\nhttps://github.com/spring-projects/spring-kafka/blob/master/spring-kafka/src/main/java/org/springframework/kafka/listener/adapter/RetryingMessageListenerAdapter.java#L108\r\n\r\nI look forward to hearing from you.\r\n\r\nthanks. \r\n",
"This issue resolved via #5885 \r\n"
] | [] | "2019-08-17T00:41:00Z" | [] | Suggest adding RetryingMessageListenerAdapter to KafkaPlugin | **Which module is your feature request related to?**
pinpoint-kafka-plugin
KafkaPlugin.class
**Is your feature request related to a problem?**
I'm using spring-cloud-starter-stream-kafka.
It is set as maxAttempts 3 by default and in this case, it was confirmed to use **RetryingMessageListenerAdapter** as shown below.
![RetryingMessageListenerAdapter](https://user-images.githubusercontent.com/34761230/63135907-9ac02380-c00a-11e9-8952-9cc9e2c780f0.gif)
call stack
`
onMessage:110, RetryingMessageListenerAdapter (org.springframework.kafka.listener.adapter)
onMessage:40, RetryingMessageListenerAdapter (org.springframework.kafka.listener.adapter)
doInvokeOnMessage:1220, KafkaMessageListenerContainer$ListenerConsumer (org.springframework.kafka.listener)
invokeOnMessage:1213, KafkaMessageListenerContainer$ListenerConsumer (org.springframework.kafka.listener)
doInvokeRecordListener:1174, KafkaMessageListenerContainer$ListenerConsumer (org.springframework.kafka.listener)
doInvokeWithRecords:1155, KafkaMessageListenerContainer$ListenerConsumer (org.springframework.kafka.listener)
invokeRecordListener:1096, KafkaMessageListenerContainer$ListenerConsumer (org.springframework.kafka.listener)
invokeListener:924, KafkaMessageListenerContainer$ListenerConsumer (org.springframework.kafka.listener)
pollAndInvoke:740, KafkaMessageListenerContainer$ListenerConsumer (org.springframework.kafka.listener)
run:689, KafkaMessageListenerContainer$ListenerConsumer (org.springframework.kafka.listener)
call:511, Executors$RunnableAdapter (java.util.concurrent)
run:266, FutureTask (java.util.concurrent)
run:748, Thread (java.lang)
`
maxAttempts default setting
`spring.cloud.stream.bindings.<channelName>.consumer.maxAttempts: default 3`
https://docs.spring.io/spring-cloud-https://github.com/naver/pinpoint/blob/master/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/KafkaPlugin.java#L72
if set entrypoint like below, it works
`profiler.kafka.consumer.entryPoint = org.springframework.kafka.listener.adapter.RetryingMessageListenerAdapter`
Just add a few lines. It seems to be more convenient to use.
**Describe the solution you'd like**
https://github.com/naver/pinpoint/blob/master/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/KafkaPlugin.java#L72
In the above line, adding one line as shown below is expected to work because it implements the onMessage method of the same AcknowledgingConsumerAwareMessageListener interface.
`transformTemplate.transform("org.springframework.kafka.listener.adapter.RetryingMessageListenerAdapterTransform", RecordMessagingMessageListenerAdapterTransform.class);`
You can rename RecordMessagingMessageListenerAdapterTransform-> AcknowledgingConsumerAwareMessageListenerTransform to use it in common, or you can create a RetryingMessageListenerAdapterTransform.class separately
**Additional context**
In addition, there are instructions to leave entryPoint empty when using spring-kafka as shown below. I experienced some failures.
> Setting when using spring-kafka (In this case, you can leave profiler.kafka.consumer.entryPoint option to empty.)
> profiler.springkafka.consumer.enable=true
https://github.com/naver/pinpoint/blob/master/plugins/kafka/README.md
I think it change like below
BatchMessagingMessageListenerAdapter, RecordMessagingMessageListenerAdapter are the default implementations,
If you use RetryingMessageListenerAdapter, FilteringMessageListenerAdapter, FilteringBatchMessageListenerAdapter, etc., it is better to set it at the entrypoint.
| [
"plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/KafkaPlugin.java"
] | [
"plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/KafkaPlugin.java"
] | [] | diff --git a/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/KafkaPlugin.java b/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/KafkaPlugin.java
index aaff75dc805c..4f224e82662a 100644
--- a/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/KafkaPlugin.java
+++ b/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/KafkaPlugin.java
@@ -45,7 +45,9 @@
import static com.navercorp.pinpoint.common.util.VarArgs.va;
-
+/**
+ * @author Harris Gwag (gwagdalf)
+ */
public class KafkaPlugin implements ProfilerPlugin, TransformTemplateAware {
private final PLogger logger = PLoggerFactory.getLogger(this.getClass());
@@ -68,10 +70,11 @@ public void setup(ProfilerPluginSetupContext context) {
transformTemplate.transform("org.apache.kafka.clients.consumer.ConsumerRecord", ConsumerRecordTransform.class);
if (config.isSpringConsumerEnable()) {
- transformTemplate.transform("org.springframework.kafka.listener.adapter.RecordMessagingMessageListenerAdapterTransform", RecordMessagingMessageListenerAdapterTransform.class);
-
+ transformTemplate.transform("org.springframework.kafka.listener.adapter.RecordMessagingMessageListenerAdapter", AcknowledgingConsumerAwareMessageListenerTransform.class);
transformTemplate.transform("org.springframework.kafka.listener.adapter.BatchMessagingMessageListenerAdapter", BatchMessagingMessageListenerAdapterTransform.class);
+ // Spring Cloud Starter Stream Kafka 2.2.x is supported
+ transformTemplate.transform("org.springframework.kafka.listener.adapter.RetryingMessageListenerAdapter", AcknowledgingConsumerAwareMessageListenerTransform.class);
}
if (StringUtils.hasText(config.getKafkaEntryPoint())) {
@@ -168,7 +171,7 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader,
}
- public static class RecordMessagingMessageListenerAdapterTransform implements TransformCallback {
+ public static class AcknowledgingConsumerAwareMessageListenerTransform implements TransformCallback {
@Override
public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
| null | train | test | "2019-08-16T11:43:55" | "2019-08-16T00:52:47Z" | gwagdalf | test |
pinpoint-apm/pinpoint/6048_6079 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/6048 | pinpoint-apm/pinpoint/6079 | [
"keyword_pr_to_issue"
] | af464b1c16814362c9de533d41749433ad81104c | b4f2d6b4bb125f9bcde66b4f0e11fa09b9ecd453 | [
"Ok, let me look at this problem and solve it",
"attaching log, which may help you better\r\n```\r\nError Message\r\njava.lang.AssertionError: Cannot find apiId of [org.frameworkset.elasticsearch.client.ConfigRestClientUtil.createIndiceMapping(java.lang.String, java.lang.String)]\r\nStacktrace\r\ncom.navercorp.pinpoint.test.plugin.PinpointPluginTestException: java.lang.AssertionError: Cannot find apiId of [org.frameworkset.elasticsearch.client.ConfigRestClientUtil.createIndiceMapping(java.lang.String, java.lang.String)]\r\n\tat com.navercorp.pinpoint.plugin.elasticsearchbboss.ElasticsearchExecutorIT.indiceCreate(ElasticsearchExecutorIT.java:116)\r\n\tat com.navercorp.pinpoint.plugin.elasticsearchbboss.ElasticsearchExecutorIT.testClientInterface(ElasticsearchExecutorIT.java:101)\r\n```",
"Hi,@RoySRose :\r\nThis problem is caused by not enabling ElasticsearchBboss plugin, can enable the plugin in pinpoint.config:\r\nprofiler.elasticsearchbboss.enabled=true"
] | [] | "2019-10-11T09:05:02Z" | [
"bug",
"module:plugin"
] | elasticsearch bboss test failure | Hello, @yin-bp
I've noticed that bboss plugin integration tests are failing in our daily routine test.
Do you mind checking `ElasticsearchExecutorIT.java` out?
| [
"agent/src/main/resources-local/pinpoint.config",
"agent/src/main/resources-release/pinpoint-real-env-lowoverhead-sample.config",
"agent/src/main/resources-release/pinpoint.config"
] | [
"agent/src/main/resources-local/pinpoint.config",
"agent/src/main/resources-release/pinpoint-real-env-lowoverhead-sample.config",
"agent/src/main/resources-release/pinpoint.config"
] | [
"agent-it8/src/test/java/com/navercorp/pinpoint/plugin/elasticsearchbboss/ElasticsearchExecutorIT.java",
"agent-it8/src/test/java/com/navercorp/pinpoint/plugin/elasticsearchbboss/ElasticsearchExecutorIT569.java"
] | diff --git a/agent/src/main/resources-local/pinpoint.config b/agent/src/main/resources-local/pinpoint.config
index cd2275f432d6..349b83c6b89d 100644
--- a/agent/src/main/resources-local/pinpoint.config
+++ b/agent/src/main/resources-local/pinpoint.config
@@ -1071,7 +1071,7 @@ profiler.elasticsearch.recordESVersion=false
###########################################################
# ElasticsearchBBoss
###########################################################
-profiler.elasticsearchbboss.enabled=false
+profiler.elasticsearchbboss.enabled=true
profiler.elasticsearchbboss.recordResult=false
profiler.elasticsearchbboss.recordArgs=true
profiler.elasticsearchbboss.recordDsl=true
diff --git a/agent/src/main/resources-release/pinpoint-real-env-lowoverhead-sample.config b/agent/src/main/resources-release/pinpoint-real-env-lowoverhead-sample.config
index 941f9cb99073..c842a062f0f4 100644
--- a/agent/src/main/resources-release/pinpoint-real-env-lowoverhead-sample.config
+++ b/agent/src/main/resources-release/pinpoint-real-env-lowoverhead-sample.config
@@ -793,7 +793,7 @@ profiler.elasticsearch.recordESVersion=false
###########################################################
# ElasticsearchBBoss
###########################################################
-profiler.elasticsearchbboss.enabled=false
+profiler.elasticsearchbboss.enabled=true
profiler.elasticsearchbboss.recordResult=false
profiler.elasticsearchbboss.recordArgs=true
profiler.elasticsearchbboss.recordDsl=true
diff --git a/agent/src/main/resources-release/pinpoint.config b/agent/src/main/resources-release/pinpoint.config
index d77e52b072a7..ab3ab1d53f72 100644
--- a/agent/src/main/resources-release/pinpoint.config
+++ b/agent/src/main/resources-release/pinpoint.config
@@ -985,7 +985,7 @@ profiler.elasticsearch.recordESVersion=false
###########################################################
# ElasticsearchBBoss
###########################################################
-profiler.elasticsearchbboss.enabled=false
+profiler.elasticsearchbboss.enabled=true
profiler.elasticsearchbboss.recordResult=false
profiler.elasticsearchbboss.recordArgs=true
profiler.elasticsearchbboss.recordDsl=true
| diff --git a/agent-it8/src/test/java/com/navercorp/pinpoint/plugin/elasticsearchbboss/ElasticsearchExecutorIT.java b/agent-it8/src/test/java/com/navercorp/pinpoint/plugin/elasticsearchbboss/ElasticsearchExecutorIT.java
index f536a6027303..d164ba8a294d 100644
--- a/agent-it8/src/test/java/com/navercorp/pinpoint/plugin/elasticsearchbboss/ElasticsearchExecutorIT.java
+++ b/agent-it8/src/test/java/com/navercorp/pinpoint/plugin/elasticsearchbboss/ElasticsearchExecutorIT.java
@@ -17,19 +17,12 @@
import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifierHolder;
-import com.navercorp.pinpoint.plugin.AgentPath;
-import com.navercorp.pinpoint.test.plugin.Dependency;
-import com.navercorp.pinpoint.test.plugin.JvmVersion;
-import com.navercorp.pinpoint.test.plugin.PinpointAgent;
-import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
import org.frameworkset.elasticsearch.ElasticSearchHelper;
import org.frameworkset.elasticsearch.client.ClientInterface;
import org.frameworkset.elasticsearch.entity.ESDatas;
import org.junit.AfterClass;
-import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.junit.runner.RunWith;
import pl.allegro.tech.embeddedelasticsearch.EmbeddedElastic;
import pl.allegro.tech.embeddedelasticsearch.PopularProperties;
@@ -47,12 +40,8 @@
* @author yinbp[yin-bp@163.com]
*/
-@RunWith(PinpointPluginTestSuite.class)
-@PinpointAgent(AgentPath.PATH)
-@Dependency({"com.bbossgroups.plugins:bboss-elasticsearch-rest-jdbc:[5.6.9,]",
- "pl.allegro.tech:embedded-elasticsearch:2.8.0"})
-@JvmVersion(8)
-public class ElasticsearchExecutorIT {
+
+public abstract class ElasticsearchExecutorIT {
private static EmbeddedElastic embeddedElastic;
private static ClientInterface clientInterface;
private static ClientInterface configRestClientInterface ;
@@ -64,13 +53,13 @@ public static void setUpBeforeClass() throws Exception {
// BBoss connect elasticsearch use localhost and http port 9200 default.
-// Here is a bboss web demo base spring boot and elasticsearch 5.x,6.x:
+// Here is a bboss web demo base spring boot and elasticsearch 5.x,6.x,7.x,8.x:
// https://github.com/bbossgroups/es_bboss_web
//
// Here is a quickstart tutorial:
// https://esdoc.bbossgroups.com/#/quickstart
embeddedElastic = EmbeddedElastic.builder()
- .withElasticVersion( "5.0.0")
+ .withElasticVersion( "6.8.0")
.withSetting(PopularProperties.HTTP_PORT, 9200)
.withEsJavaOpts("-Xms128m -Xmx512m")
.withStartTimeout(2, MINUTES)
@@ -95,54 +84,65 @@ public static void tearDownAfterClass() {
if(embeddedElastic != null)
embeddedElastic.stop();
}
+
+
@Test
- public void testClientInterface() throws Exception {
+ public void indiceCreate( ) throws Exception {
PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
- indiceCreate(verifier);
- indiceExist( verifier);
- add2ndGetDocument(verifier);
- bulkDocuments(verifier);
- searchDocuments(verifier);
- updateAndDeleteDocument(verifier);
- }
- public void indiceCreate(PluginTestVerifier verifier) throws Exception {
- boolean existIndice = configRestClientInterface.existIndice("cars");
- Method createIndiceMappingMethod = configRestClientInterface.getClass().getDeclaredMethod("createIndiceMapping",String.class,String.class);
-
- if(!existIndice){
- // Create cars indice with car indexType by bboss
- // Get indice mappings and settings with dsl name "createCarIndice" from configfile elasticsearchbboss/car-mapping.xml
- configRestClientInterface.createIndiceMapping("cars","createCarIndice");
- verifier.verifyTrace(event(serviceType, createIndiceMappingMethod));
+ Class configClass = Class.forName("org.frameworkset.elasticsearch.client.ConfigRestClientUtil");
+ Method createIndiceMappingMethod = configClass.getMethod("createIndiceMapping",String.class,String.class);
+ try {
+ configRestClientInterface.createIndiceMapping("cars", "createCarIndice");
+
}
- else{
- //drop and create indice
+ catch (Exception e){
+
+ };
+ verifier.verifyTrace(event(serviceType, createIndiceMappingMethod));
+
+
+
+ }
+
+ @Test
+ public void indiceDrop( ) throws Exception {
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ Class configClass = Class.forName("org.frameworkset.elasticsearch.client.ConfigRestClientUtil");
+ Method dropIndiceMethod = configClass.getMethod("dropIndice",String.class);
+ try {
configRestClientInterface.dropIndice("cars");
- configRestClientInterface.createIndiceMapping("cars","createCarIndice");
- Method dropIndiceMethod = configRestClientInterface.getClass().getDeclaredMethod("dropIndice",String.class);
- verifier.verifyTrace(event(serviceType, dropIndiceMethod));
- verifier.verifyTrace(event(serviceType, createIndiceMappingMethod));
+ }
+ catch (Exception e){
+
}
+ verifier.verifyTrace(event(serviceType, dropIndiceMethod));
+
+
+
}
- public void indiceExist(PluginTestVerifier verifier) throws Exception{
+ @Test
+ public void indiceExist( ) throws Exception{
//Validate the indice twitter exist or not
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
- boolean existIndice = clientInterface.existIndice("twitter");
-
- //TODO just a sample
- Assert.assertEquals(existIndice,false);
//Validate the indice cars exist or not
- existIndice = clientInterface.existIndice("cars");
- Assert.assertEquals(existIndice,true);
- Method existIndiceMethod = clientInterface.getClass().getDeclaredMethod("existIndice",String.class);
+ boolean existIndice = clientInterface.existIndice("cars");
+
+// Assert.assertEquals(existIndice,true);
+ Class restClientUtilClass = Class.forName("org.frameworkset.elasticsearch.client.RestClientUtil");
+ Method existIndiceMethod = restClientUtilClass.getMethod("existIndice",String.class);
verifier.verifyTrace(event(serviceType, existIndiceMethod));
}
-
- public void add2ndGetDocument(PluginTestVerifier verifier) throws Exception{
+ @Test
+ public void addDocument( ) throws Exception{
+ Class restClientUtilClass = Class.forName("org.frameworkset.elasticsearch.client.RestClientUtil");
+ Method addDocumentMethod = restClientUtilClass.getDeclaredMethod("addDocument",String.class,String.class,
+ Object.class,String.class);
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
Car car = new Car();
//set carid as the index documentid
car.setCarId("1");
@@ -152,21 +152,38 @@ public void add2ndGetDocument(PluginTestVerifier verifier) throws Exception{
//add data to cars/car indice. Use force refresh when test case,but product mode does not use forcerefresh
// and should use:
- // clientInterface.addDocument("cars","car",car).
- clientInterface.addDocument("cars","car",car,"refresh=true");
- //get car by document id "1"
- car = clientInterface.getDocument("cars","car","1",Car.class);
- Assert.assertNotNull(car);
- Assert.assertEquals("1",car.getCarId());
- Method addDocumentMethod = clientInterface.getClass().getDeclaredMethod("addDocument",String.class,
- String.class,Object.class,String.class);
+ // clientInterface.addDocument("cars",car).
+ try {
+ clientInterface.addDocument("cars", "car",car, "refresh=true");
+ }
+ catch (Exception e){
+
+ }
+
verifier.verifyTrace(event(serviceType, addDocumentMethod));
- Method getDocumentMethod = clientInterface.getClass().getDeclaredMethod("getDocument",String.class,
- String.class,String.class,Class.class);
+
+ }
+ @Test
+ public void getDocument( ) throws Exception{
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ //get car by document id "1"
+ try {
+ Car car = clientInterface.getDocument("cars","1",Car.class);
+ }
+ catch (Exception e){
+
+ }
+
+
+ Class restClientUtilClass = Class.forName("org.frameworkset.elasticsearch.client.RestClientUtil");
+ Method getDocumentMethod = restClientUtilClass.getDeclaredMethod("getDocument",String.class,
+ String.class,Class.class);
verifier.verifyTrace(event(serviceType, getDocumentMethod));
}
- public void bulkDocuments(PluginTestVerifier verifier)throws Exception{
+ @Test
+ public void bulkDocuments( )throws Exception{
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
List<Car> cars = new ArrayList<Car>();
Car car = new Car();
//set carid as the index documentid
@@ -184,40 +201,51 @@ public void bulkDocuments(PluginTestVerifier verifier)throws Exception{
cars.add(car);
//add datas to cars/car indice.Use force refresh when test case,but product mode does not use forcerefresh
// and should use:
- // clientInterface.addDocuments("cars","car",cars);
- clientInterface.addDocuments("cars","car",cars,"refresh=true");
- //get car by document id "2"
- car = clientInterface.getDocument("cars","car","2",Car.class);
- Assert.assertNotNull(car);
- Assert.assertEquals("2",car.getCarId());
- Method addDocumentsMethod = clientInterface.getClass().getDeclaredMethod("addDocuments",String.class,
- String.class,List.class,String.class);
+ // clientInterface.addDocuments("cars",cars);
+
+ try {
+ clientInterface.addDocuments("cars","car",cars,"refresh=true");
+ }
+ catch (Exception e){
+
+ }
+ Class restClientUtilClass = Class.forName("org.frameworkset.elasticsearch.client.RestClientUtil");
+ Method addDocumentsMethod = restClientUtilClass.getDeclaredMethod("addDocuments",String.class,String.class,
+ List.class,String.class);
verifier.verifyTrace(event(serviceType, addDocumentsMethod));
- Method getDocumentMethod = clientInterface.getClass().getDeclaredMethod("getDocument",String.class,
- String.class,String.class,Class.class);
- verifier.verifyTrace(event(serviceType, getDocumentMethod));
+
}
- public void searchDocuments(PluginTestVerifier verifier)throws Exception{
- Map<String,Object> condition = new HashMap<>();
- //set description as search condition
- condition.put("description","passat");
+ @Test
+ public void searchDocuments()throws Exception{
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
+ try {
+ Map<String,Object> condition = new HashMap<>();
+ //set description as search condition
+ condition.put("description","passat");
- //search data to cars/car indice that match condition with a simple query dsl named testSearch defined in elasticsearchbboss/car-mapping.xml.
- ESDatas<Car> carESDatas = configRestClientInterface.searchList("cars/_search","testSearch",condition,Car.class);
- //datas that match condition
- List<Car> cars = carESDatas.getDatas();
- //totalsize that match condition
- long totalSize = carESDatas.getTotalSize();
- Assert.assertTrue(totalSize > 0);
- Method searchListMethod = configRestClientInterface.getClass().getDeclaredMethod("searchList",String.class,
+ //search data to cars/car indice that match condition with a simple query dsl named testSearch defined in elasticsearchbboss/car-mapping.xml.
+ ESDatas<Car> carESDatas = configRestClientInterface.searchList("cars/_search","testSearch",condition,Car.class);
+ //datas that match condition
+ List<Car> cars = carESDatas.getDatas();
+ //totalsize that match condition
+ long totalSize = carESDatas.getTotalSize();
+ }
+ catch (Exception e){
+
+ }
+
+ Class configClass = Class.forName("org.frameworkset.elasticsearch.client.ConfigRestClientUtil");
+ Method searchListMethod = configClass.getDeclaredMethod("searchList",String.class,
String.class,Map.class,Class.class);
verifier.verifyTrace(event(serviceType, searchListMethod));
}
- public void updateAndDeleteDocument(PluginTestVerifier verifier)throws Exception{
+ @Test
+ public void updateDocument( )throws Exception{
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
Car car = new Car();
//set carid as the index documentid
car.setCarId("1");
@@ -228,28 +256,40 @@ public void updateAndDeleteDocument(PluginTestVerifier verifier)throws Exception
// Update data on cars/car indice that document id is 1.
// Use force refresh when test case,but product mode does not use forcerefresh
// and should use:
- // clientInterface.updateDocument("cars","car","1",car);
- clientInterface.updateDocument("cars","car","1",car,"refresh=true");
- // Get modified car
- car = clientInterface.getDocument("cars","car","1",Car.class);
- Assert.assertEquals("1.0T",car.getModel());
+ // clientInterface.updateDocument("cars","1",car);
+
+ try {
+ clientInterface.updateDocument("cars","car","1",car,"refresh=true");
+ }
+ catch (Exception e){
+
+ }
+ Class restClientUtilClass = Class.forName("org.frameworkset.elasticsearch.client.RestClientUtil");
+ Method updateDocumentMethod = restClientUtilClass.getDeclaredMethod("updateDocument",String.class,String.class,
+ Object.class,Object.class,String.class);
+ verifier.verifyTrace(event(serviceType, updateDocumentMethod));
+
+ }
+
+ @Test
+ public void deleteDocument( )throws Exception{
+ PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
// Delete data on cars/car indice that document id is 1.
// Use force refresh when test case,but product mode does not use forcerefresh
// and should use:
- // clientInterface.deleteDocument("cars","car","1");
- clientInterface.deleteDocument("cars","car","1","refresh=true");
- // Get delete car. will get a null object.
- car = clientInterface.getDocument("cars","car","1",Car.class);
- Assert.assertNull(car);
- Method updateDocumentMethod = clientInterface.getClass().getDeclaredMethod("updateDocument",String.class,
- String.class,Object.class,Object.class,String.class);
- verifier.verifyTrace(event(serviceType, updateDocumentMethod));
- Method getDocumentMethod = clientInterface.getClass().getDeclaredMethod("getDocument",String.class,
- String.class,String.class,Class.class);
- verifier.verifyTrace(event(serviceType, getDocumentMethod));
- Method deleteDocumentMethod = clientInterface.getClass().getDeclaredMethod("deleteDocument",String.class,
- String.class,String.class,String.class);
- verifier.verifyTrace(event(serviceType, deleteDocumentMethod));
+ // clientInterface.deleteDocument("cars","1");
+
+ try {
+ clientInterface.deleteDocument("cars","car","1","refresh=true");
+ }
+ catch (Exception e){
+
+ }
+ Class restClientUtilClass = Class.forName("org.frameworkset.elasticsearch.client.RestClientUtil");
+ Method deleteDocument = restClientUtilClass.getDeclaredMethod("deleteDocument",String.class,String.class,
+ String.class,String.class);
+ verifier.verifyTrace(event(serviceType, deleteDocument));
+
}
}
diff --git a/agent-it8/src/test/java/com/navercorp/pinpoint/plugin/elasticsearchbboss/ElasticsearchExecutorIT569.java b/agent-it8/src/test/java/com/navercorp/pinpoint/plugin/elasticsearchbboss/ElasticsearchExecutorIT569.java
new file mode 100644
index 000000000000..b20dc97e374e
--- /dev/null
+++ b/agent-it8/src/test/java/com/navercorp/pinpoint/plugin/elasticsearchbboss/ElasticsearchExecutorIT569.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2018 NAVER Corp.
+ * 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.
+ */
+package com.navercorp.pinpoint.plugin.elasticsearchbboss;
+
+
+import com.navercorp.pinpoint.plugin.AgentPath;
+import com.navercorp.pinpoint.test.plugin.Dependency;
+import com.navercorp.pinpoint.test.plugin.JvmVersion;
+import com.navercorp.pinpoint.test.plugin.PinpointAgent;
+import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
+import org.junit.runner.RunWith;
+
+
+/**
+ * @author yinbp[yin-bp@163.com]
+ */
+
+@RunWith(PinpointPluginTestSuite.class)
+@PinpointAgent(AgentPath.PATH)
+@Dependency({"com.bbossgroups.plugins:bboss-elasticsearch-rest-jdbc:[5.6.9,5.8.3)",
+ "pl.allegro.tech:embedded-elasticsearch:2.8.0"})
+@JvmVersion(8)
+public class ElasticsearchExecutorIT569 extends ElasticsearchExecutorIT{
+
+
+}
| train | test | "2019-10-11T10:40:51" | "2019-10-02T05:16:49Z" | RoySRose | test |
pinpoint-apm/pinpoint/6148_6149 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/6148 | pinpoint-apm/pinpoint/6149 | [
"keyword_issue_to_pr"
] | ddbb2cac267acea54dc506bb9b229e75647907ba | f946e3305e7be91154dc5878528b29ec9183f9d6 | [
"resolved via #6149 #6154 "
] | [] | "2019-11-07T02:11:26Z" | [
"bug",
"module:plugin"
] | Fixes a problem where Kafka Plugin doesn't work in certain situations | Fixes a problem where Kafka Plugin doesn't work in certain situations
#### description
If Sampling is not set to 1, Kafka Plugin may not handle traces properly, which may cause problems. | [
"plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ConsumerRecordEntryPointInterceptor.java"
] | [
"plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ConsumerRecordEntryPointInterceptor.java"
] | [] | diff --git a/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ConsumerRecordEntryPointInterceptor.java b/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ConsumerRecordEntryPointInterceptor.java
index 0c8604f14bd6..b0ca62488086 100644
--- a/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ConsumerRecordEntryPointInterceptor.java
+++ b/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ConsumerRecordEntryPointInterceptor.java
@@ -148,7 +148,7 @@ Trace createTrace0(TraceContext traceContext, ConsumerRecord consumerRecord) {
if (isDebug) {
logger.debug("TraceID not exist. camSampled is false. skip trace.");
}
- return null;
+ return trace;
}
}
| null | train | test | "2019-11-06T03:06:27" | "2019-11-07T02:09:52Z" | koo-taejin | test |
pinpoint-apm/pinpoint/6148_6154 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/6148 | pinpoint-apm/pinpoint/6154 | [
"keyword_issue_to_pr"
] | a2f4df5610a10e8164983bfa2934a367ded786ec | ead87bcd571f7b1766e248dfb31de869d84c9b56 | [
"resolved via #6149 #6154 "
] | [] | "2019-11-07T09:12:06Z" | [
"bug",
"module:plugin"
] | Fixes a problem where Kafka Plugin doesn't work in certain situations | Fixes a problem where Kafka Plugin doesn't work in certain situations
#### description
If Sampling is not set to 1, Kafka Plugin may not handle traces properly, which may cause problems. | [
"plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ConsumerRecordEntryPointInterceptor.java"
] | [
"plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ConsumerRecordEntryPointInterceptor.java"
] | [] | diff --git a/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ConsumerRecordEntryPointInterceptor.java b/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ConsumerRecordEntryPointInterceptor.java
index 0c8604f14bd6..b0ca62488086 100644
--- a/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ConsumerRecordEntryPointInterceptor.java
+++ b/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ConsumerRecordEntryPointInterceptor.java
@@ -148,7 +148,7 @@ Trace createTrace0(TraceContext traceContext, ConsumerRecord consumerRecord) {
if (isDebug) {
logger.debug("TraceID not exist. camSampled is false. skip trace.");
}
- return null;
+ return trace;
}
}
| null | val | test | "2019-10-14T09:23:11" | "2019-11-07T02:09:52Z" | koo-taejin | test |
pinpoint-apm/pinpoint/6150_6155 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/6150 | pinpoint-apm/pinpoint/6155 | [
"keyword_issue_to_pr"
] | ead87bcd571f7b1766e248dfb31de869d84c9b56 | 29a0a994ae515e25d322dce16b5721ee443feb91 | [
"resolved via #6151 #6155 "
] | [] | "2019-11-07T09:50:55Z" | [
"enhancement",
"module:plugin"
] | Adds support Kafka 2.2.0+ | #### description
There are major method changes in version 2.2.0.
* KafkaCosumer poll method
```
# 2.0.0+
org.apache.kafka.clients.consumer.KafkaConsumer#poll(long, boolean)
->
# 2.2.0+
org.apache.kafka.clients.consumer.KafkaConsumer#poll(org.apache.kafka.common.utils.Timer, boolean)
```
* KafkaProducer constructor
```
org.apache.kafka.clients.producer.KafkaProducer#KafkaProducer(org.apache.kafka.clients.producer.ProducerConfig, org.apache.kafka.common.serialization.Serializer<K>, org.apache.kafka.common.serialization.Serializer<V>, org.apache.kafka.clients.Metadata, org.apache.kafka.clients.KafkaClient)
->
# 2.2.0+
org.apache.kafka.clients.producer.KafkaProducer#KafkaProducer(java.util.Map<java.lang.String,java.lang.Object>, org.apache.kafka.common.serialization.Serializer<K>, org.apache.kafka.common.serialization.Serializer<V>, org.apache.kafka.clients.Metadata, org.apache.kafka.clients.KafkaClient, org.apache.kafka.clients.producer.internals.ProducerInterceptors, org.apache.kafka.common.utils.Time)
``` | [
"plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/KafkaPlugin.java",
"plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ProducerConstructorInterceptor.java"
] | [
"plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/KafkaPlugin.java",
"plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ProducerConstructorInterceptor.java"
] | [] | diff --git a/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/KafkaPlugin.java b/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/KafkaPlugin.java
index d1c527d52792..dc5cb7e9cbac 100644
--- a/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/KafkaPlugin.java
+++ b/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/KafkaPlugin.java
@@ -55,8 +55,11 @@ public void setup(ProfilerPluginSetupContext context) {
public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
final InstrumentClass target = instrumentor.getInstrumentClass(classLoader, className, classfileBuffer);
- InstrumentMethod constructor = target.getConstructor("org.apache.kafka.clients.producer.ProducerConfig",
- "org.apache.kafka.common.serialization.Serializer", "org.apache.kafka.common.serialization.Serializer");
+ // Version 2.2.0+ is supported.
+ InstrumentMethod constructor = target.getConstructor("java.util.Map",
+ "org.apache.kafka.common.serialization.Serializer", "org.apache.kafka.common.serialization.Serializer",
+ "org.apache.kafka.clients.Metadata", "org.apache.kafka.clients.KafkaClient",
+ "org.apache.kafka.clients.producer.internals.ProducerInterceptors", "org.apache.kafka.common.utils.Time");
// Version 2.0.0+ is supported.
if (constructor == null) {
@@ -64,6 +67,12 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader,
"org.apache.kafka.common.serialization.Serializer", "org.apache.kafka.common.serialization.Serializer",
"org.apache.kafka.clients.Metadata", "org.apache.kafka.clients.KafkaClient");
}
+
+ if (constructor == null) {
+ constructor = target.getConstructor("org.apache.kafka.clients.producer.ProducerConfig",
+ "org.apache.kafka.common.serialization.Serializer", "org.apache.kafka.common.serialization.Serializer");
+ }
+
constructor.addInterceptor(KafkaConstants.PRODUCER_CONSTRUCTOR_INTERCEPTOR);
InstrumentMethod sendMethod = target.getDeclaredMethod("send", "org.apache.kafka.clients.producer.ProducerRecord", "org.apache.kafka.clients.producer.Callback");
@@ -88,12 +97,19 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader,
"org.apache.kafka.common.serialization.Deserializer", "org.apache.kafka.common.serialization.Deserializer");
constructor.addInterceptor(KafkaConstants.CONSUMER_CONSTRUCTOR_INTERCEPTOR);
+ // Version 2.2.0+ is supported.
+ InstrumentMethod pollMethod = target.getDeclaredMethod("poll", "org.apache.kafka.common.utils.Timer", "boolean");
+
// Version 2.0.0+ is supported.
- InstrumentMethod pollMethod = target.getDeclaredMethod("poll", "long", "boolean");
+ if (pollMethod == null) {
+ pollMethod = target.getDeclaredMethod("poll", "long", "boolean");
+ }
+ // Version 2.0.0-
if (pollMethod == null) {
pollMethod = target.getDeclaredMethod("poll", "long");
}
+
pollMethod.addInterceptor(KafkaConstants.CONSUMER_POLL_INTERCEPTOR);
target.addField(KafkaConstants.REMOTE_ADDRESS_ACCESSOR);
diff --git a/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ProducerConstructorInterceptor.java b/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ProducerConstructorInterceptor.java
index ffb7b18cab12..2d1cca62cc04 100644
--- a/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ProducerConstructorInterceptor.java
+++ b/plugins/kafka/src/main/java/com/navercorp/pinpoint/plugin/kafka/interceptor/ProducerConstructorInterceptor.java
@@ -23,15 +23,19 @@
import com.navercorp.pinpoint.common.util.CollectionUtils;
import com.navercorp.pinpoint.plugin.kafka.KafkaConstants;
import com.navercorp.pinpoint.plugin.kafka.field.accessor.RemoteAddressFieldAccessor;
+
import org.apache.kafka.clients.producer.ProducerConfig;
import java.util.List;
+import java.util.Map;
/**
* @author Taejin Koo
*/
public class ProducerConstructorInterceptor implements AroundInterceptor {
+ private static final String KEY_BOOTSTRAP_SERVERS = "bootstrap.servers";
+
private final PLogger logger = PLoggerFactory.getLogger(this.getClass());
private final boolean isDebug = logger.isDebugEnabled();
@@ -57,12 +61,21 @@ public void after(Object target, Object[] args, Object result, Throwable throwab
}
ProducerConfig producerConfig = getProducerConfig(args);
- if (producerConfig == null) {
+ if (producerConfig != null) {
+ String remoteAddress = getRemoteAddress(producerConfig);
+ ((RemoteAddressFieldAccessor) target)._$PINPOINT$_setRemoteAddress(remoteAddress);
+ return;
+ }
+
+ // Version 2.2.0+ is supported.
+ Map map = getMap(args);
+ if (map != null) {
+ Object remoteAddressObject = map.get(KEY_BOOTSTRAP_SERVERS);
+ String remoteAddress = getRemoteAddress0(remoteAddressObject);
+ ((RemoteAddressFieldAccessor) target)._$PINPOINT$_setRemoteAddress(remoteAddress);
return;
}
- String remoteAddress = getRemoteAddress(producerConfig);
- ((RemoteAddressFieldAccessor) target)._$PINPOINT$_setRemoteAddress(remoteAddress);
}
private ProducerConfig getProducerConfig(Object args[]) {
@@ -71,20 +84,43 @@ private ProducerConfig getProducerConfig(Object args[]) {
}
if (args[0] instanceof ProducerConfig) {
- return (ProducerConfig)args[0];
+ return (ProducerConfig) args[0];
+ }
+
+ return null;
+ }
+
+ private Map getMap(Object args[]) {
+ if (ArrayUtils.isEmpty(args)) {
+ return null;
+ }
+
+ if (args[0] instanceof Map) {
+ return (Map) args[0];
}
return null;
}
private String getRemoteAddress(ProducerConfig producerConfig) {
- List<String> serverList = producerConfig.getList("bootstrap.servers");
+ List<String> serverList = producerConfig.getList(KEY_BOOTSTRAP_SERVERS);
+ return getRemoteAddress0(serverList);
+ }
+
+ private String getRemoteAddress0(Object remoteAddressObject) {
String remoteAddress = KafkaConstants.UNKNOWN;
- if (CollectionUtils.nullSafeSize(serverList) == 1) {
- remoteAddress = serverList.get(0);
- } else if (CollectionUtils.nullSafeSize(serverList) > 1) {
- remoteAddress = serverList.toString();
+ if (remoteAddressObject instanceof List) {
+ List remoteAddressList = (List) remoteAddressObject;
+ if (CollectionUtils.nullSafeSize(remoteAddressList) == 1) {
+ remoteAddress = String.valueOf(remoteAddressList.get(0));
+ } else if (CollectionUtils.nullSafeSize(remoteAddressList) > 1) {
+ remoteAddress = remoteAddressList.toString();
+ }
+ return remoteAddress;
+ } else if (remoteAddressObject instanceof String) {
+ return (String) remoteAddressObject;
}
+
return remoteAddress;
}
| null | train | test | "2019-11-07T10:39:37" | "2019-11-07T07:21:47Z" | koo-taejin | test |
pinpoint-apm/pinpoint/6152_6158 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/6152 | pinpoint-apm/pinpoint/6158 | [
"keyword_issue_to_pr"
] | 29a0a994ae515e25d322dce16b5721ee443feb91 | 9ace68f76243a524558bc3da0d00846baa5d9f15 | [
"resolved via #6153 #6158 "
] | [] | "2019-11-08T02:08:12Z" | [
"bug",
"module:agent"
] | Allows to set queueSize in the TcpDataSender | #### description
Allows to set queueSize on the TcpDataSender.
related issue #6144
| [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/SpanDataSenderProvider.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/StatDataSenderProvider.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java"
] | [
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/SpanDataSenderProvider.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/StatDataSenderProvider.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java"
] | [] | diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/SpanDataSenderProvider.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/SpanDataSenderProvider.java
index e83689d3ef00..002e8f471731 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/SpanDataSenderProvider.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/SpanDataSenderProvider.java
@@ -78,7 +78,7 @@ public DataSender get() {
PinpointClientFactory pinpointClientFactory = clientFactoryProvider.get();
MessageSerializer<byte[]> messageSerializer = new ThriftMessageSerializer(messageConverter);
- return new TcpDataSender("SpanDataSender", ip, port, pinpointClientFactory, messageSerializer);
+ return new TcpDataSender("SpanDataSender", ip, port, pinpointClientFactory, messageSerializer, writeQueueSize);
} else {
UdpDataSenderFactory factory = new UdpDataSenderFactory(ip, port, UDP_EXECUTOR_NAME, writeQueueSize, timeout, sendBufferSize, messageConverter);
return factory.create(ioType);
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/StatDataSenderProvider.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/StatDataSenderProvider.java
index 8b740c87abd7..95f44ff49569 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/StatDataSenderProvider.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/StatDataSenderProvider.java
@@ -80,7 +80,7 @@ public DataSender get() {
PinpointClientFactory pinpointClientFactory = clientFactoryProvider.get();
MessageSerializer<byte[]> messageSerializer = new ThriftMessageSerializer(messageConverter);
- return new TcpDataSender("StatDataSender", ip, port, pinpointClientFactory, messageSerializer);
+ return new TcpDataSender("StatDataSender", ip, port, pinpointClientFactory, messageSerializer, writeQueueSize);
} else {
UdpDataSenderFactory factory = new UdpDataSenderFactory(ip, port, UDP_EXECUTOR_NAME, writeQueueSize, timeout, sendBufferSize, messageConverter);
return factory.create(ioType);
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java
index 94c0986ce780..b0e02dc5b45f 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/TcpDataSender.java
@@ -53,6 +53,8 @@
*/
public class TcpDataSender implements EnhancedDataSender<Object> {
+ private static final int DEFAULT_QUEUE_SIZE = 1024 * 5;
+
private final Logger logger;
static {
@@ -75,7 +77,7 @@ public class TcpDataSender implements EnhancedDataSender<Object> {
public TcpDataSender(String name, String host, int port, PinpointClientFactory clientFactory) {
- this(name, ClientFactoryUtils.newPinpointClientProvider(host, port, clientFactory), newDefaultMessageSerializer());
+ this(name, ClientFactoryUtils.newPinpointClientProvider(host, port, clientFactory), newDefaultMessageSerializer(), DEFAULT_QUEUE_SIZE);
}
private static ThriftMessageSerializer newDefaultMessageSerializer() {
@@ -84,21 +86,27 @@ private static ThriftMessageSerializer newDefaultMessageSerializer() {
}
public TcpDataSender(String name, String host, int port, PinpointClientFactory clientFactory, MessageSerializer<byte[]> messageSerializer) {
- this(name, ClientFactoryUtils.newPinpointClientProvider(host, port, clientFactory), messageSerializer);
+ this(name, ClientFactoryUtils.newPinpointClientProvider(host, port, clientFactory), messageSerializer, DEFAULT_QUEUE_SIZE);
+ }
+
+ public TcpDataSender(String name, String host, int port, PinpointClientFactory clientFactory, MessageSerializer<byte[]> messageSerializer, int queueSize) {
+ this(name, ClientFactoryUtils.newPinpointClientProvider(host, port, clientFactory), messageSerializer, queueSize);
}
- private TcpDataSender(String name, ClientFactoryUtils.PinpointClientProvider clientProvider, MessageSerializer<byte[]> messageSerializer) {
+ private TcpDataSender(String name, ClientFactoryUtils.PinpointClientProvider clientProvider, MessageSerializer<byte[]> messageSerializer, int queueSize) {
this.logger = newLogger(name);
- Assert.requireNonNull(clientProvider, "clientProvider must not be null");
+ Assert.requireNonNull(clientProvider, "clientProvider");
this.client = clientProvider.get();
- this.messageSerializer = Assert.requireNonNull(messageSerializer, "messageSerializer must not be null");
+ Assert.isTrue(queueSize > 0, "queueSize must be 'queueSize > 0'");
+
+ this.messageSerializer = Assert.requireNonNull(messageSerializer, "messageSerializer");
this.timer = createTimer(name);
this.writeFailFutureListener = new WriteFailFutureListener(logger, "io write fail.", "host", -1);
final String executorName = getExecutorName(name);
- this.executor = createAsyncQueueingExecutor(1024 * 5, executorName);
+ this.executor = createAsyncQueueingExecutor(queueSize, executorName);
}
private AsyncQueueingExecutor<Object> createAsyncQueueingExecutor(int queueSize, String executorName) {
| null | train | test | "2019-11-08T02:32:16" | "2019-11-07T08:17:48Z" | koo-taejin | test |
pinpoint-apm/pinpoint/6507_6510 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/6507 | pinpoint-apm/pinpoint/6510 | [
"keyword_issue_to_pr"
] | 511872a4553f23ebd93ee7aa1bc824a253087284 | 3276a81109c697f64221af4e4777e80e55f20022 | [
"This issue expect to have resolved via #6508, #6510"
] | [] | "2020-02-18T02:44:16Z" | [
"bug",
"module:plugin"
] | Fix problem that do not set some fields when an exception occurs | #### related module
Kafka-Plugin
#### description
If service type has record statistics, destnationId value have to send for to draw servermap.
But, current ProducerSendInterceptor code do not set destinationId field when exception occurred while send() method invoked.
For this reason, servermap has not drawn when when exception occurred while send() method invoked.
| [
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ChannelBasicPublishInterceptor.java"
] | [
"plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ChannelBasicPublishInterceptor.java"
] | [] | diff --git a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ChannelBasicPublishInterceptor.java b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ChannelBasicPublishInterceptor.java
index 78961d8b9fa1..0618de2e382c 100644
--- a/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ChannelBasicPublishInterceptor.java
+++ b/plugins/rabbitmq/src/main/java/com/navercorp/pinpoint/plugin/rabbitmq/client/interceptor/ChannelBasicPublishInterceptor.java
@@ -103,27 +103,27 @@ public void after(Object target, Object[] args, Object result, Throwable throwab
SpanEventRecorder recorder = trace.currentSpanEventRecorder();
recorder.recordApi(descriptor);
- if (throwable == null) {
- String endPoint = RabbitMQClientConstants.UNKNOWN;
- // Producer's endPoint should be the socket address of where the producer is actually connected to.
- final Connection connection = ((Channel) target).getConnection();
- if (connection instanceof AMQConnection) {
- AMQConnection amqConnection = (AMQConnection) connection;
- FrameHandler frameHandler = amqConnection.getFrameHandler();
- if (frameHandler instanceof RemoteAddressAccessor) {
- endPoint = ((RemoteAddressAccessor) frameHandler)._$PINPOINT$_getRemoteAddress();
- }
+
+ String endPoint = RabbitMQClientConstants.UNKNOWN;
+ // Producer's endPoint should be the socket address of where the producer is actually connected to.
+ final Connection connection = ((Channel) target).getConnection();
+ if (connection instanceof AMQConnection) {
+ AMQConnection amqConnection = (AMQConnection) connection;
+ FrameHandler frameHandler = amqConnection.getFrameHandler();
+ if (frameHandler instanceof RemoteAddressAccessor) {
+ endPoint = ((RemoteAddressAccessor) frameHandler)._$PINPOINT$_getRemoteAddress();
}
- recorder.recordEndPoint(endPoint);
- // DestinationId is used to render the virtual queue node.
- // We choose the exchange name as the logical name of the queue node.
- recorder.recordDestinationId("exchange-" + exchange);
-
- recorder.recordAttribute(RabbitMQClientConstants.RABBITMQ_EXCHANGE_ANNOTATION_KEY, exchange);
- recorder.recordAttribute(RabbitMQClientConstants.RABBITMQ_ROUTINGKEY_ANNOTATION_KEY, routingKey);
- } else {
- recorder.recordException(throwable);
}
+ recorder.recordEndPoint(endPoint);
+ // DestinationId is used to render the virtual queue node.
+ // We choose the exchange name as the logical name of the queue node.
+ recorder.recordDestinationId("exchange-" + exchange);
+
+ recorder.recordAttribute(RabbitMQClientConstants.RABBITMQ_EXCHANGE_ANNOTATION_KEY, exchange);
+ recorder.recordAttribute(RabbitMQClientConstants.RABBITMQ_ROUTINGKEY_ANNOTATION_KEY, routingKey);
+
+ recorder.recordException(throwable);
+
} finally {
trace.traceBlockEnd();
}
@@ -136,13 +136,13 @@ private boolean validate(Object target, Object[] args) {
if (args == null || args.length < 6) {
return false;
}
- if (args[0] !=null && !(args[0] instanceof String)) {
+ if (args[0] != null && !(args[0] instanceof String)) {
return false;
}
- if (args[1] !=null && !(args[1] instanceof String)) {
+ if (args[1] != null && !(args[1] instanceof String)) {
return false;
}
- if (args[4] !=null && !(args[4] instanceof AMQP.BasicProperties)) {
+ if (args[4] != null && !(args[4] instanceof AMQP.BasicProperties)) {
return false;
}
return true;
| null | train | test | "2020-02-18T03:41:14" | "2020-02-17T08:32:50Z" | koo-taejin | test |
pinpoint-apm/pinpoint/7527_7528 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/7527 | pinpoint-apm/pinpoint/7528 | [
"keyword_pr_to_issue",
"connected"
] | 4bb8ea6eb71a50edca7477b5d6c3dc48a174616f | 418503ec9a74fac2f57c45a68a2cafdb4d635937 | [
"I will post a PR to fix it.",
"@emeroad Do you think this is a bug?",
"@tankilo \r\nThanks for your contribution.\r\n\r\nI fully agree with your opinion.\r\nI really like this PR. :+1: ",
"Thank you for your contribution"
] | [] | "2021-01-03T02:18:59Z" | [
"bug",
"module:plugin",
"module:agent"
] | HttpClient4 plugin's BasicFutureMethodInterceptor failed to record exception detatils when intercepting method `org.apache.http.concurrent.BasicFuture#failed` | #### contribution info
* Contributor : @tankilo
#### Prerequisites
Please check the [FAQ](http://pinpoint-apm.github.io/pinpoint/faq.html), and search existing [issues](https://github.com/pinpoint-apm/pinpoint/issues) for similar questions before creating a new issue.**YOU MAY DELETE THIS PREREQUISITES SECTION.**
- [x] I have checked the [FAQ](http://pinpoint-apm.github.io/pinpoint/faq.html), and [issues](https://github.com/pinpoint-apm/pinpoint/issues) and found no answer.
#### What version of pinpoint are you using?
master
#### Describe the bug
HttpClient4 plugin's BasicFutureMethodInterceptor failed to record exception detatils when intercepting method `org.apache.http.concurrent.BasicFuture#failed`
![image](https://user-images.githubusercontent.com/10413284/103470276-b36ddc80-4dab-11eb-96a9-ce5e16ce0fb0.png)
#### What did you do to trigger the bug?
Run the demo code with pinpoint agent.
Of course ,i didn't run any server on endpoint `http://127.0.0.1:9200`.
```
public class TestHttpClient {
public static void main(String[] args){
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(50000)
.setSocketTimeout(50000)
.setConnectionRequestTimeout(1000)
.build();
IOReactorConfig ioReactorConfig = IOReactorConfig.custom().
setIoThreadCount(Runtime.getRuntime().availableProcessors())
.setSoKeepAlive(true)
.build();
ConnectingIOReactor ioReactor=null;
try {
ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
} catch (IOReactorException e) {
e.printStackTrace();
}
PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor);
connManager.setMaxTotal(100);
connManager.setDefaultMaxPerRoute(100);
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().
setConnectionManager(connManager)
.setDefaultRequestConfig(requestConfig)
.build();
String url = "http://127.0.0.1:9200/_bulk";
HttpPost httpPost = new HttpPost(url);
StringEntity entity = null;
try {
String a = "{ \"index\": { \"_index\": \"test\", \"_type\": \"test\"} }\n" +
"{\"name\": \"上海\",\"age\":33}\n";
entity = new StringEntity(a);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
httpPost.setEntity(entity);
//start
client.start();
//异步请求
client.execute(httpPost, new Back());
while(true){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class Back implements FutureCallback<HttpResponse>{
private long start = System.currentTimeMillis();
Back(){
}
public void completed(HttpResponse httpResponse) {
try {
System.out.println("cost is:"+(System.currentTimeMillis()-start)+":"+EntityUtils.toString(httpResponse.getEntity()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void failed(Exception e) {
System.err.println(" cost is:"+(System.currentTimeMillis()-start)+":"+e);
}
public void cancelled() {
}
}
}
```
#### Expected behavior
![image](https://user-images.githubusercontent.com/10413284/103470263-70136e00-4dab-11eb-8ccb-ffde5563c651.png)
Exception details should be recorded
#### Screenshots
If applicable, add screenshots to help explain your problem.
#### Logs
If applicable, please attach agent/collector/web DEBUG log that includes the code execution that led to the bug. In case of agents, including the start-up log may be of great help.
#### Additional context
Add any other context about the problem here, such as affected library for agents, how your collector/web/hbase is set up if applicable.
| [
"plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/HttpClient4Plugin.java",
"plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/BasicFutureMethodInterceptor.java"
] | [
"plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/HttpClient4Plugin.java",
"plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/BasicFutureFailedMethodInterceptor.java",
"plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/BasicFutureMethodInterceptor.java"
] | [] | diff --git a/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/HttpClient4Plugin.java b/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/HttpClient4Plugin.java
index 99a6dddd5f53..28e723a09b67 100644
--- a/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/HttpClient4Plugin.java
+++ b/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/HttpClient4Plugin.java
@@ -30,6 +30,7 @@
import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPlugin;
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPluginSetupContext;
+import com.navercorp.pinpoint.plugin.httpclient4.interceptor.BasicFutureFailedMethodInterceptor;
import com.navercorp.pinpoint.plugin.httpclient4.interceptor.BasicFutureMethodInterceptor;
import com.navercorp.pinpoint.plugin.httpclient4.interceptor.DefaultClientExchangeHandlerImplStartMethodInterceptor;
import com.navercorp.pinpoint.plugin.httpclient4.interceptor.DefaultHttpRequestRetryHandlerRetryRequestMethodInterceptor;
@@ -340,7 +341,7 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
InstrumentMethod failed = target.getDeclaredMethod("failed", "java.lang.Exception");
if (failed != null) {
- failed.addInterceptor(BasicFutureMethodInterceptor.class);
+ failed.addInterceptor(BasicFutureFailedMethodInterceptor.class);
}
diff --git a/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/BasicFutureFailedMethodInterceptor.java b/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/BasicFutureFailedMethodInterceptor.java
new file mode 100644
index 000000000000..6f52de039449
--- /dev/null
+++ b/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/BasicFutureFailedMethodInterceptor.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2014 NAVER Corp.
+ *
+ * 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.
+ */
+
+package com.navercorp.pinpoint.plugin.httpclient4.interceptor;
+
+import com.navercorp.pinpoint.bootstrap.context.AsyncContext;
+import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
+import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
+import com.navercorp.pinpoint.bootstrap.context.TraceContext;
+import com.navercorp.pinpoint.bootstrap.interceptor.AsyncContextSpanEventSimpleAroundInterceptor;
+import com.navercorp.pinpoint.plugin.httpclient4.HttpClient4Constants;
+
+/**
+ *
+ * @author netspider
+ * @author jaehong.kim
+ *
+ */
+public class BasicFutureFailedMethodInterceptor extends AsyncContextSpanEventSimpleAroundInterceptor {
+
+ public BasicFutureFailedMethodInterceptor(TraceContext traceContext, MethodDescriptor methodDescriptor) {
+ super(traceContext, methodDescriptor);
+ }
+
+ @Override
+ protected void doInBeforeTrace(SpanEventRecorder recorder, AsyncContext asyncContext, Object target, Object[] args) {
+ recorder.recordServiceType(HttpClient4Constants.HTTP_CLIENT_4_INTERNAL);
+ }
+
+ @Override
+ protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
+ recorder.recordApi(methodDescriptor);
+ if (throwable!= null) {
+ recorder.recordException(throwable);
+ } else if (args.length == 1 && args[0] instanceof Exception) {
+ recorder.recordException((Exception) args[0]);
+ }
+ }
+}
\ No newline at end of file
diff --git a/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/BasicFutureMethodInterceptor.java b/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/BasicFutureMethodInterceptor.java
index 37f2d361c3e2..4e45dfe0ca83 100644
--- a/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/BasicFutureMethodInterceptor.java
+++ b/plugins/httpclient4/src/main/java/com/navercorp/pinpoint/plugin/httpclient4/interceptor/BasicFutureMethodInterceptor.java
@@ -43,6 +43,10 @@ protected void doInBeforeTrace(SpanEventRecorder recorder, AsyncContext asyncCon
@Override
protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
recorder.recordApi(methodDescriptor);
- recorder.recordException(throwable);
+ if ("failed".equals(methodDescriptor.getMethodName()) && args.length == 1 && args[0] instanceof Exception) {
+ recorder.recordException((Exception) args[0]);
+ } else {
+ recorder.recordException(throwable);
+ }
}
}
\ No newline at end of file
| null | test | test | "2021-05-07T10:36:14" | "2021-01-03T02:09:13Z" | tankilo | test |
pinpoint-apm/pinpoint/7628_7631 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/7628 | pinpoint-apm/pinpoint/7631 | [
"keyword_pr_to_issue"
] | 1bfefa9bbcba69fde998d9ccce0d79a72a0780a8 | b8caf43e8059bd62d0dcff7821277effa3fcfc97 | [
"Yes. It looks like it's a bug. Any suggestions?",
"> Yes. It looks like it's a bug. Any suggestions?\r\n\r\nplease fix it like this: ```profilableClass != null && !profilableClass.isEmpty() ```\r\nI already tested in local env \r\nAlso need I create a pr for this?"
] | [] | "2021-02-08T03:54:09Z" | [
"bug",
"module:agent"
] | I found a bug in DefaultProfilerConfig.java | problem: pinpoint.config's properties ``` profiler.include``` not work
so I review the code ,and find something maybe wrong
#### What version of pinpoint are you using?
master
``` java
//. file: https://github.com/pinpoint-apm/pinpoint/blob/master/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java
// position line 365 to 375
@Value("${profiler.include}")
void setProfilableClassFilter(String profilableClass) {
// TODO have to remove
// profile package included in order to test "call stack view".
// this config must not be used in service environment because the size of profiling information will get heavy.
// We may need to change this configuration to regular expression.
if (profilableClass != null && profilableClass.isEmpty()) {
this.profilableClassFilter = new ProfilableClassFilter(profilableClass);
} else {
this.profilableClassFilter = new SkipFilter<String>();
}
}
```
``` if (profilableClass != null && profilableClass.isEmpty()) { ``` this line
the condition maybe is ```profilableClass != null && !profilableClass.isEmpty() ```, or this will not work forever
thank a lot
| [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java"
] | [
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java"
] | [] | diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java
index 0d70dcd66d74..750969f65436 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/config/DefaultProfilerConfig.java
@@ -368,7 +368,7 @@ void setProfilableClassFilter(String profilableClass) {
// profile package included in order to test "call stack view".
// this config must not be used in service environment because the size of profiling information will get heavy.
// We may need to change this configuration to regular expression.
- if (profilableClass != null && profilableClass.isEmpty()) {
+ if (profilableClass != null && !profilableClass.isEmpty()) {
this.profilableClassFilter = new ProfilableClassFilter(profilableClass);
} else {
this.profilableClassFilter = new SkipFilter<String>();
| null | train | test | "2021-02-08T03:49:39" | "2021-02-06T13:26:37Z" | snaigle | test |
pinpoint-apm/pinpoint/7748_7749 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/7748 | pinpoint-apm/pinpoint/7749 | [
"keyword_pr_to_issue"
] | 9ad18b7a64af84b4c5141feeaadbf5dca404b6db | d0d9d63b7cb1a0f5a427d9f282b26f5bf3c7d939 | [
"Thank you for your contribution."
] | [] | "2021-03-18T11:11:55Z" | [
"bug",
"module:agent"
] | Spring cloud gateway call tree/servermap is incorrect | #### What version of pinpoint are you using?
master/v2.2.2
#### Describe the bug
When the call path is as: _gateway_(optional) -> _appA_ -> _gateway_(spring cloud gateway with netty-http) -> _appB_, the call tree and the servermap would be incorrect. The call tree after gateway is missing.
>
> ----> gateway ----> unknown (appB's host:port)
> user ---> appA __ /
> \
> ----->appB
>
It should be: user ---> appA ---> gateway ---> appB
#### What did you do to trigger the bug?
1. build a gateway by using spring cloud gateway via start.spring.io with dependency Spring Cloud Gateway
2. add a route to _appB_
3. add a java app (_appA_) which pass the request to the _gateway_
All these apps should have pinpoint agent installed.
#### Cause
The pinpoint headers were added by gateway multiple times. The pinpoint headers generated by _appA_ are kept and not replaced by new values generated by the _gateway_.
> T 192.168.1.88:48598 -> 192.168.1.88:16101 [AP] #2737
> GET /user/1000 HTTP/1.1.
> User-Agent: Apache-HttpClient/4.5.6 (Java/1.8.0_xxx).
> Accept-Encoding: gzip,deflate.
> Pinpoint-TraceID: D6569WtHRb2I8kK-41gvEA^1616059917098^10.
> Pinpoint-SpanID: 1929507258409571489.
> Pinpoint-pSpanID: -7870392703037294246.
> Pinpoint-Flags: 0.
> Pinpoint-pAppName: pinpoint-verify.
> Pinpoint-pAppType: 1000.
> Pinpoint-Host: verify.example.com.
> Forwarded: proto=http;host=verify.example.com;for="127.0.0.1:58568".
> X-Forwarded-For: 127.0.0.1.
> X-Forwarded-Proto: http.
> X-Forwarded-Port: 80.
> X-Forwarded-Host: verify.example.com.
> host: 192.168.1.88:16101.
> accept: */*.
> Pinpoint-TraceID: D6569WtHRb2I8kK-41gvEA^1616059917098^10.
> Pinpoint-SpanID: -602080378178433913.
> Pinpoint-pSpanID: 1929507258409571489.
> Pinpoint-Flags: 0.
> Pinpoint-pAppName: gateway-local.
> Pinpoint-pAppType: 1000.
> Pinpoint-Host: 192.168.1.88:16101.
#### Expected behavior
The call tree and server map for the transaction should be correct.
| [
"plugins/reactor-netty/src/main/java/com/navercorp/pinpoint/plugin/reactor/netty/interceptor/HttpClientRequestHeaderAdaptor.java"
] | [
"plugins/reactor-netty/src/main/java/com/navercorp/pinpoint/plugin/reactor/netty/interceptor/HttpClientRequestHeaderAdaptor.java"
] | [] | diff --git a/plugins/reactor-netty/src/main/java/com/navercorp/pinpoint/plugin/reactor/netty/interceptor/HttpClientRequestHeaderAdaptor.java b/plugins/reactor-netty/src/main/java/com/navercorp/pinpoint/plugin/reactor/netty/interceptor/HttpClientRequestHeaderAdaptor.java
index b195e6d6a24e..839c462d46f4 100644
--- a/plugins/reactor-netty/src/main/java/com/navercorp/pinpoint/plugin/reactor/netty/interceptor/HttpClientRequestHeaderAdaptor.java
+++ b/plugins/reactor-netty/src/main/java/com/navercorp/pinpoint/plugin/reactor/netty/interceptor/HttpClientRequestHeaderAdaptor.java
@@ -31,7 +31,11 @@ public class HttpClientRequestHeaderAdaptor implements ClientHeaderAdaptor<HttpC
@Override
public void setHeader(final HttpClientRequest request, final String name, final String value) {
if (request != null) {
- request.addHeader(name, value);
+ try {
+ request.header(name, value);
+ } catch (IllegalStateException|UnsupportedOperationException e) {
+ logger.warn("Set header {}={} failed, because {}", name, value, e.getMessage());
+ }
if (isDebug) {
logger.debug("Set header {}={}", name, value);
}
| null | val | test | "2021-03-16T11:46:47" | "2021-03-18T11:11:10Z" | yjqg6666 | test |
pinpoint-apm/pinpoint/7895_7896 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/7895 | pinpoint-apm/pinpoint/7896 | [
"keyword_pr_to_issue",
"connected"
] | af77f082c2e44c5b1c6e3f4d4355e90c487104a8 | 3436a0d582899310ee54f013cd04c16a0d026c2e | [] | [] | "2021-05-26T12:34:09Z" | [
"bug",
"module:plugin"
] | Jedis get `Unknown` endpoint when using `spring-boot-starter-data-redis` | #### contribution info
* Contributor : @hoverwinter
- spring-boot 2.4.2 (spring-boot-starter-data-redis) with default configuration.
Reason:
`JedisPlugin` has no interceptor for following constructor of `BinaryJedis`:
- public BinaryJedis(String host, int port, int connectionTimeout, int soTimeout, int infiniteSoTimeout)
- public BinaryJedis(String host, int port, int connectionTimeout, int soTimeout, int infiniteSoTimeout, boolean ssl, SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, HostnameVerifier hostnameVerifier)
- public BinaryJedis(URI uri, int connectionTimeout, int soTimeout, int infiniteSoTimeout, SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, HostnameVerifier hostnameVerifier)
- public BinaryJedis(final JedisSocketFactory jedisSocketFactory)
New parameter named `infiniteSoTimeout` is introduced in new version, such as `3.4.0` | [
"plugins/bom/pom.xml",
"plugins/redis/src/main/java/com/navercorp/pinpoint/plugin/redis/jedis/JedisPlugin.java",
"plugins/redis/src/main/java/com/navercorp/pinpoint/plugin/redis/jedis/interceptor/SetEndPointInterceptor.java"
] | [
"plugins/bom/pom.xml",
"plugins/redis/src/main/java/com/navercorp/pinpoint/plugin/redis/jedis/JedisPlugin.java",
"plugins/redis/src/main/java/com/navercorp/pinpoint/plugin/redis/jedis/interceptor/SetEndPointInterceptor.java"
] | [] | diff --git a/plugins/bom/pom.xml b/plugins/bom/pom.xml
index 02637114fffc..f032d39c78c3 100644
--- a/plugins/bom/pom.xml
+++ b/plugins/bom/pom.xml
@@ -30,7 +30,7 @@
<name>pinpoint-plugin-bom</name>
<properties>
- <jedis.version>2.4.2</jedis.version>
+ <jedis.version>3.4.0</jedis.version>
<lettuce.version>5.1.2.RELEASE</lettuce.version>
<cassandra.driver.version>2.1.7.1</cassandra.driver.version>
<dubbo.version>2.5.3</dubbo.version>
diff --git a/plugins/redis/src/main/java/com/navercorp/pinpoint/plugin/redis/jedis/JedisPlugin.java b/plugins/redis/src/main/java/com/navercorp/pinpoint/plugin/redis/jedis/JedisPlugin.java
index 8e0996a7ec49..abe3b67f08b7 100644
--- a/plugins/redis/src/main/java/com/navercorp/pinpoint/plugin/redis/jedis/JedisPlugin.java
+++ b/plugins/redis/src/main/java/com/navercorp/pinpoint/plugin/redis/jedis/JedisPlugin.java
@@ -113,10 +113,14 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader,
JedisUtils.addSetEndPointInterceptor(target, "java.lang.String", "int", "int", "boolean", "javax.net.ssl.SSLSocketFactory", "javax.net.ssl.SSLParameters", "javax.net.ssl.HostnameVerifier");
// host, port, connectionTimeout, soTimeout
JedisUtils.addSetEndPointInterceptor(target, "java.lang.String", "int", "int", "int");
+ // host, port, connectionTimeout, soTimeout, infiniteSoTimeout
+ JedisUtils.addSetEndPointInterceptor(target, "java.lang.String", "int", "int", "int", "int");
// host, port, connectionTimeout, soTimeout, ssl
JedisUtils.addSetEndPointInterceptor(target, "java.lang.String", "int", "int", "int", "boolean");
// host, port, connectionTimeout, soTimeout, ssl, sslSocketFactory, sslParameters, hostnameVerifier
JedisUtils.addSetEndPointInterceptor(target, "java.lang.String", "int", "int", "int", "boolean", "javax.net.ssl.SSLSocketFactory", "javax.net.ssl.SSLParameters", "javax.net.ssl.HostnameVerifier");
+ // host, port, connectionTimeout, soTimeout, infiniteSoTimeout, ssl, sslSocketFactory, sslParameters, hostnameVerifier
+ JedisUtils.addSetEndPointInterceptor(target, "java.lang.String", "int", "int", "int", "int", "boolean", "javax.net.ssl.SSLSocketFactory", "javax.net.ssl.SSLParameters", "javax.net.ssl.HostnameVerifier");
// shardInfo
JedisUtils.addSetEndPointInterceptor(target, "redis.clients.jedis.JedisShardInfo");
// uri
@@ -131,6 +135,10 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader,
JedisUtils.addSetEndPointInterceptor(target, "java.net.URI", "int", "int");
// uri, connectionTimeout, soTimeout, sslSocketFactory, sslParameters, hostnameVerifier
JedisUtils.addSetEndPointInterceptor(target, "java.net.URI", "int", "int", "javax.net.ssl.SSLSocketFactory", "javax.net.ssl.SSLParameters", "javax.net.ssl.HostnameVerifier");
+ // uri, connectionTimeout, soTimeout, infiniteSoTimeout, sslSocketFactory, sslParameters, hostnameVerifier
+ JedisUtils.addSetEndPointInterceptor(target, "java.net.URI", "int", "int", "int", "javax.net.ssl.SSLSocketFactory", "javax.net.ssl.SSLParameters", "javax.net.ssl.HostnameVerifier");
+ // redis.clients.jedis.JedisSocketFactory
+ JedisUtils.addSetEndPointInterceptor(target, "redis.clients.jedis.JedisSocketFactory");
// methods(commands)
final JedisPluginConfig config = new JedisPluginConfig(instrumentor.getProfilerConfig());
diff --git a/plugins/redis/src/main/java/com/navercorp/pinpoint/plugin/redis/jedis/interceptor/SetEndPointInterceptor.java b/plugins/redis/src/main/java/com/navercorp/pinpoint/plugin/redis/jedis/interceptor/SetEndPointInterceptor.java
index 505fffe64d37..a16fdca3f371 100644
--- a/plugins/redis/src/main/java/com/navercorp/pinpoint/plugin/redis/jedis/interceptor/SetEndPointInterceptor.java
+++ b/plugins/redis/src/main/java/com/navercorp/pinpoint/plugin/redis/jedis/interceptor/SetEndPointInterceptor.java
@@ -29,6 +29,7 @@
import com.navercorp.pinpoint.bootstrap.logging.PLogger;
import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
import com.navercorp.pinpoint.plugin.redis.jedis.EndPointAccessor;
+import redis.clients.jedis.JedisSocketFactory;
/**
* Jedis (redis client) constructor interceptor
@@ -75,6 +76,9 @@ private String getEndPoint(Object[] args) {
} else if (argZero instanceof JedisShardInfo) {
final JedisShardInfo info = (JedisShardInfo) argZero;
return HostAndPort.toHostAndPortString(info.getHost(), info.getPort());
+ } else if (argZero instanceof JedisSocketFactory) {
+ final JedisSocketFactory factory = (JedisSocketFactory) argZero;
+ return HostAndPort.toHostAndPortString(factory.getHost(), factory.getPort());
}
return "Unknown";
}
| null | train | test | "2021-05-26T04:13:10" | "2021-05-26T12:20:01Z" | hoverwinter | test |
pinpoint-apm/pinpoint/8019_8024 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/8019 | pinpoint-apm/pinpoint/8024 | [
"keyword_pr_to_issue"
] | be5a28d31fce4a209a82f7e191a8519ca7bf5a85 | 96254db2f83a05da89b4057c59487fb73646ac1d | [] | [] | "2021-07-12T03:20:15Z" | [
"enhancement",
"module:plugin"
] | jdk http client can not profiling https request | #### What version of pinpoint are you using?
master/v2.2.2
#### Describe the bug
the plugin jdk-http can only profiling/sampling http request, https request is not supported.
#### Expected behavior
request traced.
A PR would be made to fix it.
Update: see PR #8024. | [
"agent-testweb/pom.xml",
"agent/src/main/resources/profiles/local/pinpoint.config",
"agent/src/main/resources/profiles/release/pinpoint.config",
"plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPlugin.java",
"plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPluginConfig.java",
"plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/interceptor/HttpURLConnectionInterceptor.java"
] | [
"agent-testweb/jdk-http-plugin-testweb/README.md",
"agent-testweb/jdk-http-plugin-testweb/pom.xml",
"agent-testweb/jdk-http-plugin-testweb/src/main/resources/application.yml",
"agent-testweb/pom.xml",
"agent/src/main/resources/profiles/local/pinpoint.config",
"agent/src/main/resources/profiles/release/pinpoint.config",
"plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPlugin.java",
"plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPluginConfig.java",
"plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/interceptor/HttpURLConnectionInterceptor.java"
] | [
"agent-testweb/jdk-http-plugin-testweb/src/main/java/com/pinpointest/plugin/CertService.java",
"agent-testweb/jdk-http-plugin-testweb/src/main/java/com/pinpointest/plugin/JdkHttpPluginTestStarter.java",
"agent-testweb/jdk-http-plugin-testweb/src/main/java/com/pinpointest/plugin/controller/HelloWorldController.java",
"agent-testweb/jdk-http-plugin-testweb/src/main/java/com/pinpointest/plugin/controller/JdkHttpPluginController.java"
] | diff --git a/agent-testweb/jdk-http-plugin-testweb/README.md b/agent-testweb/jdk-http-plugin-testweb/README.md
new file mode 100644
index 000000000000..a09b57f7e64e
--- /dev/null
+++ b/agent-testweb/jdk-http-plugin-testweb/README.md
@@ -0,0 +1,16 @@
+
+## Install
+```
+$ mvnw -P pinpoint-jdk-http-plugin-testweb install -Dmaven.test.skip=true
+```
+
+## Run
+```
+$ mvnw -P pinpoint-jdk-http-plugin-testweb spring-boot:start
+```
+You can then access here: https://localhost:18443/
+
+## Stop
+```
+$ mvnw -P pinpoint-jdk-http-plugin-testweb spring-boot:stop
+```
diff --git a/agent-testweb/jdk-http-plugin-testweb/pom.xml b/agent-testweb/jdk-http-plugin-testweb/pom.xml
new file mode 100644
index 000000000000..5a805af40f2d
--- /dev/null
+++ b/agent-testweb/jdk-http-plugin-testweb/pom.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>com.navercorp.pinpoint</groupId>
+ <artifactId>pinpoint-agent-testweb</artifactId>
+ <version>2.3.1-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>pinpoint-jdk-http-plugin-testweb</artifactId>
+
+ <packaging>jar</packaging>
+
+ <properties>
+ <pinpoint.agent.jvmargument>
+ ${pinpoint.agent.default.jvmargument}
+ </pinpoint.agent.jvmargument>
+
+ <pinpoint.server.port>18443</pinpoint.server.port>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ </dependency>
+ </dependencies>
+
+</project>
\ No newline at end of file
diff --git a/agent-testweb/jdk-http-plugin-testweb/src/main/resources/application.yml b/agent-testweb/jdk-http-plugin-testweb/src/main/resources/application.yml
new file mode 100644
index 000000000000..d26aac35ece6
--- /dev/null
+++ b/agent-testweb/jdk-http-plugin-testweb/src/main/resources/application.yml
@@ -0,0 +1,21 @@
+# Defined in commandlineArgument of agent-test pom.xml
+
+server:
+ port: 18443
+ http:
+ port: 18080
+ http2:
+ enabled: true
+ ssl:
+ key-alias: pinpoint-keystore
+ key-store: classpath:pinpoint-keystore.jks
+ key-store-type: JKS
+ key-store-password: 123456
+
+logging:
+ level:
+ root: info
+
+springdoc:
+ swagger-ui:
+ path: /
diff --git a/agent-testweb/pom.xml b/agent-testweb/pom.xml
index ffb8351e5823..3f0a602515ae 100644
--- a/agent-testweb/pom.xml
+++ b/agent-testweb/pom.xml
@@ -48,6 +48,7 @@
-Dprofiler.sampling.rate=${pinpoint.agent.sampling-rate}
</pinpoint.agent.default.jvmargument>
<pinpoint.agent.jvmargument>${pinpoint.agent.default.jvmargument}</pinpoint.agent.jvmargument>
+ <pinpoint.server.port>18080</pinpoint.server.port>
</properties>
<modules>
@@ -59,6 +60,7 @@
<module>dubbo-plugin-testweb</module>
<!-- <module>spring-cloud-gateway-plugin-testweb</module>-->
<!-- <module>spring-webflux-plugin-testweb</module>-->
+ <module>jdk-http-plugin-testweb</module>
</modules>
@@ -131,7 +133,7 @@
<jvmArguments>${pinpoint.agent.jvmargument}</jvmArguments>
<agents>${maven.multiModuleProjectDirectory}/agent/target/pinpoint-agent-${project.version}/pinpoint-bootstrap.jar</agents>
<commandlineArguments>
- --server.port=18080
+ --server.port=${pinpoint.server.port}
--logging.level.root=info
--springdoc.swagger-ui.path=/
</commandlineArguments>
diff --git a/agent/src/main/resources/profiles/local/pinpoint.config b/agent/src/main/resources/profiles/local/pinpoint.config
index aca4895e8dfd..10e94326c987 100644
--- a/agent/src/main/resources/profiles/local/pinpoint.config
+++ b/agent/src/main/resources/profiles/local/pinpoint.config
@@ -787,6 +787,7 @@ profiler.apache.httpclient4.io=true
# JDK HTTPURLConnection #
###########################################################
# Profile parameter.
+profiler.jdk.http=true
profiler.jdk.http.param=true
###########################################################
diff --git a/agent/src/main/resources/profiles/release/pinpoint.config b/agent/src/main/resources/profiles/release/pinpoint.config
index 97c8f9e1b160..a4c1b36b5690 100644
--- a/agent/src/main/resources/profiles/release/pinpoint.config
+++ b/agent/src/main/resources/profiles/release/pinpoint.config
@@ -783,6 +783,7 @@ profiler.apache.httpclient4.io=true
# JDK HTTPURLConnection #
###########################################################
# Profile parameter.
+profiler.jdk.http=true
profiler.jdk.http.param=true
###########################################################
diff --git a/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPlugin.java b/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPlugin.java
index d01307aa8bd1..fc27056e280e 100644
--- a/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPlugin.java
+++ b/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPlugin.java
@@ -24,6 +24,9 @@
import com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformCallback;
import com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformTemplate;
import com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformTemplateAware;
+import com.navercorp.pinpoint.bootstrap.interceptor.scope.ExecutionPolicy;
+import com.navercorp.pinpoint.bootstrap.logging.PLogger;
+import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPlugin;
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPluginSetupContext;
import com.navercorp.pinpoint.bootstrap.plugin.util.InstrumentUtils;
@@ -32,15 +35,27 @@
/**
*
* @author Jongho Moon
+ * @author yjqg6666
*
*/
public class JdkHttpPlugin implements ProfilerPlugin, TransformTemplateAware {
private TransformTemplate transformTemplate;
+ private final PLogger logger = PLoggerFactory.getLogger(this.getClass());
+
+ public static final String INTERCEPT_HTTPS_CLASS_NAME = "sun.net.www.protocol.https.HttpsURLConnectionImpl";
+
+
@Override
public void setup(ProfilerPluginSetupContext context) {
+ JdkHttpPluginConfig config = new JdkHttpPluginConfig(context.getConfig());
+ if (!config.isEnable()) {
+ logger.info("{} disabled", this.getClass().getSimpleName());
+ return;
+ }
transformTemplate.transform("sun.net.www.protocol.http.HttpURLConnection", HttpURLConnectionTransform.class);
+ transformTemplate.transform(INTERCEPT_HTTPS_CLASS_NAME, HttpURLConnectionTransform.class);
}
public static class HttpURLConnectionTransform implements TransformCallback {
@@ -56,13 +71,13 @@ public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, Strin
}
final InstrumentMethod connectMethod = InstrumentUtils.findMethod(target, "connect");
- connectMethod.addScopedInterceptor(HttpURLConnectionInterceptor.class, "HttpURLConnection");
+ connectMethod.addScopedInterceptor(HttpURLConnectionInterceptor.class, "HttpURLConnectionConnect", ExecutionPolicy.ALWAYS);
final InstrumentMethod getInputStreamMethod = InstrumentUtils.findMethod(target, "getInputStream");
- getInputStreamMethod.addScopedInterceptor(HttpURLConnectionInterceptor.class, "HttpURLConnection");
+ getInputStreamMethod.addScopedInterceptor(HttpURLConnectionInterceptor.class, "HttpURLConnectionInput", ExecutionPolicy.BOUNDARY);
final InstrumentMethod getOutputStreamMethod = InstrumentUtils.findMethod(target, "getOutputStream");
- getOutputStreamMethod.addScopedInterceptor(HttpURLConnectionInterceptor.class, "HttpURLConnection");
+ getOutputStreamMethod.addScopedInterceptor(HttpURLConnectionInterceptor.class, "HttpURLConnectionOutput", ExecutionPolicy.BOUNDARY);
return target.toBytecode();
}
diff --git a/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPluginConfig.java b/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPluginConfig.java
index 0b695c00a151..f93a78c727c4 100644
--- a/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPluginConfig.java
+++ b/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/JdkHttpPluginConfig.java
@@ -9,13 +9,19 @@
public class JdkHttpPluginConfig {
private final boolean param;
+ private final boolean enable;
private final HttpDumpConfig httpDumpConfig;
public JdkHttpPluginConfig(ProfilerConfig src) {
+ this.enable = src.readBoolean("profiler.jdk.http", true);
this.param = src.readBoolean("profiler.jdk.http.param", true);
this.httpDumpConfig = HttpDumpConfig.getDefault();
}
+ public boolean isEnable() {
+ return enable;
+ }
+
public boolean isParam() {
return param;
}
@@ -27,7 +33,8 @@ public HttpDumpConfig getHttpDumpConfig() {
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("JdkHttpPluginConfig{");
- sb.append("param=").append(param);
+ sb.append("enable=").append(enable);
+ sb.append(", param=").append(param);
sb.append(", httpDumpConfig=").append(httpDumpConfig);
sb.append('}');
return sb.toString();
diff --git a/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/interceptor/HttpURLConnectionInterceptor.java b/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/interceptor/HttpURLConnectionInterceptor.java
index 27775dfebf45..246bcbdb06e6 100644
--- a/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/interceptor/HttpURLConnectionInterceptor.java
+++ b/plugins/jdk-http/src/main/java/com/navercorp/pinpoint/plugin/jdk/http/interceptor/HttpURLConnectionInterceptor.java
@@ -19,6 +19,7 @@
import com.navercorp.pinpoint.bootstrap.context.*;
import com.navercorp.pinpoint.bootstrap.interceptor.AroundInterceptor;
import com.navercorp.pinpoint.bootstrap.interceptor.scope.InterceptorScope;
+import com.navercorp.pinpoint.bootstrap.interceptor.scope.InterceptorScopeInvocation;
import com.navercorp.pinpoint.bootstrap.logging.PLogger;
import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
import com.navercorp.pinpoint.bootstrap.plugin.request.*;
@@ -30,6 +31,7 @@
/**
* @author netspider
* @author emeroad
+ * @author yjqg6666
*/
public class HttpURLConnectionInterceptor implements AroundInterceptor {
private static final Object TRACE_BLOCK_BEGIN_MARKER = new Object();
@@ -62,12 +64,16 @@ public void before(Object target, Object[] args) {
if (isDebug) {
logger.beforeInterceptor(target, args);
}
+
+ if (target == null) {
+ return;
+ }
+
Trace trace = traceContext.currentRawTraceObject();
if (trace == null) {
return;
}
- final HttpURLConnection request = (HttpURLConnection) target;
boolean connected = false;
if (target instanceof ConnectedGetter) {
connected = ((ConnectedGetter) target)._$PINPOINT$_isConnected();
@@ -77,71 +83,80 @@ public void before(Object target, Object[] args) {
connecting = ((ConnectingGetter) target)._$PINPOINT$_isConnecting();
}
- if (connected || connecting) {
- return;
+ boolean addRequestHeader = !connected && !connecting;
+ if (isInterceptingHttps()) {
+ addRequestHeader = addRequestHeader && isInterceptingConnect();
}
- final boolean sampling = trace.canSampled();
- if (!sampling) {
- if (request != null) {
+ final HttpURLConnection request = (HttpURLConnection) target;
+ final boolean canSample = trace.canSampled();
+ if (canSample) {
+ scope.getCurrentInvocation().setAttachment(TRACE_BLOCK_BEGIN_MARKER);
+ final SpanEventRecorder recorder = trace.traceBlockBegin();
+ recorder.recordServiceType(JdkHttpConstants.SERVICE_TYPE);
+ if (addRequestHeader) {
+ final TraceId nextId = trace.getTraceId().getNextTraceId();
+ recorder.recordNextSpanId(nextId.getSpanId());
+ String host = getHost(request);
+ this.requestTraceWriter.write(request, nextId, host);
+ }
+ } else {
+ if (addRequestHeader) {
this.requestTraceWriter.write(request);
}
- return;
- }
-
- scope.getCurrentInvocation().setAttachment(TRACE_BLOCK_BEGIN_MARKER);
-
- final SpanEventRecorder recorder = trace.traceBlockBegin();
- recorder.recordServiceType(JdkHttpConstants.SERVICE_TYPE);
- final TraceId nextId = trace.getTraceId().getNextTraceId();
- recorder.recordNextSpanId(nextId.getSpanId());
-
- if (request != null) {
- String host = getHost(request);
- this.requestTraceWriter.write(request, nextId, host);
}
}
-
- private String getHost(HttpURLConnection httpURLConnection) {
- final URL url = httpURLConnection.getURL();
- if (url != null) {
- final String host = url.getHost();
- final int port = url.getPort();
- if (host != null) {
- return JdkHttpClientRequestAdaptor.getEndpoint(host, port);
- }
- }
- return null;
- }
-
@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
if (isDebug) {
// do not log result
logger.afterInterceptor(target, args);
}
+ if (target == null) {
+ return;
+ }
Trace trace = traceContext.currentTraceObject();
- if (trace == null) {
+ if (trace == null || !trace.canSampled()) {
return;
}
- Object marker = scope.getCurrentInvocation().getAttachment();
- if (marker != TRACE_BLOCK_BEGIN_MARKER) {
+ final InterceptorScopeInvocation currentInvocation = scope.getCurrentInvocation();
+ if (TRACE_BLOCK_BEGIN_MARKER != currentInvocation.getAttachment()) {
return;
}
try {
+ final HttpURLConnection request = (HttpURLConnection) target;
final SpanEventRecorder recorder = trace.currentSpanEventRecorder();
recorder.recordApi(descriptor);
recorder.recordException(throwable);
- final HttpURLConnection request = (HttpURLConnection) target;
- if (request != null) {
- this.clientRequestRecorder.record(recorder, request, throwable);
- }
+ this.clientRequestRecorder.record(recorder, request, throwable);
} finally {
+ currentInvocation.removeAttachment();
trace.traceBlockEnd();
}
}
+
+ private String getHost(HttpURLConnection httpURLConnection) {
+ final URL url = httpURLConnection.getURL();
+ if (url != null) {
+ final String host = url.getHost();
+ final int port = url.getPort();
+ if (host != null) {
+ return JdkHttpClientRequestAdaptor.getEndpoint(host, port);
+ }
+ }
+ return null;
+ }
+
+ private boolean isInterceptingConnect() {
+ return "connect".contentEquals(this.descriptor.getMethodName());
+ }
+
+ private boolean isInterceptingHttps() {
+ return JdkHttpPlugin.INTERCEPT_HTTPS_CLASS_NAME.contentEquals(this.descriptor.getClassName());
+ }
+
}
| diff --git a/agent-testweb/jdk-http-plugin-testweb/src/main/java/com/pinpointest/plugin/CertService.java b/agent-testweb/jdk-http-plugin-testweb/src/main/java/com/pinpointest/plugin/CertService.java
new file mode 100644
index 000000000000..d460e6b38baf
--- /dev/null
+++ b/agent-testweb/jdk-http-plugin-testweb/src/main/java/com/pinpointest/plugin/CertService.java
@@ -0,0 +1,100 @@
+package com.pinpointest.plugin;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.core.io.Resource;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import java.io.InputStream;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.Certificate;
+import java.util.Enumeration;
+import java.util.Objects;
+
+@Component
+public class CertService {
+
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
+
+ private final Resource keyStorePath;
+ private final String password;
+ private final String keyStoreType;
+
+ private SSLContext sslContext;
+
+ public CertService(@Value("${server.ssl.key-store-type}") String keyStoreType,
+ @Value("${server.ssl.key-store}") Resource keyStorePath,
+ @Value("${server.ssl.key-store-password}") String password) {
+ this.keyStoreType = Objects.requireNonNull(keyStoreType, "keyStoreType");
+ this.keyStorePath = Objects.requireNonNull(keyStorePath, "keyStorePath");
+ this.password = Objects.requireNonNull(password, "password");
+ }
+
+ @PostConstruct
+ public void importCertForLocalCall() throws Exception {
+ KeyStore keyStore = KeyStore.getInstance(keyStoreType);
+ logger.info("KeyStore type:{}", keyStore.getType());
+ try (InputStream inputStream = keyStorePath.getInputStream()) {
+ keyStore.load(inputStream, password.toCharArray());
+ }
+
+
+ Enumeration<String> aliases = keyStore.aliases();
+ while (aliases.hasMoreElements()) {
+ String alias = aliases.nextElement();
+ logger.info("KeyStore aliases:{}", alias);
+ Certificate certificate = keyStore.getCertificate(alias);
+ logger.debug("Certificate:{}", certificate);
+ }
+
+ KeyManagerFactory kmf = newKeyManagerFactory(keyStore);
+ TrustManagerFactory tmf = newTrustManagerFactory(keyStore);
+
+
+ logger.info("KeyManagerFactory Algorithm:{} Provider:{}", kmf.getAlgorithm(), kmf.getProvider());
+ logger.info("TrustManagerFactory Algorithm:{} Provider:{}", tmf.getAlgorithm(), tmf.getProvider());
+
+ this.sslContext = newSSLContext(kmf, tmf);
+ }
+
+ private SSLContext newSSLContext(KeyManagerFactory kmf, TrustManagerFactory tmf) throws NoSuchAlgorithmException, KeyManagementException {
+ SSLContext sslContext = SSLContext.getInstance("SSL");
+
+ KeyManager[] keyManagers = kmf.getKeyManagers();
+ TrustManager[] trustManagers = tmf.getTrustManagers();
+ sslContext.init(keyManagers, trustManagers, new SecureRandom());
+
+ return sslContext;
+ }
+
+ private TrustManagerFactory newTrustManagerFactory(KeyStore keyStore) throws NoSuchAlgorithmException, KeyStoreException {
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ tmf.init(keyStore);
+ return tmf;
+ }
+
+ private KeyManagerFactory newKeyManagerFactory(KeyStore keyStore) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+ kmf.init(keyStore, password.toCharArray());
+ return kmf;
+ }
+
+ @Bean
+ public SSLContext getSslContext() {
+ return sslContext;
+ }
+
+}
diff --git a/agent-testweb/jdk-http-plugin-testweb/src/main/java/com/pinpointest/plugin/JdkHttpPluginTestStarter.java b/agent-testweb/jdk-http-plugin-testweb/src/main/java/com/pinpointest/plugin/JdkHttpPluginTestStarter.java
new file mode 100644
index 000000000000..ba004484b464
--- /dev/null
+++ b/agent-testweb/jdk-http-plugin-testweb/src/main/java/com/pinpointest/plugin/JdkHttpPluginTestStarter.java
@@ -0,0 +1,32 @@
+package com.pinpointest.plugin;
+
+import org.apache.catalina.connector.Connector;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
+import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
+import org.springframework.context.annotation.Bean;
+
+@SpringBootApplication
+public class JdkHttpPluginTestStarter {
+
+ public static void main(String[] args) {
+ SpringApplication.run(JdkHttpPluginTestStarter.class, args);
+ }
+
+ @Bean
+ public ServletWebServerFactory serverFactory(@Value("${server.http.port}") int httpPort) {
+ TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
+ tomcat.addAdditionalTomcatConnectors(createHttpConnector(httpPort));
+ tomcat.setDisableMBeanRegistry(false);
+ return tomcat;
+ }
+
+ private Connector createHttpConnector(int httpPort) {
+ Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
+ connector.setPort(httpPort);
+ return connector;
+ }
+
+}
diff --git a/agent-testweb/jdk-http-plugin-testweb/src/main/java/com/pinpointest/plugin/controller/HelloWorldController.java b/agent-testweb/jdk-http-plugin-testweb/src/main/java/com/pinpointest/plugin/controller/HelloWorldController.java
new file mode 100644
index 000000000000..48e2cd1e50ec
--- /dev/null
+++ b/agent-testweb/jdk-http-plugin-testweb/src/main/java/com/pinpointest/plugin/controller/HelloWorldController.java
@@ -0,0 +1,13 @@
+package com.pinpointest.plugin.controller;
+
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+public class HelloWorldController {
+
+ @RequestMapping("/helloworld")
+ public String helloWorld() {
+ return "Hello-World";
+ }
+}
diff --git a/agent-testweb/jdk-http-plugin-testweb/src/main/java/com/pinpointest/plugin/controller/JdkHttpPluginController.java b/agent-testweb/jdk-http-plugin-testweb/src/main/java/com/pinpointest/plugin/controller/JdkHttpPluginController.java
new file mode 100644
index 000000000000..e6893c63ca72
--- /dev/null
+++ b/agent-testweb/jdk-http-plugin-testweb/src/main/java/com/pinpointest/plugin/controller/JdkHttpPluginController.java
@@ -0,0 +1,132 @@
+package com.pinpointest.plugin.controller;
+
+import org.apache.commons.io.IOUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Objects;
+
+@RestController
+public class JdkHttpPluginController {
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
+
+ public static final String HTTP_TARGET = "%s://localhost:%s/helloworld";
+
+
+ private final SSLContext sslContext;
+ private final int httpsPort;
+ private final int httpPort;
+
+ public JdkHttpPluginController(@Value("${server.port}") int httpsPort,
+ @Value("${server.http.port}") int httpPort,
+ SSLContext sslContext) {
+ this.httpsPort = httpsPort;
+ this.httpPort = httpPort;
+ this.sslContext = Objects.requireNonNull(sslContext, "sslContext");
+ }
+
+ private String getHttpUrl(String schema) {
+ if (schema.equalsIgnoreCase("https")) {
+ return String.format(HTTP_TARGET, schema, httpsPort);
+ } else {
+ return String.format(HTTP_TARGET, schema, httpPort);
+ }
+ }
+
+
+ @GetMapping(value = "/http-get")
+ public String httpGet() {
+ return httpCall("http", "GET");
+ }
+
+
+ @GetMapping(value = "/https-get")
+ public String httpsGet() {
+ return httpCall("https", "GET");
+ }
+
+
+ @GetMapping(value = "/http-post")
+ public String httpPost() {
+ return httpCall("http", "POST");
+ }
+
+ @GetMapping(value = "/https-post")
+ public String httpsPost() {
+ return httpCall("https", "GET");
+ }
+
+
+ @GetMapping(value = "/error")
+ public String error() throws IOException {
+ try {
+ final URL url = new URL("http://localhost:39000");
+ HttpURLConnection connection = openConnection(url);
+ connection.connect();
+ } catch (IOException e) {
+ return e.getMessage();
+ }
+ return "success";
+ }
+
+ private String httpCall(String schema, String method) {
+ final URL url = newURL(getHttpUrl(schema));
+ try {
+ HttpURLConnection connection = openConnection(url);
+ connection.setRequestMethod(method);
+ connection.connect();
+
+ final String contents = readStream(connection);
+ final URL targetURL = connection.getURL();
+
+ String log = String.format("url:%s contents:%s", targetURL, contents);
+ logger.info(log);
+ return log;
+ } catch (Exception e) {
+ logger.warn("{} open error", url, e);
+ return "fail";
+ }
+ }
+
+ private HttpURLConnection openConnection(URL url) throws IOException {
+ HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
+ if (httpURLConnection instanceof HttpsURLConnection) {
+ HttpsURLConnection httpsURLConnection = (HttpsURLConnection) httpURLConnection;
+ httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());
+ httpsURLConnection.setHostnameVerifier(new HostnameVerifier() {
+ @Override
+ public boolean verify(String hostname, SSLSession session) {
+ return "localhost".equalsIgnoreCase(hostname);
+ }
+ });
+ }
+ return httpURLConnection;
+ }
+
+ private String readStream(HttpURLConnection connection) throws IOException {
+ try (InputStream inputStream = connection.getInputStream()) {
+ return IOUtils.toString(inputStream, connection.getContentEncoding());
+ }
+ }
+
+ private URL newURL(String spec) {
+ try {
+ return new URL(spec);
+ } catch (MalformedURLException exception) {
+ throw new IllegalArgumentException("invalid url" + spec, exception);
+ }
+ }
+
+}
| test | test | "2021-08-10T09:48:59" | "2021-07-09T06:31:35Z" | yjqg6666 | test |
pinpoint-apm/pinpoint/9614_9615 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/9614 | pinpoint-apm/pinpoint/9615 | [
"keyword_pr_to_issue",
"connected"
] | 0a049cc7131e042fcb7f275c91f24d9e9d6a88c9 | 00fa07c24f3a8d17417bb2246f84682bb814f676 | [] | [] | "2023-01-09T05:49:17Z" | [] | Apply temporary fix to Pinot #6834 issue | https://github.com/apache/pinot/issues/6834
| [
"commons-pinot/src/main/java/com/navercorp/pinpoint/common/pinot/datasource/WrappedPinotPreparedStatement.java"
] | [
"commons-pinot/src/main/java/com/navercorp/pinpoint/common/pinot/datasource/WrappedPinotPreparedStatement.java"
] | [] | diff --git a/commons-pinot/src/main/java/com/navercorp/pinpoint/common/pinot/datasource/WrappedPinotPreparedStatement.java b/commons-pinot/src/main/java/com/navercorp/pinpoint/common/pinot/datasource/WrappedPinotPreparedStatement.java
index e39316e38d25..6226f2186b68 100644
--- a/commons-pinot/src/main/java/com/navercorp/pinpoint/common/pinot/datasource/WrappedPinotPreparedStatement.java
+++ b/commons-pinot/src/main/java/com/navercorp/pinpoint/common/pinot/datasource/WrappedPinotPreparedStatement.java
@@ -16,30 +16,153 @@
package com.navercorp.pinpoint.common.pinot.datasource;
+import org.apache.commons.codec.binary.Hex;
import org.apache.pinot.client.PinotConnection;
import org.apache.pinot.client.PinotPreparedStatement;
+import org.apache.pinot.client.utils.DateTimeUtils;
+import org.apache.pinot.client.utils.DriverUtils;
+import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.sql.Date;
/**
* @author Hyunjoon Cho
*/
public class WrappedPinotPreparedStatement extends PinotPreparedStatement {
+ // Temporary variables for fillStatementWithParameters(). TODO: remove these when Pinot driver is fixed.
+ private String query;
+ private final String[] parameters;
+ private final int maxRows = Integer.MAX_VALUE;
public WrappedPinotPreparedStatement(PinotConnection connection, String query) {
super(connection, query);
+ this.query = query;
+ if (!DriverUtils.queryContainsLimitStatement(this.query)) {
+ this.query = this.query + " LIMIT " + this.maxRows;
+ }
+ this.parameters = new String[this.getQuestionMarkCount(query)];
+ }
+
+ /* copied from org.apache.pinot.client.PreparedStatement. TODO: remove when Pinot driver is fixed. */
+ private int getQuestionMarkCount(String query) {
+ int questionMarkCount = 0;
+
+ for(int index = query.indexOf(63); index != -1; index = query.indexOf(63, index + 1)) {
+ ++questionMarkCount;
+ }
+
+ return questionMarkCount;
}
+
@Override
public boolean execute() throws SQLException {
// WARNING Do not invoke close().
// Ignore spotbug warning
- ResultSet resultSet = executeQuery();
+ ResultSet resultSet = executeQuery(fillStatementWithParameters());
if (resultSet.isLast()) {
return false;
} else {
return true;
}
}
+
+ /* temporary function. TODO: remove these when Pinot driver is fixed */
+ private String fillStatementWithParameters() throws SQLException {
+ String[] queryParts = query.split("\\?");
+ StringBuilder sb = new StringBuilder();
+ int i = 0;
+ while (i < parameters.length) {
+ sb.append(queryParts[i]);
+ if (parameters[i] == null) {
+ throw new SQLException("Prepared Statement parameter is not provided. index = " + i);
+
+ }
+ sb.append(parameters[i]);
+ i++;
+ }
+
+ while (i < queryParts.length) {
+ sb.append(queryParts[i]);
+ i++;
+ }
+
+ return sb.toString();
+ }
+
+ /* temporary setter functions to redirect mybatis parameter setting to temporary variables this.query and this.parameters TODO: remove these when Pinot driver is fixed */
+ public void setNull(int parameterIndex, int sqlType) throws SQLException {
+ this.validateState();
+ this.parameters[parameterIndex - 1] = "'NULL'";
+ }
+
+ public void setBoolean(int parameterIndex, boolean x) throws SQLException {
+ this.validateState();
+ this.parameters[parameterIndex - 1] = "'" + x + "'";
+ }
+
+ public void setShort(int parameterIndex, short x) throws SQLException {
+ this.validateState();
+ this.parameters[parameterIndex - 1] = String.valueOf(x);
+ }
+
+ public void setInt(int parameterIndex, int x) throws SQLException {
+ this.validateState();
+ this.parameters[parameterIndex - 1] = String.valueOf(x);
+ }
+
+ public void setLong(int parameterIndex, long x) throws SQLException {
+ this.validateState();
+ this.parameters[parameterIndex - 1] = String.valueOf(x);
+ }
+
+ public void setFloat(int parameterIndex, float x) throws SQLException {
+ this.validateState();
+ this.parameters[parameterIndex - 1] = String.valueOf(x);
+ }
+
+ public void setDouble(int parameterIndex, double x) throws SQLException {
+ this.validateState();
+ this.parameters[parameterIndex - 1] = String.valueOf(x);
+ }
+
+ public void setString(int parameterIndex, String x) throws SQLException {
+ this.validateState();
+ this.parameters[parameterIndex - 1] = "'" + x.replace("'", "''") + "'";;
+ }
+
+ public void setBytes(int parameterIndex, byte[] x) throws SQLException {
+ this.validateState();
+ this.parameters[parameterIndex - 1] = Hex.encodeHexString(x);
+ }
+
+ public void setDate(int parameterIndex, Date x) throws SQLException {
+ this.parameters[parameterIndex - 1] = DateTimeUtils.dateToString(x);
+ }
+
+ public void setTime(int parameterIndex, Time x) throws SQLException {
+ this.validateState();
+ this.parameters[parameterIndex - 1] = DateTimeUtils.timeToString(x);
+ }
+
+ public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
+ this.validateState();
+ this.parameters[parameterIndex - 1] = DateTimeUtils.timeStampToString(x);
+ }
+
+ public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
+ this.validateState();
+ this.parameters[parameterIndex - 1] = x.toString();
+ }
+
+ public void clearParameters() throws SQLException {
+ this.validateState();
+ for (int i = 0; i < this.parameters.length; i++) {
+ this.parameters[i] = null;
+ }
+ }
}
| null | test | test | "2023-01-09T05:51:38" | "2023-01-09T05:43:36Z" | ga-ram | test |
pinpoint-apm/pinpoint/5_8 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/5 | pinpoint-apm/pinpoint/8 | [
"timestamp(timedelta=1185.0, similarity=0.8948048723314214)"
] | 08ad403d69d57644b75c96d2c5371244d8e6f38b | e153099b20124570274842a6b913d42b83669f69 | [
"Decided to use doc directory for images.\n"
] | [] | "2014-12-26T07:44:34Z" | [] | Images for README and docs | Creating an issue to upload images for ref-linking in README and docs.
| [
"README.md",
"quickstart/README.md"
] | [
"README.md",
"quickstart/README.md"
] | [] | diff --git a/README.md b/README.md
index 3c13dadde3f1..398c6f92c4e1 100644
--- a/README.md
+++ b/README.md
@@ -6,26 +6,26 @@
* Minimal impact on performance (approximately 3% increase in resource usage)
## Overview
-Services nowadays often consists of many different components, communicating amongst themselves as well as making API calls to external services. How each and every transaction gets executed is often left as a blackbox. Pinpoint traces transaction flows between these components and provides a clear view to identify problem areas and potential bottlenecks.
+Services nowadays often consist of many different components, communicating amongst themselves as well as making API calls to external services. How each and every transaction gets executed is often left as a blackbox. Pinpoint traces transaction flows between these components and provides a clear view to identify problem areas and potential bottlenecks.
* **ServerMap** - Understand the topology of any distributed systems by visualizing how their components are interconnected. Clicking on a node reveals details about the component, such as its current status, and transaction count.
* **Request/Response Scatter Chart** - Visualize request count and response patterns over time to identify potential problems. Transactions can be selected for additional detail by dragging over the chart.
- [Image]
+ ![Server Map](doc/img/ss_server-map.png)
* **CallStack** - Gain code-level visibility to every transaction in a distributed environment, identifying bottlenecks and points of failure in a single view.
- [Image]
+ ![Call Stack](doc/img/ss_call-stack.png)
* **Inspector** - View additional details on the application such as CPU usage, Memory/Garbage Collection, and JVM arguments.
- [Image]
+ ![Inspector](doc/img/ss_inspector.png)
## Architecture
To be included.
## Quick Start
-You may run a sample Pinpoint instance in your own machine by running four simple scripts for each components : Collector, Web, Sample TestApp, HBase.
+You may run a sample Pinpoint instance in your own machine by running four simple scripts for each components: Collector, Web, Sample TestApp, HBase.
Once the components are running, you should be able to visit http://localhost:28080 to view the Pinpoint Web UI, and http://localhost:28081 to generate transactions on the Sample TestApp.
@@ -38,4 +38,6 @@ To be included.
To be included.
## License
-Pinpoint is licensed under the Apache License, Version 2.0. See LICENSE for full license text.
+Pinpoint is licensed under the Apache License, Version 2.0.
+
+See [LICENSE](LICENSE) for full license text.
diff --git a/quickstart/README.md b/quickstart/README.md
index 3bbfcaa650ff..21b944e9b5a8 100644
--- a/quickstart/README.md
+++ b/quickstart/README.md
@@ -10,9 +10,9 @@ In order to build Pinpoint and run QuickStart, the following requirements must b
* Maven installed
* JAVA_7_HOME environment variable set to JDK 7 installation directory.
-JDK 7+ and JAVA_7_HOME environment variable are required to build profiler-optional. If you choose to build each modules separately, you may do so with JDK 6.
+JDK 7+ and JAVA_7_HOME environment variable are required to build profiler-optional. If you choose to build each module separately, you may do so with JDK 6.
-QuickStart currently only supports Linux, and OSX.
+QuickStart supports Linux, and OSX.
## Starting
@@ -35,6 +35,14 @@ The following script downloads HBase standalone from [Apache download site](http
**TestApp** - Run ```quickstart/bin/start-testapp.sh```
+Once the startup scripts are completed, the last 10 lines of the Tomcat log are tailed to the console:
+
+**Collector** ![Collector quick start successful](../doc/img/ss_quickstart-collector-log.png)
+
+**Web UI** ![Web quick start successful](../doc/img/ss_quickstart-web-log.png)
+
+**TestApp** ![TestApp quick start successful](../doc/img/ss_quickstart-testapp-log.png)
+
### Check Status
Once HBase and the 3 daemons are running, you may visit the following addresses to test out your very own Pinpoint instance.
| null | train | train | "2014-12-26T07:59:37" | "2014-12-26T06:07:54Z" | Xylus | test |
pinpoint-apm/pinpoint/85_86 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/85 | pinpoint-apm/pinpoint/86 | [
"timestamp(timedelta=4984.0, similarity=0.9205776189652282)"
] | 37186eae8b31733e89d97a3be0404bcc37f4aa12 | d03dc824ecaf451e147ed1e5c51866e358442bbe | [] | [] | "2015-01-08T04:35:11Z" | [
"bug",
"enhancement"
] | Improvement thread safety of InterceptorRegistry | improvement thread safety of `InterceptorRegistry`
`array[index]=value` is not thread safe.
| [
"bootstrap-core/pom.xml",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/InterceptorRegistry.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/LoggingInterceptor.java",
"commons/src/main/java/com/navercorp/pinpoint/common/util/DelegateEnumeration.java"
] | [
"bootstrap-core/pom.xml",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/InterceptorRegistry.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/LoggingInterceptor.java",
"bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/WeakAtomicReferenceArray.java",
"commons/src/main/java/com/navercorp/pinpoint/common/util/DelegateEnumeration.java"
] | [
"bootstrap-core/src/test/java/com/navercorp/pinpoint/bootstrap/interceptor/AtomicMaxUpdater.java",
"bootstrap-core/src/test/java/com/navercorp/pinpoint/bootstrap/interceptor/InterceptorRegistryTest.java",
"bootstrap-core/src/test/java/com/navercorp/pinpoint/bootstrap/interceptor/WeakAtomicReferenceArrayTest.java",
"bootstrap-core/src/test/resources/log4j.xml",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/InterceptorTest.java"
] | diff --git a/bootstrap-core/pom.xml b/bootstrap-core/pom.xml
index 1d3b70ebedc2..7f53514ed877 100644
--- a/bootstrap-core/pom.xml
+++ b/bootstrap-core/pom.xml
@@ -13,6 +13,26 @@
<packaging>jar</packaging>
<dependencies>
+ <!-- Logging depedencies -->
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <!-- commons-logging-adapter -->
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>jcl-over-slf4j</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ </dependency>
</dependencies>
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/InterceptorRegistry.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/InterceptorRegistry.java
index 867294d3d035..76c98a400f2c 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/InterceptorRegistry.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/InterceptorRegistry.java
@@ -23,18 +23,19 @@
/**
* @author emeroad
*/
-public class InterceptorRegistry {
+public final class InterceptorRegistry {
- private static final LoggingInterceptor DUMMY = new LoggingInterceptor("com.navercorp.pinpoint.profiler.interceptor.DUMMY");
+ private static final LoggingInterceptor LOGGING_INTERCEPTOR = new LoggingInterceptor("com.navercorp.pinpoint.profiler.interceptor.LOGGING_INTERCEPTOR");
public static final InterceptorRegistry REGISTRY = new InterceptorRegistry();
private final static int DEFAULT_MAX = 4096;
- private final int max;
+ private final int registrySize;
private final AtomicInteger id = new AtomicInteger(0);
- private final StaticAroundInterceptor[] index;
- private final SimpleAroundInterceptor[] simpleIndex;
+
+ private final WeakAtomicReferenceArray<StaticAroundInterceptor> staticIndex;
+ private final WeakAtomicReferenceArray<SimpleAroundInterceptor> simpleIndex;
// private final ConcurrentMap<String, Integer> nameIndex = new ConcurrentHashMap<String, Integer>();
@@ -42,24 +43,29 @@ public InterceptorRegistry() {
this(DEFAULT_MAX);
}
- InterceptorRegistry(int max) {
- this.max = max;
- this.index = new StaticAroundInterceptor[max];
- this.simpleIndex = new SimpleAroundInterceptor[max];
+ InterceptorRegistry(int maxRegistrySize) {
+ if (maxRegistrySize < 0) {
+ throw new IllegalArgumentException("negative maxRegistrySize:" + maxRegistrySize);
+ }
+ this.registrySize = maxRegistrySize;
+ this.staticIndex = new WeakAtomicReferenceArray<StaticAroundInterceptor>(maxRegistrySize, StaticAroundInterceptor.class);
+ this.simpleIndex = new WeakAtomicReferenceArray<SimpleAroundInterceptor>(maxRegistrySize, SimpleAroundInterceptor.class);
}
- public int addInterceptor0(StaticAroundInterceptor interceptor) {
+ public int addStaticInterceptor(StaticAroundInterceptor interceptor) {
if (interceptor == null) {
return -1;
}
+ return addInterceptor(interceptor, staticIndex);
+ }
+
+ private <T extends Interceptor> int addInterceptor(T interceptor, WeakAtomicReferenceArray<T> index) {
final int newId = nextId();
- if (newId >= max) {
- throw new IndexOutOfBoundsException("size=" + index.length + " id=" + id);
+ if (newId >= registrySize) {
+ throw new IndexOutOfBoundsException("size=" + index.length() + " id=" + id);
}
-
- this.index[newId] = interceptor;
-// this.nameIndex.put(interceptor.getClass().getName(), newId);
+ index.set(newId, interceptor);
return newId;
}
@@ -72,72 +78,59 @@ int addSimpleInterceptor0(SimpleAroundInterceptor interceptor) {
return -1;
}
final int newId = nextId();
- if (newId >= max) {
- throw new IndexOutOfBoundsException("size=" + index.length + " id=" + id);
+ if (newId >= registrySize) {
+ throw new IndexOutOfBoundsException("size=" + staticIndex.length() + " id=" + id);
}
- this.simpleIndex[newId] = interceptor;
-// this.nameIndex.put(interceptor.getClass().getName(), newId);
+ this.simpleIndex.set(newId, interceptor);
return newId;
}
public StaticAroundInterceptor getInterceptor0(int key) {
- StaticAroundInterceptor interceptor = index[key];
+ final StaticAroundInterceptor interceptor = staticIndex.get(key);
if (interceptor == null) {
- // return DUMMY upon wrong logic
- return DUMMY;
+ // return LOGGING_INTERCEPTOR upon wrong logic
+ return LOGGING_INTERCEPTOR;
}
return interceptor;
}
+ public Interceptor findInterceptor0(int key) {
+ final SimpleAroundInterceptor simpleInterceptor = this.simpleIndex.get(key);
+ if (simpleInterceptor != null) {
+ return simpleInterceptor;
+ }
+ final StaticAroundInterceptor staticAroundInterceptor = this.staticIndex.get(key);
+ if (staticAroundInterceptor != null) {
+ return staticAroundInterceptor;
+ }
+ Logger logger = Logger.getLogger(InterceptorRegistry.class.getName());
+ if (logger.isLoggable(Level.WARNING)) {
+ logger.warning("interceptor not found. id:" + key);
+ }
+ return LOGGING_INTERCEPTOR;
+ }
+
SimpleAroundInterceptor getSimpleInterceptor0(int key) {
- SimpleAroundInterceptor interceptor = simpleIndex[key];
+ final SimpleAroundInterceptor interceptor = simpleIndex.get(key);
if (interceptor == null) {
- // return DUMMY upon wrong logic
- return DUMMY;
+ // return LOGGING_INTERCEPTOR upon wrong logic
+ return LOGGING_INTERCEPTOR;
}
return interceptor;
}
-// SimpleAroundInterceptor getInterceptor0(int key) {
-// StaticAfterInterceptor interceptor = index[key];
-// if (interceptor == null) {
-// // return DUMMY upon wrong logic
-// return DUMMY;
-// }
-// return interceptor;
-// }
-// public Interceptor findInterceptor0(String interceptorName) {
-// Integer indexNumber = this.nameIndex.get(interceptorName);
-// if (indexNumber != null) {
-// return index[indexNumber];
-// }
-// return null;
-// }
public static int addInterceptor(StaticAroundInterceptor interceptor) {
- return REGISTRY.addInterceptor0(interceptor);
+ return REGISTRY.addStaticInterceptor(interceptor);
}
public static StaticAroundInterceptor getInterceptor(int key) {
return REGISTRY.getInterceptor0(key);
}
-
public static Interceptor findInterceptor(int key) {
- SimpleAroundInterceptor simpleInterceptor = REGISTRY.getSimpleInterceptor0(key);
- if (simpleInterceptor != null) {
- return simpleInterceptor;
- }
- StaticAroundInterceptor staticAroundInterceptor = REGISTRY.getInterceptor0(key);
- if (staticAroundInterceptor != null) {
- return staticAroundInterceptor;
- }
- Logger logger = Logger.getLogger(InterceptorRegistry.class.getName());
- if (logger.isLoggable(Level.WARNING)) {
- logger.warning("interceptor not found. id:" + key);
- }
- return DUMMY;
+ return REGISTRY.findInterceptor0(key);
}
public static int addSimpleInterceptor(SimpleAroundInterceptor interceptor) {
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/LoggingInterceptor.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/LoggingInterceptor.java
index 58e732bde24e..9ad6777ea144 100644
--- a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/LoggingInterceptor.java
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/LoggingInterceptor.java
@@ -23,7 +23,7 @@
/**
* @author emeroad
*/
-public class LoggingInterceptor implements StaticAroundInterceptor, SimpleAroundInterceptor {
+public class LoggingInterceptor implements StaticAroundInterceptor, SimpleAroundInterceptor, Interceptor {
private final Logger logger;
@@ -60,10 +60,7 @@ public void after(Object target, Object[] args, Object result, Throwable throwab
}
public static String defaultString(final Object object) {
- if (object == null) {
- return "null";
- }
- return object.toString();
+ return String.valueOf(object);
}
}
diff --git a/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/WeakAtomicReferenceArray.java b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/WeakAtomicReferenceArray.java
new file mode 100644
index 000000000000..2b22326627b2
--- /dev/null
+++ b/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/WeakAtomicReferenceArray.java
@@ -0,0 +1,43 @@
+package com.navercorp.pinpoint.bootstrap.interceptor;
+
+import java.util.concurrent.atomic.AtomicReferenceArray;
+
+/**
+ * @author emeroad
+ */
+public final class WeakAtomicReferenceArray<T> {
+
+ private final int length;
+ private final AtomicReferenceArray<T> atomicArray;
+// private final T[] array;
+
+ public WeakAtomicReferenceArray(int length, Class<? extends T> clazz) {
+ this.length = length;
+ this.atomicArray = new AtomicReferenceArray<T>(length);
+// this.array = (T[]) Array.newInstance(clazz, length);
+ }
+
+ public final void set(int index, T newValue) {
+ this.atomicArray.set(index, newValue);
+ // need TestCase ~~
+// this.array[index] = newValue;
+ }
+
+ public final int length() {
+ return length;
+ }
+
+
+ public final T get(int index) {
+ // try not thread safe read -> fail -> thread safe read
+// final T unsafeValue = this.array[index];
+// if (unsafeValue != null) {
+// return unsafeValue;
+// }
+// return (T) this.array[index];
+
+ // thread safe read
+ return this.atomicArray.get(index);
+ }
+
+}
diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/DelegateEnumeration.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/DelegateEnumeration.java
index 59fdd5f0f069..5f05f83036e7 100644
--- a/commons/src/main/java/com/navercorp/pinpoint/common/util/DelegateEnumeration.java
+++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/DelegateEnumeration.java
@@ -58,7 +58,7 @@ public boolean hasMoreElements() {
@Override
public E nextElement() {
next(false);
- // nextExcetpion
+ // nextException
if (nextException != null) {
final Exception exception = this.nextException;
clearNext();
| diff --git a/bootstrap-core/src/test/java/com/navercorp/pinpoint/bootstrap/interceptor/AtomicMaxUpdater.java b/bootstrap-core/src/test/java/com/navercorp/pinpoint/bootstrap/interceptor/AtomicMaxUpdater.java
new file mode 100644
index 000000000000..2bf67518386d
--- /dev/null
+++ b/bootstrap-core/src/test/java/com/navercorp/pinpoint/bootstrap/interceptor/AtomicMaxUpdater.java
@@ -0,0 +1,28 @@
+package com.navercorp.pinpoint.bootstrap.interceptor;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * @author emeroad
+ */
+public class AtomicMaxUpdater {
+
+ private final AtomicInteger maxIndex = new AtomicInteger(-1);
+
+ public boolean updateMax(int max) {
+ while (true) {
+ final int currentMax = maxIndex.get();
+ if (currentMax >= max) {
+ return false;
+ }
+ final boolean update = maxIndex.compareAndSet(currentMax, max);
+ if (update) {
+ return true;
+ }
+ }
+ }
+
+ public int getIndex() {
+ return maxIndex.get();
+ }
+}
diff --git a/bootstrap-core/src/test/java/com/navercorp/pinpoint/bootstrap/interceptor/InterceptorRegistryTest.java b/bootstrap-core/src/test/java/com/navercorp/pinpoint/bootstrap/interceptor/InterceptorRegistryTest.java
new file mode 100644
index 000000000000..208577960766
--- /dev/null
+++ b/bootstrap-core/src/test/java/com/navercorp/pinpoint/bootstrap/interceptor/InterceptorRegistryTest.java
@@ -0,0 +1,84 @@
+package com.navercorp.pinpoint.bootstrap.interceptor;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import static org.mockito.Mockito.mock;
+
+public class InterceptorRegistryTest {
+
+ @Test
+ public void indexSize_0() {
+
+ try {
+ new InterceptorRegistry(-1);
+ Assert.fail();
+ } catch (IllegalArgumentException ignore) {
+ }
+
+ }
+
+ @Test
+ public void indexSize_1() {
+ try {
+ InterceptorRegistry interceptorRegistry = new InterceptorRegistry(0);
+ StaticAroundInterceptor mock = mock(StaticAroundInterceptor.class);
+ interceptorRegistry.addStaticInterceptor(mock);
+ Assert.fail();
+ } catch (IndexOutOfBoundsException ignore) {
+ }
+ }
+
+ @Test
+ public void indexSize_2() {
+ InterceptorRegistry interceptorRegistry = new InterceptorRegistry(1);
+ interceptorRegistry.addStaticInterceptor(mock(StaticAroundInterceptor.class));
+ try {
+ interceptorRegistry.addStaticInterceptor(mock(StaticAroundInterceptor.class));
+ Assert.fail();
+ } catch (IndexOutOfBoundsException ignore) {
+ }
+ }
+
+ @Test
+ public void addStaticInterceptor() {
+ StaticAroundInterceptor mock = mock(StaticAroundInterceptor.class);
+
+ InterceptorRegistry registry = new InterceptorRegistry();
+ int key = registry.addStaticInterceptor(mock);
+ StaticAroundInterceptor find = registry.getInterceptor0(key);
+
+ Assert.assertSame(mock, find);
+ }
+
+ @Test
+ public void addSimpleInterceptor() {
+ SimpleAroundInterceptor mock = mock(SimpleAroundInterceptor.class);
+
+ InterceptorRegistry registry = new InterceptorRegistry();
+ int key = registry.addSimpleInterceptor0(mock);
+ SimpleAroundInterceptor find = registry.getSimpleInterceptor0(key);
+
+ Assert.assertSame(mock, find);
+ }
+
+ @Test
+ public void findInterceptor() {
+ SimpleAroundInterceptor mock0 = mock(SimpleAroundInterceptor.class);
+ StaticAroundInterceptor mock1 = mock(StaticAroundInterceptor.class);
+
+ InterceptorRegistry registry = new InterceptorRegistry();
+ int key1 = registry.addSimpleInterceptor0(mock0);
+ Assert.assertEquals(key1, 0);
+ int key2 = registry.addStaticInterceptor(mock1);
+ Assert.assertEquals(key2, 1);
+ Interceptor interceptor0 = registry.findInterceptor0(0);
+ Assert.assertNotNull(interceptor0);
+ Assert.assertSame(interceptor0, mock0);
+ Interceptor interceptor1 = registry.findInterceptor0(1);
+ Assert.assertNotNull(interceptor1);
+ Assert.assertSame(interceptor1, mock1);
+
+ }
+
+}
\ No newline at end of file
diff --git a/bootstrap-core/src/test/java/com/navercorp/pinpoint/bootstrap/interceptor/WeakAtomicReferenceArrayTest.java b/bootstrap-core/src/test/java/com/navercorp/pinpoint/bootstrap/interceptor/WeakAtomicReferenceArrayTest.java
new file mode 100644
index 000000000000..b08d0accbe30
--- /dev/null
+++ b/bootstrap-core/src/test/java/com/navercorp/pinpoint/bootstrap/interceptor/WeakAtomicReferenceArrayTest.java
@@ -0,0 +1,314 @@
+package com.navercorp.pinpoint.bootstrap.interceptor;
+
+import junit.framework.Assert;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Random;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * raceCondition generate fail.~~~~ hmm
+ */
+@Ignore
+public class WeakAtomicReferenceArrayTest {
+
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
+
+ private final int arraySize = 1024 * 2000;
+ private final int testMapSize = 1;
+
+ private final Map<Integer, AtomicReferenceTest> map = new HashMap<Integer, AtomicReferenceTest>();
+ private final AtomicInteger nextMapId = new AtomicInteger();
+
+ private int writerThreadSize = 1;
+ private ThreadPoolExecutor writer;
+
+ private int readThreadSize = 2;
+ private ThreadPoolExecutor reader;
+
+ private final AtomicInteger failCounter = new AtomicInteger();
+
+ @Before
+ public void setUp() throws Exception {
+ writer = (ThreadPoolExecutor) Executors.newFixedThreadPool(writerThreadSize);
+ reader = (ThreadPoolExecutor) Executors.newFixedThreadPool(readThreadSize);
+ writer.prestartAllCoreThreads();
+ reader.prestartAllCoreThreads();
+ for (int i = 0; i < testMapSize; i++) {
+ map.put(i, new AtomicReferenceTest());
+ }
+ }
+
+
+ @After
+ public void tearDown() throws Exception {
+ writer.shutdownNow();
+ reader.shutdownNow();
+ }
+
+ static final class Cell {
+ volatile long p0, p1, p2, p3, p4, p5, p6;
+ volatile WeakAtomicReferenceArray<Integer> weakAtomicReferenceArray;
+ volatile long q0, q1, q2, q3, q4, q5, q6;
+ }
+
+ private static class ChangedValue {
+ private int index;
+ private int value;
+
+ public ChangedValue(int index, int value) {
+ this.index = index;
+ this.value = value;
+ }
+ }
+
+ private class AtomicReferenceTest {
+ private final Cell cell = new Cell();
+
+ private final AtomicInteger nextId = new AtomicInteger(0);
+ private final AtomicMaxUpdater maxIndex = new AtomicMaxUpdater();
+// private final ConcurrentLinkedQueue<Integer> updateIndex = new ConcurrentLinkedQueue<Integer>();
+ private final WeakAtomicReferenceArray<Integer> ref;
+ private final AtomicInteger afterLast = new AtomicInteger(-1);
+ private final AtomicReference<ChangedValue> lastChangeValue = new AtomicReference<ChangedValue>();
+
+
+ private final Random random = new Random();
+
+ public AtomicReferenceTest() {
+ cell.weakAtomicReferenceArray = new WeakAtomicReferenceArray<Integer>(arraySize, Integer.class);
+ ref = cell.weakAtomicReferenceArray;
+ }
+
+ public boolean nextId() {
+
+ int nextId = this.nextId.getAndIncrement();
+ if (nextId < arraySize) {
+ ref.set(nextId, nextId);
+ afterLast.set(nextId);
+// maxIndex.updateMax(nextId);
+// updateIndex.offer(nextId);
+// logger.debug("nextId:{}", nextId);
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean changeId(int index, int value) {
+
+ if (index < arraySize) {
+ ref.set(index, value);
+ lastChangeValue.set(new ChangedValue(index, value));
+// maxIndex.updateMax(nextId);
+// updateIndex.offer(nextId);
+// logger.debug("nextId:{}", nextId);
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+
+ public boolean get(final int findIndex) {
+ if (findIndex == -1) {
+ return true;
+ }
+ Integer findResult = ref.get(findIndex);
+ return checkInteger(findIndex, findResult);
+ }
+
+ public boolean checkChangeId() {
+ ChangedValue changedValue = lastChangeValue.get();
+ if (changedValue == null){
+ return true;
+ }
+ Integer findResult = ref.get(changedValue.index);
+ return checkInteger(changedValue.value, findResult);
+ }
+
+ private boolean checkInteger(int findIndex, Integer findResult) {
+ if (findResult == null) {
+ logger.info("null find:{} result:{}", findIndex, nextId.get());
+ return false;
+ }
+ final boolean result = findResult == findIndex;
+ if (!result) {
+ logger.info("not equals findResult:{}, findIndex:{}", findResult, findIndex);
+ }
+ return result;
+ }
+
+// public boolean testInsert() {
+// final Integer findIndex = updateIndex.poll();
+// if (findIndex == null) {
+// return true;
+// }
+// Integer findResult = cell.weakAtomicReferenceArray.get(findIndex);
+// if (random.nextInt(3) == 0) {
+// updateIndex.offer(findIndex);
+// }
+// return checkInteger(findIndex, findResult);
+// }
+
+
+
+ public boolean randomGet() {
+ if (writerThreadSize != 1) {
+ return true;
+ }
+// final int maxIndex = getMaxIndex();
+ final int maxIndex = afterLast.get();
+ if (maxIndex == -1) {
+ return true;
+ }
+ int randomIndex;
+ if (maxIndex == 0) {
+ randomIndex = 0;
+ } else {
+ randomIndex = Math.abs(random.nextInt()) % (maxIndex);
+ }
+ return get(randomIndex);
+ }
+
+ public boolean lastGet() {
+ return get(getMaxIndex());
+ }
+
+ private int getMaxIndex() {
+ return maxIndex.getIndex();
+ }
+
+ }
+
+ @Test
+ public void testLastGet() {
+ AtomicReferenceTest mock = new AtomicReferenceTest();
+ Assert.assertTrue(mock.lastGet());
+
+ mock.nextId();
+ Assert.assertTrue(mock.lastGet());
+ for (int i = 0; i < 10; i++) {
+ Assert.assertTrue(mock.lastGet());
+ }
+ }
+
+ @Test
+ public void testRandomGet() {
+ AtomicReferenceTest mock = new AtomicReferenceTest();
+ Assert.assertTrue(mock.randomGet());
+ mock.nextId();
+ mock.nextId();
+ mock.nextId();
+ Assert.assertTrue(mock.randomGet());
+ for (int i = 0; i < 10; i++) {
+ Assert.assertTrue(mock.randomGet());
+ }
+ }
+
+
+
+ @Test
+ public void testTestMock3() {
+ AtomicReferenceTest mock = new AtomicReferenceTest();
+ mock.nextId();
+ mock.nextId();
+ mock.nextId();
+ Assert.assertTrue(mock.randomGet());
+ for (int i = 0; i < 100; i++) {
+ Assert.assertTrue(mock.randomGet());
+ }
+ }
+
+ @Test
+ public void test() throws Exception {
+ final AtomicBoolean start = new AtomicBoolean(true);
+
+ final Runnable writeJob = new Runnable() {
+ @Override
+ public void run() {
+ logger.info("WriteJob-start");
+ int i =0;
+ while (start.get()) {
+
+ AtomicReferenceTest referenceTest = getTestMock();
+ referenceTest.nextId();
+// referenceTest.changeId(0, i);
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException ignore) {
+ }
+ i++;
+ }
+ logger.info("WriteJob-end");
+ }
+
+ };
+
+ final Runnable readJob = new Runnable() {
+ @Override
+ public void run() {
+ logger.info("ReaderJob-start");
+ while (start.get()) {
+
+ AtomicReferenceTest atomicReferenceTest = getTestMock();
+ if (!atomicReferenceTest.lastGet()) {
+ failCounter.getAndIncrement();
+ }
+// if (!atomicReferenceTest.checkChangeId()) {
+// failCounter.getAndIncrement();
+// }
+// if (!testMock.testInsert()) {
+// failCounter.getAndIncrement();
+// }
+// if (!testMock.randomGet()) {
+// failCounter.getAndIncrement();
+// }
+// try {
+// Thread.sleep(10);
+// } catch (InterruptedException e) {
+// e.printStackTrace();
+// }
+ }
+ logger.info("ReaderJob-end");
+ }
+ };
+
+ for (int i = 0; i < readThreadSize; i++) {
+ reader.execute(readJob);
+ }
+ for (int i = 0; i < writerThreadSize; i++) {
+ writer.execute(writeJob);
+ }
+
+ System.out.println("start");
+ for (int i = 0; i < 100; i++) {
+ Thread.sleep(1000);
+ logger.info("failCounter:{}", failCounter.get());
+ }
+ start.set(false);
+ Thread.sleep(1000);
+ Assert.assertEquals("raceCondition test", failCounter.get(), 0);
+ writer.shutdown();
+ reader.shutdown();
+
+ }
+
+ private AtomicReferenceTest getTestMock() {
+ int andIncrement = nextMapId.getAndIncrement();
+ int mapIndex = andIncrement % testMapSize;
+ return map.get(mapIndex);
+ }
+
+}
\ No newline at end of file
diff --git a/bootstrap-core/src/test/resources/log4j.xml b/bootstrap-core/src/test/resources/log4j.xml
new file mode 100644
index 000000000000..79094a1014e3
--- /dev/null
+++ b/bootstrap-core/src/test/resources/log4j.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
+<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
+
+ <appender name="console" class="org.apache.log4j.ConsoleAppender">
+ <layout class="org.apache.log4j.EnhancedPatternLayout">
+ <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%-5p](%-35c{1.}:%-3L) %m%n" />
+ <!-- %L(line number) option is extremely slow. -->
+ <!--<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%-5p](%-30c{1}) %m%n" />-->
+ </layout>
+ </appender>
+
+ <logger name="com.navercorp.pinpoint" additivity="false">
+ <level value="DEBUG" />
+ <appender-ref ref="console" />
+ </logger>
+
+ <root>
+ <level value="DEBUG" />
+ <appender-ref ref="console" />
+ </root>
+</log4j:configuration>
\ No newline at end of file
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/InterceptorRegistryTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/InterceptorTest.java
similarity index 94%
rename from profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/InterceptorRegistryTest.java
rename to profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/InterceptorTest.java
index 31c2226be5e6..3b77dedadc76 100644
--- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/InterceptorRegistryTest.java
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/InterceptorTest.java
@@ -34,21 +34,10 @@
/**
* @author emeroad
*/
-public class InterceptorRegistryTest {
+public class InterceptorTest {
- private final Logger logger = LoggerFactory.getLogger(InterceptorRegistryTest.class.getName());
+ private final Logger logger = LoggerFactory.getLogger(InterceptorTest.class.getName());
- private InterceptorRegistry registry = new InterceptorRegistry();
-
- @Test
- public void addInterceptor() throws Exception {
- TestBeforeInterceptor interceptor = new TestBeforeInterceptor();
-
- int key = registry.addInterceptor0(interceptor);
- Interceptor find = registry.getInterceptor0(key);
-
- Assert.assertEquals(interceptor, find);
- }
// @Test
public void methodName() throws NoSuchMethodException {
| train | train | "2015-01-07T02:34:47" | "2015-01-08T04:14:33Z" | emeroad | test |
pinpoint-apm/pinpoint/91_93 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/91 | pinpoint-apm/pinpoint/93 | [
"timestamp(timedelta=330.0, similarity=0.9231018481336303)"
] | ffea8a79e1bb8eea86853ea6691d34a4e6766ebb | 014e675d01cb9fabcf85225ecd0f5a010568cc5c | [] | [] | "2015-01-12T06:32:03Z" | [
"enhancement"
] | Extended URL matcher function | [
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/MatcherGroup.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/MatcherGroup.java",
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/PostfixServerMatcher.java"
] | [
"web/src/test/java/com/navercorp/pinpoint/web/applicationmap/link/PostfixServerMatcherTest.java"
] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/MatcherGroup.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/MatcherGroup.java
index bc1d9841120e..be01593f4a70 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/MatcherGroup.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/MatcherGroup.java
@@ -68,6 +68,7 @@ public ServerMatcher match(String value) {
return serverMatcher;
}
}
+
return defaultMatcher;
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/PostfixServerMatcher.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/PostfixServerMatcher.java
new file mode 100644
index 000000000000..2a2156e6287d
--- /dev/null
+++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/PostfixServerMatcher.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2014 NAVER Corp.
+ *
+ * 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.
+ */
+
+package com.navercorp.pinpoint.web.applicationmap.link;
+
+/**
+ * @author minwoo.jung
+ */
+public class PostfixServerMatcher implements ServerMatcher {
+
+ public final String postfix;
+ public final String url;
+ public final String linkName;
+
+ public PostfixServerMatcher(String postfix, String url, String linkName) {
+ this.postfix = postfix;
+ this.url = url;
+ this.linkName = linkName;
+ }
+
+ @Override
+ public boolean isMatched(String value) {
+ if (value == null) {
+ return false;
+ }
+ return value.endsWith(postfix);
+ }
+
+ @Override
+ public String getLinkName() {
+ return linkName;
+ }
+
+ @Override
+ public String getLink(String value) {
+ final int index = value.lastIndexOf(postfix);
+
+ if (index == -1) {
+ throw new IllegalArgumentException("invalid serverName:" + value);
+ }
+
+ String hostName = value.substring(0, index);
+ return url + hostName;
+ }
+}
| diff --git a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/link/PostfixServerMatcherTest.java b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/link/PostfixServerMatcherTest.java
new file mode 100644
index 000000000000..e09c02f0fc7f
--- /dev/null
+++ b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/link/PostfixServerMatcherTest.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2014 NAVER Corp.
+ *
+ * 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.
+ */
+
+package com.navercorp.pinpoint.web.applicationmap.link;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+/**
+ * @author minwoo.jung
+ */
+public class PostfixServerMatcherTest {
+
+ @Test
+ public void test() {
+ String url = "http://naver.com/";
+ String postfix = ".seoul.idc";
+ PostfixServerMatcher matcher = new PostfixServerMatcher(postfix, url, "NAVER");
+
+ String serverName = "naverServer01";
+ assertTrue(matcher.isMatched(serverName + postfix));
+ assertFalse(matcher.isMatched("naverserver" + "busan.idc"));
+
+ assertEquals(url + serverName, matcher.getLink(serverName + postfix));
+ }
+
+}
| train | train | "2015-01-12T05:50:14" | "2015-01-12T02:10:05Z" | minwoo-jung | test |
|
pinpoint-apm/pinpoint/94_96 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/94 | pinpoint-apm/pinpoint/96 | [
"timestamp(timedelta=38.0, similarity=0.9612864887245522)"
] | e5a47fbd9595183834b46224a2f05fdbe8126e96 | 9eaa863ceeae20aa3ed7c4516fc7dcb07764f0d0 | [] | [] | "2015-01-12T07:59:34Z" | [
"enhancement"
] | Change position and url Monitor site link in inspector page | [
"web/src/main/java/com/navercorp/pinpoint/web/view/ApplicationAgentListSerializer.java",
"web/src/main/webapp/views/agentInfoMain.html"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/view/ApplicationAgentListSerializer.java",
"web/src/main/webapp/views/agentInfoMain.html"
] | [] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/view/ApplicationAgentListSerializer.java b/web/src/main/java/com/navercorp/pinpoint/web/view/ApplicationAgentListSerializer.java
index a4dc85753f4d..2f8e1f83c78c 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/view/ApplicationAgentListSerializer.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/view/ApplicationAgentListSerializer.java
@@ -66,9 +66,9 @@ private void writeAgentList(JsonGenerator jgen, List<AgentInfoBo> agentList, Mat
jgen.writeNumberField("endStatus", agentInfoBo.getEndStatus());
jgen.writeObjectField("serverMetaData", agentInfoBo.getServerMetaData());
- ServerMatcher serverMatcher = matcherGroup.match(agentInfoBo.getIp());
+ ServerMatcher serverMatcher = matcherGroup.match(agentInfoBo.getHostName());
jgen.writeStringField("linkName", serverMatcher.getLinkName());
- jgen.writeStringField("linkURL", serverMatcher.getLink(agentInfoBo.getIp()));
+ jgen.writeStringField("linkURL", serverMatcher.getLink(agentInfoBo.getHostName()));
jgen.writeEndObject();
}
diff --git a/web/src/main/webapp/views/agentInfoMain.html b/web/src/main/webapp/views/agentInfoMain.html
index 083f736cb534..af9409c4719e 100644
--- a/web/src/main/webapp/views/agentInfoMain.html
+++ b/web/src/main/webapp/views/agentInfoMain.html
@@ -25,14 +25,14 @@ <h3>Information</h3>
</tr>
<tr>
<td class="text-right"><strong>Hostname</strong></td>
- <td class="text-left">{{info.hostName}}</td>
+ <td class="text-left">{{info.hostName}} <a ng-if="info.linkName" class="btn btn-default btn-xs" href="{{info.linkURL}}" target="_blank" title="System resource monitoring site">{{info.linkName}}</a></td>
<td class="text-right"><strong>JVM GC Type</strong></td>
<td class="text-left">{{info.jvmGcType}}</td>
</tr>
<tr>
<td class="text-right"><strong>IP</strong></td>
<td class="text-left">
- <div>{{info.ip}} <a ng-if="info.linkName" class="btn btn-default btn-xs" href="{{info.linkURL}}" target="_blank" title="System resource monitoring site">{{info.linkName}}</a></div>
+ <div>{{info.ip}}</div>
</td>
<td class="text-right"><strong>Start Time</strong></td>
<td class="text-left">{{agent.startTime | date:'yyyy-MM-dd HH:mm:ss Z'}}</td>
| null | train | train | "2015-01-12T07:43:56" | "2015-01-12T06:41:34Z" | minwoo-jung | test |
|
pinpoint-apm/pinpoint/140_141 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/140 | pinpoint-apm/pinpoint/141 | [
"timestamp(timedelta=58546.0, similarity=0.9608887208928373)"
] | 473df4e30e98726718646496d9161e31240be4aa | d9fc90c86793fab2c32b6fed4e7cb0309d34327b | [] | [] | "2015-01-27T08:32:23Z" | [
"bug"
] | Timer thread leak when client reconnect to server. | Timer thread leak when client reconnect to server.
Client auto reconnect when socket disconnect from peer.
In this situation client does not clean up running timer thread.
It can be problem when agent running for a long time or collector restart frequently.
| [
"rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocketHandler.java"
] | [
"rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocketHandler.java"
] | [
"rpc/src/test/java/com/navercorp/pinpoint/rpc/client/ReconnectTest.java"
] | diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocketHandler.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocketHandler.java
index f3018f3bc0dd..2f4761836b68 100644
--- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocketHandler.java
+++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocketHandler.java
@@ -453,30 +453,6 @@ public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws
}
- @Override
- public void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent e) throws Exception {
- final int currentState = state.getState();
- if (currentState == State.CLOSED) {
- logger.debug("channelClosed() normal. state:{} {}", state.getString(currentState), e.getChannel());
- return;
- } else if(currentState == State.INIT_RECONNECT){
- logger.debug("channelClosed() reconnect fail. state:{} {}", state.getString(currentState), e.getChannel());
- } else if (state.isRun(currentState) || currentState == State.RECONNECT) {
- // abnormal closed from here
- if (state.isRun(currentState)) {
- logger.debug("change state=reconnect");
- state.setState(State.RECONNECT);
- }
- logger.info("channelClosed() UnexpectedChannelClosed. state:{} try reconnect channel:{}, connectSocketAddress:{}", state.getString(), e.getChannel(), connectSocketAddress);
-
- this.pinpointSocketFactory.reconnect(this.pinpointSocket, this.connectSocketAddress);
- return;
- } else {
- logger.info("channelClosed() UnexpectedChannelClosed. state:{} {}", state.getString(currentState), e.getChannel());
- }
- releaseResource();
- }
-
private void ensureOpen() {
final int currentState = state.getState();
if (state.isRun(currentState)) {
@@ -503,8 +479,6 @@ boolean isClosed() {
public void close() {
logger.debug("close() call");
- this.handshaker.handshakeAbort();
-
int currentState = this.state.getState();
if (currentState == State.CLOSED) {
logger.debug("already close()");
@@ -522,36 +496,44 @@ public void close() {
// when you release resources, you need to clear messages about request/response and stream channel. need to handle reversely?
// handling timer is unclear so just make and enhance later.
+ closeStreamChannelManager(channel);
sendClosedPacket(channel);
- releaseResource();
+
logger.debug("channel.close()");
-
- ChannelFuture channelFuture = channel.close();
- channelFuture.addListener(new WriteFailFutureListener(logger, "close() event failed.", "close() event success."));
- channelFuture.awaitUninterruptibly();
+ ChannelFuture closeFuture = channel.close();
+ closeFuture.addListener(new WriteFailFutureListener(logger, "close() event failed.", "close() event success."));
+ closeFuture.awaitUninterruptibly();
logger.debug("close() complete");
}
+ private void closeStreamChannelManager(Channel channel) {
+ if (!channel.isConnected()) {
+ logger.debug("channel already closed. skip closeStreamChannelManager() {}", channel);
+ return;
+ }
+
+ // stream channel clear and send stream close packet
+ SocketHandlerContext context = getChannelContext(channel);
+ if (context != null) {
+ context.getStreamChannelManager().close();
+ }
+ }
+
private void releaseResource() {
logger.debug("releaseResource()");
+
+ this.handshaker.handshakeAbort();
this.requestManager.close();
-
- if (this.channel != null) {
- SocketHandlerContext context = getChannelContext(channel);
- if (context != null) {
- context.getStreamChannelManager().close();
- }
- }
-
this.channelTimer.stop();
}
-
+
private void sendClosedPacket(Channel channel) {
if (!channel.isConnected()) {
logger.debug("channel already closed. skip sendClosedPacket() {}", channel);
return;
}
- logger.debug("write ClientClosePacket");
+
+ logger.debug("write ClientClosePacket");
ClientClosePacket clientClosePacket = new ClientClosePacket();
ChannelFuture write = channel.write(clientClosePacket);
write.addListener(new ChannelFutureListener() {
@@ -567,7 +549,28 @@ public void operationComplete(ChannelFuture future) throws Exception {
write.awaitUninterruptibly(3000, TimeUnit.MILLISECONDS);
}
+ @Override
+ public void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent e) throws Exception {
+ final int currentState = state.getState();
+ if (State.CLOSED == currentState) {
+ logger.debug("channelClosed() normal. state:{} {}", state.getString(currentState), e.getChannel());
+ } else if(State.INIT_RECONNECT == currentState){
+ logger.debug("channelClosed() reconnect fail. state:{} {}", state.getString(currentState), e.getChannel());
+ } else if (state.isRun(currentState) || State.RECONNECT == currentState) {
+ // abnormal closed from here
+ if (state.isRun(currentState)) {
+ logger.debug("change state=reconnect");
+ state.setState(State.RECONNECT);
+ }
+ logger.info("channelClosed() UnexpectedChannelClosed. state:{} try reconnect channel:{}, connectSocketAddress:{}", state.getString(), e.getChannel(), connectSocketAddress);
+ this.pinpointSocketFactory.reconnect(this.pinpointSocket, this.connectSocketAddress);
+ } else {
+ logger.info("channelClosed() UnexpectedChannelClosed. state:{} {}", state.getString(currentState), e.getChannel());
+ }
+ releaseResource();
+ }
+
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("PinpointSocketHandler{");
| diff --git a/rpc/src/test/java/com/navercorp/pinpoint/rpc/client/ReconnectTest.java b/rpc/src/test/java/com/navercorp/pinpoint/rpc/client/ReconnectTest.java
index fe40921cb1ae..d307e0b620f6 100644
--- a/rpc/src/test/java/com/navercorp/pinpoint/rpc/client/ReconnectTest.java
+++ b/rpc/src/test/java/com/navercorp/pinpoint/rpc/client/ReconnectTest.java
@@ -17,11 +17,14 @@
package com.navercorp.pinpoint.rpc.client;
import java.io.IOException;
+import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadMXBean;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
+import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -110,6 +113,45 @@ public void reconnectPerformed(PinpointSocket socket) {
Assert.assertTrue(reconnectPerformed.get());
}
+
+ // it takes very long time.
+ // @Test
+ @Ignore
+ public void reconnectStressTest() throws IOException, InterruptedException {
+ int count = 3;
+
+ ThreadMXBean tbean = ManagementFactory.getThreadMXBean();
+
+ int threadCount = tbean.getThreadCount();
+ for (int i = 0; i < count; i++) {
+ logger.info((i + 1) + "th's start.");
+
+ PinpointServerSocket serverSocket = PinpointRPCTestUtils.createServerSocket(bindPort, new TestSeverMessageListener());
+ PinpointSocket socket = socketFactory.connect("localhost", bindPort);
+ PinpointRPCTestUtils.close(serverSocket);
+
+ logger.info("server.close()---------------------------");
+ Thread.sleep(10000);
+
+ serverSocket = PinpointRPCTestUtils.createServerSocket(bindPort, new TestSeverMessageListener());
+ logger.info("bind server---------------------------");
+
+ Thread.sleep(10000);
+ logger.info("request server---------------------------");
+ byte[] randomByte = TestByteUtils.createRandomByte(10);
+ byte[] response = PinpointRPCTestUtils.request(socket, randomByte);
+
+ Assert.assertArrayEquals(randomByte, response);
+
+ PinpointRPCTestUtils.close(socket);
+ PinpointRPCTestUtils.close(serverSocket);
+ }
+
+ Thread.sleep(10000);
+
+ Assert.assertEquals(threadCount, tbean.getThreadCount());
+ }
+
@Test
public void scheduledConnect() throws IOException, InterruptedException {
| train | train | "2015-01-26T07:53:18" | "2015-01-26T09:20:06Z" | koo-taejin | test |
pinpoint-apm/pinpoint/173_174 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/173 | pinpoint-apm/pinpoint/174 | [
"timestamp(timedelta=32.0, similarity=0.9506279071029448)"
] | 9c095f8dce5fa6d2a63af39e85097bf9ca8a1dc3 | 5cb1c2485bc738ada1acfcbee64f45145859e8ea | [] | [] | "2015-02-12T06:09:25Z" | [
"enhancement"
] | Add pinpoint version to system properties while bootstrap start | [
"bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/PinpointBootStrap.java",
"bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/ProfilerLibClass.java"
] | [
"bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/PinpointBootStrap.java",
"bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/ProfilerLibClass.java"
] | [] | diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/PinpointBootStrap.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/PinpointBootStrap.java
index 4deb31928844..3f64842b1c5a 100644
--- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/PinpointBootStrap.java
+++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/PinpointBootStrap.java
@@ -30,6 +30,7 @@
import com.navercorp.pinpoint.bootstrap.util.IdValidateUtils;
import com.navercorp.pinpoint.common.PinpointConstants;
import com.navercorp.pinpoint.common.ServiceTypeProviderLoader;
+import com.navercorp.pinpoint.common.Version;
import com.navercorp.pinpoint.common.util.BytesUtils;
import com.navercorp.pinpoint.common.util.SimpleProperty;
import com.navercorp.pinpoint.common.util.SystemProperty;
@@ -106,6 +107,8 @@ public static void premain(String agentArgs, Instrumentation instrumentation) {
// set the path of log file as a system property
saveLogFilePath(classPathResolver);
+
+ savePinpointVersion();
try {
// Is it right to load the configuration in the bootstrap?
@@ -229,6 +232,11 @@ private static void saveLogFilePath(ClassPathResolver classPathResolver) {
SYSTEM_PROPERTY.setProperty(ProductInfo.NAME + ".log", agentLogFilePath);
}
+
+ private static void savePinpointVersion() {
+ logger.info("pinpoint version:" + Version.VERSION);
+ SYSTEM_PROPERTY.setProperty(ProductInfo.NAME + ".version", Version.VERSION);
+ }
private static String getConfigPath(ClassPathResolver classPathResolver) {
final String configName = ProductInfo.NAME + ".config";
diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/ProfilerLibClass.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/ProfilerLibClass.java
index 26b9cc5dc98b..c8a9b3bf3134 100644
--- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/ProfilerLibClass.java
+++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/ProfilerLibClass.java
@@ -32,7 +32,8 @@ public class ProfilerLibClass {
"com.google.common",
"org.apache.commons.lang",
"org.apache.log4j",
- "com.codahale.metrics"
+ "com.codahale.metrics",
+ "com.nhncorp.nelo2"
};
public boolean onLoadClass(String clazzName) {
| null | test | train | "2015-02-11T08:08:21" | "2015-02-12T02:17:19Z" | minwoo-jung | test |
|
pinpoint-apm/pinpoint/215_222 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/215 | pinpoint-apm/pinpoint/222 | [
"timestamp(timedelta=11044.0, similarity=0.8815885731887749)"
] | f101d233a2706443085010e78854102ad50f0867 | 3435c5300d43b0455f9feb9f5f08171e27404dfb | [
"Making further modifications, It would be better for `PinpointBootstrap` to govern the agent's lifecycle (ie. start/stop methods).\n"
] | [] | "2015-03-10T02:54:21Z" | [
"enhancement"
] | Sending server meta data should be separated from the agent's lifecycle | The agent's lifecycle (and sending agent information) is currently controlled by plugins. Each plugin must specify if it will control the agent's lifecycle, and call `Agent.start()` manually if it does.
For example, a Tomcat 6 application is modified to invoke `Agent.start()` after `org.apache.catalina.core.StandardService.start()` method completes, and only then would the agent sends its information along with the server's meta data.
The agent's information should be sent regardless of the enclosing application's status, and this requires adding a way for the application to notify that it has finished gathering the server's meta data.
| [
"bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/context/ServerMetaDataHolder.java",
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardServiceStartInterceptor.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInfoSender.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolder.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/util/ApplicationServerTypeResolver.java"
] | [
"bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/context/ServerMetaDataHolder.java",
"plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardServiceStartInterceptor.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInfoSender.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolder.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/util/ApplicationServerTypeResolver.java"
] | [
"profiler/src/main/java/com/navercorp/pinpoint/test/PluginTestAgent.java",
"profiler/src/main/java/com/navercorp/pinpoint/test/TestableServerMetaDataListener.java",
"profiler/src/main/java/com/navercorp/pinpoint/test/junit4/BasePinpointTest.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/AgentInfoSenderTest.java",
"profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolderTest.java"
] | diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/context/ServerMetaDataHolder.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/context/ServerMetaDataHolder.java
index e6be6dc7f6a0..a46ba77f9498 100644
--- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/context/ServerMetaDataHolder.java
+++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/context/ServerMetaDataHolder.java
@@ -22,11 +22,22 @@
* @author hyungil.jeong
*/
public interface ServerMetaDataHolder {
+
void setServerName(String serverName);
void addConnector(String protocol, int port);
void addServiceInfo(String serviceName, List<String> serviceLibs);
- ServerMetaData getServerMetaData();
+ void addListener(ServerMetaDataListener listener);
+
+ void removeListener(ServerMetaDataListener listener);
+
+ void publishServerMetaData();
+
+ public interface ServerMetaDataListener {
+
+ public void publishServerMetaData(ServerMetaData serverMetaData);
+
+ }
}
diff --git a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardServiceStartInterceptor.java b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardServiceStartInterceptor.java
index 7ba9c3e1ee95..0be81c2beee8 100644
--- a/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardServiceStartInterceptor.java
+++ b/plugins/tomcat/src/main/java/com/navercorp/pinpoint/plugin/tomcat/interceptor/StandardServiceStartInterceptor.java
@@ -51,5 +51,7 @@ public void after(Object target, Object[] args, Object result, Throwable throwab
String serverInfo = ServerInfo.getServerInfo();
this.traceContext.getServerMetaDataHolder().setServerName(serverInfo);
+ // Service started. Publish server meta data.
+ this.traceContext.getServerMetaDataHolder().publishServerMetaData();
}
}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInfoSender.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInfoSender.java
index b8e41f5a55c8..c8f76716f23a 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInfoSender.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInfoSender.java
@@ -30,7 +30,7 @@
import org.slf4j.LoggerFactory;
import com.navercorp.pinpoint.bootstrap.context.ServerMetaData;
-import com.navercorp.pinpoint.bootstrap.context.ServerMetaDataHolder;
+import com.navercorp.pinpoint.bootstrap.context.ServerMetaDataHolder.ServerMetaDataListener;
import com.navercorp.pinpoint.bootstrap.context.ServiceInfo;
import com.navercorp.pinpoint.common.Version;
import com.navercorp.pinpoint.common.util.PinpointThreadFactory;
@@ -45,7 +45,7 @@
* @author koo.taejin
* @author hyungil.jeong
*/
-public class AgentInfoSender {
+public class AgentInfoSender implements ServerMetaDataListener {
private static final Logger LOGGER = LoggerFactory.getLogger(AgentInfoSender.class);
private static final ThreadFactory THREAD_FACTORY = new PinpointThreadFactory("Pinpoint-agentInfo-sender", true);
@@ -54,9 +54,8 @@ public class AgentInfoSender {
private final long agentInfoSendIntervalMs;
private final EnhancedDataSender dataSender;
private final AgentInformation agentInformation;
- private final ServerMetaDataHolder serverMetaDataHolder;
- public AgentInfoSender(EnhancedDataSender dataSender, long agentInfoSendIntervalMs, AgentInformation agentInformation, ServerMetaDataHolder serverMetaDataHolder) {
+ public AgentInfoSender(EnhancedDataSender dataSender, long agentInfoSendIntervalMs, AgentInformation agentInformation) {
if (dataSender == null) {
throw new NullPointerException("dataSender must not be null");
}
@@ -66,7 +65,6 @@ public AgentInfoSender(EnhancedDataSender dataSender, long agentInfoSendInterval
this.agentInfoSendIntervalMs = agentInfoSendIntervalMs;
this.dataSender = dataSender;
this.agentInformation = agentInformation;
- this.serverMetaDataHolder = serverMetaDataHolder;
}
public void start() {
@@ -74,20 +72,43 @@ public void start() {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("AgentInfoSender started. Sending startup information to Pinpoint server via {}. agentInfo={}", dataSender.getClass().getSimpleName(), agentInfo);
}
+ send(agentInfo);
+ }
+
+ @Override
+ public void publishServerMetaData(ServerMetaData serverMetaData) {
+ final TAgentInfo agentInfo = createTAgentInfo(serverMetaData);
+ if (LOGGER.isInfoEnabled()) {
+ LOGGER.info("Sending AgentInfo with ServerMetaData. {}", agentInfo);
+ }
+ send(agentInfo);
+ }
+
+ private void send(final TAgentInfo agentInfo) {
final AgentInfoSendRunnable agentInfoSendJob = new AgentInfoSendRunnable(agentInfo);
new AgentInfoSendRunnableWrapper(agentInfoSendJob).repeatWithFixedDelay(EXECUTOR_SERVICE, 0, this.agentInfoSendIntervalMs, TimeUnit.MILLISECONDS);
}
private TAgentInfo createTAgentInfo() {
- final ServerMetaData serverMetaData = this.serverMetaDataHolder.getServerMetaData();
-
+ final TAgentInfo agentInfo = new TAgentInfo();
+ agentInfo.setIp(this.agentInformation.getHostIp());
+ agentInfo.setHostname(this.agentInformation.getMachineName());
+ agentInfo.setPorts("");
+ agentInfo.setAgentId(this.agentInformation.getAgentId());
+ agentInfo.setApplicationName(this.agentInformation.getApplicationName());
+ agentInfo.setPid(this.agentInformation.getPid());
+ agentInfo.setStartTimestamp(this.agentInformation.getStartTime());
+ agentInfo.setServiceType(this.agentInformation.getServerType().getCode());
+ agentInfo.setVersion(Version.VERSION);
+ return agentInfo;
+ }
+
+ private TAgentInfo createTAgentInfo(final ServerMetaData serverMetaData) {
final StringBuilder ports = new StringBuilder();
-
for (Entry<Integer, String> entry : serverMetaData.getConnectors().entrySet()) {
ports.append(" ");
ports.append(entry.getKey());
}
-
final TAgentInfo agentInfo = new TAgentInfo();
agentInfo.setIp(this.agentInformation.getHostIp());
agentInfo.setHostname(this.agentInformation.getMachineName());
@@ -98,9 +119,7 @@ private TAgentInfo createTAgentInfo() {
agentInfo.setStartTimestamp(this.agentInformation.getStartTime());
agentInfo.setServiceType(this.agentInformation.getServerType().getCode());
agentInfo.setVersion(Version.VERSION);
-
agentInfo.setServerMetaData(createTServiceInfo(serverMetaData));
-
return agentInfo;
}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java
index d490ed62a8e0..1a6a5cc1beef 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java
@@ -152,9 +152,9 @@ public DefaultAgent(String agentArgs, Instrumentation instrumentation, ProfilerC
List<DefaultProfilerPluginContext> pluginContexts = loadProfilerPlugins(profilerConfig, pluginJars);
String applicationServerTypeString = profilerConfig.getApplicationServerType();
- ServiceType applicationServerType = serviceTypeRegistryService.findServiceTypeByName(applicationServerTypeString);
+ ServiceType applicationServerType = this.serviceTypeRegistryService.findServiceTypeByName(applicationServerTypeString);
- final ApplicationServerTypeResolver typeResolver = new ApplicationServerTypeResolver(pluginContexts, applicationServerType, serviceTypeRegistryService);
+ final ApplicationServerTypeResolver typeResolver = new ApplicationServerTypeResolver(pluginContexts, applicationServerType, this.serviceTypeRegistryService);
if (!typeResolver.resolve()) {
throw new PinpointException("ApplicationServerType not found.");
}
@@ -182,7 +182,8 @@ public DefaultAgent(String agentArgs, Instrumentation instrumentation, ProfilerC
this.traceContext = createTraceContext(agentInformation.getServerType());
- this.agentInfoSender = new AgentInfoSender(tcpDataSender, profilerConfig.getAgentInfoSendRetryInterval(), this.agentInformation, this.serverMetaDataHolder);
+ this.agentInfoSender = new AgentInfoSender(tcpDataSender, profilerConfig.getAgentInfoSendRetryInterval(), this.agentInformation);
+ this.serverMetaDataHolder.addListener(this.agentInfoSender);
this.agentStatMonitor = new AgentStatMonitor(this.statDataSender, this.agentInformation.getAgentId(), this.agentInformation.getStartTime());
@@ -195,14 +196,7 @@ public DefaultAgent(String agentArgs, Instrumentation instrumentation, ProfilerC
preLoadClass();
- /**
- * FIXME
- * In case of Tomcat, com.navercorp.pinpoint.profiler.modifier.tomcat.interceptor.CatalinaAwaitInterceptor invokes start() method
- * before entering await() method of org.apache.catalina.startup.Catalina. But for other applications, it must be invoked directly.
- */
- if (typeResolver.isManuallyStartupRequired()) {
- start();
- }
+ start();
}
private CommandDispatcher createCommandDispatcher() {
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolder.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolder.java
index 55effe32be25..0b9f34830219 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolder.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolder.java
@@ -33,6 +33,8 @@
* @author hyungil.jeong
*/
public class DefaultServerMetaDataHolder implements ServerMetaDataHolder {
+
+ private final List<ServerMetaDataListener> listeners;
protected String serverName;
private final List<String> vmArgs;
@@ -40,6 +42,7 @@ public class DefaultServerMetaDataHolder implements ServerMetaDataHolder {
protected final Queue<ServiceInfo> serviceInfos = new ConcurrentLinkedQueue<ServiceInfo>();
public DefaultServerMetaDataHolder(List<String> vmArgs) {
+ this.listeners = new ArrayList<ServerMetaDataListener>();
this.vmArgs = vmArgs;
}
@@ -60,7 +63,24 @@ public void addServiceInfo(String serviceName, List<String> serviceLibs) {
}
@Override
- public ServerMetaData getServerMetaData() {
+ public void addListener(ServerMetaDataListener listener) {
+ this.listeners.add(listener);
+ }
+
+ @Override
+ public void removeListener(ServerMetaDataListener listener) {
+ this.listeners.remove(listener);
+ }
+
+ @Override
+ public void publishServerMetaData() {
+ final ServerMetaData serverMetaData = createServerMetaData();
+ for (ServerMetaDataListener listener : this.listeners) {
+ listener.publishServerMetaData(serverMetaData);
+ }
+ }
+
+ private ServerMetaData createServerMetaData() {
String serverName = this.serverName == null ? "" : this.serverName;
List<String> vmArgs =
this.vmArgs == null ? Collections.<String>emptyList() : new ArrayList<String>(this.vmArgs);
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/ApplicationServerTypeResolver.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/ApplicationServerTypeResolver.java
index b9b9b7d74b03..6230c47635c3 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/ApplicationServerTypeResolver.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/ApplicationServerTypeResolver.java
@@ -19,12 +19,12 @@
import java.util.ArrayList;
import java.util.List;
-import com.navercorp.pinpoint.common.service.ServiceTypeRegistryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.navercorp.pinpoint.bootstrap.plugin.ServerTypeDetector;
import com.navercorp.pinpoint.common.ServiceType;
+import com.navercorp.pinpoint.common.service.ServiceTypeRegistryService;
import com.navercorp.pinpoint.profiler.plugin.DefaultProfilerPluginContext;
/**
@@ -40,27 +40,19 @@ public class ApplicationServerTypeResolver {
private final List<ServerTypeDetector> detectors = new ArrayList<ServerTypeDetector>();
private final ServiceTypeRegistryService serviceTypeRegistryService;
- /**
- * If we have to invoke startup() during agent initialization.
- * Some service types like BLOC or STAND_ALONE don't have an acceptor to do this.
- */
- private boolean manuallyStartupRequired = true;
public ApplicationServerTypeResolver(List<DefaultProfilerPluginContext> plugins, ServiceType defaultType, ServiceTypeRegistryService serviceTypeRegistryService) {
if (serviceTypeRegistryService == null) {
throw new NullPointerException("serviceTypeRegistryService must not be null");
}
-
+ this.serviceTypeRegistryService = serviceTypeRegistryService;
this.defaultType = defaultType;
for (DefaultProfilerPluginContext context : plugins) {
detectors.addAll(context.getServerTypeDetectors());
}
-
- this.serviceTypeRegistryService = serviceTypeRegistryService;
}
-
public String[] getServerLibPath() {
return new String[0];
}
@@ -69,10 +61,6 @@ public ServiceType getServerType() {
return serverType;
}
- public boolean isManuallyStartupRequired() {
- return manuallyStartupRequired;
- }
-
public boolean resolve() {
String serverType = null;
| diff --git a/profiler/src/main/java/com/navercorp/pinpoint/test/PluginTestAgent.java b/profiler/src/main/java/com/navercorp/pinpoint/test/PluginTestAgent.java
index 45783d9ba5b1..2eb9896f4611 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/test/PluginTestAgent.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/test/PluginTestAgent.java
@@ -54,6 +54,8 @@
*/
public class PluginTestAgent extends DefaultAgent implements PluginTestVerifier {
+ private TestableServerMetaDataListener serverMetaDataListener;
+
public PluginTestAgent(String agentArgs, Instrumentation instrumentation, ProfilerConfig profilerConfig, URL[] pluginJars) {
super(agentArgs, instrumentation, profilerConfig, pluginJars);
PluginTestVerifierHolder.setInstance(this);
@@ -88,7 +90,10 @@ protected EnhancedDataSender createTcpDataSender(CommandDispatcher commandDispat
@Override
protected ServerMetaDataHolder createServerMetaDataHolder() {
List<String> vmArgs = RuntimeMXBeanUtils.getVmArgs();
- return new ResettableServerMetaDataHolder(vmArgs);
+ ServerMetaDataHolder serverMetaDataHolder = new ResettableServerMetaDataHolder(vmArgs);
+ this.serverMetaDataListener = new TestableServerMetaDataListener();
+ serverMetaDataHolder.addListener(this.serverMetaDataListener);
+ return serverMetaDataHolder;
}
@Override
@@ -102,7 +107,7 @@ public void verifyServerType(ServiceType serviceType) {
@Override
public void verifyServerInfo(String expected) {
- String actualName = getTraceContext().getServerMetaDataHolder().getServerMetaData().getServerInfo();
+ String actualName = this.serverMetaDataListener.getServerMetaData().getServerInfo();
if (!actualName.equals(expected)) {
throw new AssertionError("Expected server name [" + expected + "] but was [" + actualName + "]");
@@ -111,7 +116,7 @@ public void verifyServerInfo(String expected) {
@Override
public void verifyConnector(String protocol, int port) {
- Map<Integer, String> connectorMap = getTraceContext().getServerMetaDataHolder().getServerMetaData().getConnectors();
+ Map<Integer, String> connectorMap = this.serverMetaDataListener.getServerMetaData().getConnectors();
String actualProtocol = connectorMap.get(port);
if (actualProtocol == null || !actualProtocol.equals(protocol)) {
@@ -121,7 +126,7 @@ public void verifyConnector(String protocol, int port) {
@Override
public void verifyService(String name, List<String> libs) {
- List<ServiceInfo> serviceInfos = getTraceContext().getServerMetaDataHolder().getServerMetaData().getServiceInfos();
+ List<ServiceInfo> serviceInfos = this.serverMetaDataListener.getServerMetaData().getServiceInfos();
for (ServiceInfo serviceInfo : serviceInfos) {
if (serviceInfo.getServiceName().equals(name)) {
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/test/TestableServerMetaDataListener.java b/profiler/src/main/java/com/navercorp/pinpoint/test/TestableServerMetaDataListener.java
new file mode 100644
index 000000000000..7795c982f102
--- /dev/null
+++ b/profiler/src/main/java/com/navercorp/pinpoint/test/TestableServerMetaDataListener.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2015 NAVER Corp.
+ *
+ * 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.
+ */
+
+package com.navercorp.pinpoint.test;
+
+import com.navercorp.pinpoint.bootstrap.context.ServerMetaData;
+import com.navercorp.pinpoint.bootstrap.context.ServerMetaDataHolder.ServerMetaDataListener;
+
+/**
+ * @author HyunGil Jeong
+ */
+public class TestableServerMetaDataListener implements ServerMetaDataListener {
+
+ private volatile ServerMetaData serverMetaData;
+
+ @Override
+ public void publishServerMetaData(ServerMetaData serverMetaData) {
+ this.serverMetaData = serverMetaData;
+ }
+
+ public ServerMetaData getServerMetaData() {
+ return this.serverMetaData;
+ }
+
+}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/test/junit4/BasePinpointTest.java b/profiler/src/main/java/com/navercorp/pinpoint/test/junit4/BasePinpointTest.java
index 9681fa517537..d32b53ed172b 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/test/junit4/BasePinpointTest.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/test/junit4/BasePinpointTest.java
@@ -23,6 +23,8 @@
import com.navercorp.pinpoint.test.ListenableDataSender;
import com.navercorp.pinpoint.test.MockAgent;
import com.navercorp.pinpoint.test.ResettableServerMetaDataHolder;
+import com.navercorp.pinpoint.test.TestableServerMetaDataListener;
+
import org.apache.thrift.TBase;
import org.junit.runner.RunWith;
@@ -42,6 +44,7 @@ public abstract class BasePinpointTest {
private volatile TBaseRecorder<? extends TBase<?, ?>> tBaseRecorder;
private volatile ServerMetaDataHolder serverMetaDataHolder;
+ private final TestableServerMetaDataListener listener = new TestableServerMetaDataListener();
protected List<SpanEventBo> getCurrentSpanEvents() {
List<SpanEventBo> spanEvents = new ArrayList<SpanEventBo>();
@@ -65,7 +68,7 @@ protected List<SpanBo> getCurrentRootSpans() {
}
protected ServerMetaData getServerMetaData() {
- return this.serverMetaDataHolder.getServerMetaData();
+ return this.listener.getServerMetaData();
}
private void setTBaseRecorder(TBaseRecorder tBaseRecorder) {
@@ -99,5 +102,6 @@ public boolean handleSend(TBase<?, ?> data) {
ResettableServerMetaDataHolder resettableServerMetaDataHolder = (ResettableServerMetaDataHolder) serverMetaDataHolder;
this.setServerMetaDataHolder(resettableServerMetaDataHolder);
}
+ this.serverMetaDataHolder.addListener(this.listener);
}
}
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/AgentInfoSenderTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/AgentInfoSenderTest.java
index 72a5abd44e9e..3f0fbaac526a 100644
--- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/AgentInfoSenderTest.java
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/AgentInfoSenderTest.java
@@ -19,18 +19,30 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
+import java.util.ArrayList;
import java.util.Collections;
+import java.util.List;
import java.util.Map;
+import java.util.Queue;
import java.util.Random;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
+import com.navercorp.pinpoint.bootstrap.context.ServerMetaData;
+import com.navercorp.pinpoint.bootstrap.context.ServerMetaDataHolder;
+import com.navercorp.pinpoint.bootstrap.context.ServiceInfo;
import com.navercorp.pinpoint.common.ServiceType;
+
import org.apache.thrift.TException;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.navercorp.pinpoint.bootstrap.context.ServerMetaDataHolder;
+import com.navercorp.pinpoint.profiler.context.DefaultServerMetaData;
import com.navercorp.pinpoint.profiler.context.DefaultServerMetaDataHolder;
import com.navercorp.pinpoint.profiler.sender.TcpDataSender;
import com.navercorp.pinpoint.rpc.PinpointSocketException;
@@ -68,7 +80,7 @@ public void agentInfoShouldBeSent() throws InterruptedException {
PinpointSocket socket = createPinpointSocket(HOST, PORT, socketFactory);
TcpDataSender sender = new TcpDataSender(socket);
- AgentInfoSender agentInfoSender = new AgentInfoSender(sender, agentInfoSendRetryIntervalMs, getAgentInfo(), getServerMetaDataHolder());
+ AgentInfoSender agentInfoSender = new AgentInfoSender(sender, agentInfoSendRetryIntervalMs, getAgentInfo());
try {
agentInfoSender.start();
@@ -95,7 +107,7 @@ public void agentInfoShouldRetryUntilSuccess() throws InterruptedException {
PinpointSocket socket = createPinpointSocket(HOST, PORT, socketFactory);
TcpDataSender dataSender = new TcpDataSender(socket);
- AgentInfoSender agentInfoSender = new AgentInfoSender(dataSender, agentInfoSendRetryIntervalMs, getAgentInfo(), getServerMetaDataHolder());
+ AgentInfoSender agentInfoSender = new AgentInfoSender(dataSender, agentInfoSendRetryIntervalMs, getAgentInfo());
try {
agentInfoSender.start();
@@ -119,7 +131,7 @@ public void agentInfoShouldBeSentOnlyOnceEvenAfterReconnect() throws Interrupted
PinpointSocket socket = createPinpointSocket(HOST, PORT, socketFactory);
TcpDataSender dataSender = new TcpDataSender(socket);
- AgentInfoSender agentInfoSender = new AgentInfoSender(dataSender, agentInfoSendRetryIntervalMs, getAgentInfo(), getServerMetaDataHolder());
+ AgentInfoSender agentInfoSender = new AgentInfoSender(dataSender, agentInfoSendRetryIntervalMs, getAgentInfo());
try {
agentInfoSender.start();
@@ -150,7 +162,7 @@ public void agentInfoShouldKeepRetrying() throws InterruptedException {
PinpointSocket socket = createPinpointSocket(HOST, PORT, socketFactory);
TcpDataSender dataSender = new TcpDataSender(socket);
- AgentInfoSender agentInfoSender = new AgentInfoSender(dataSender, agentInfoSendRetryIntervalMs, getAgentInfo(), getServerMetaDataHolder());
+ AgentInfoSender agentInfoSender = new AgentInfoSender(dataSender, agentInfoSendRetryIntervalMs, getAgentInfo());
try {
agentInfoSender.start();
@@ -161,6 +173,99 @@ public void agentInfoShouldKeepRetrying() throws InterruptedException {
assertTrue(requestCount.get() >= minimumAgentInfoSendRetryCount);
assertEquals(0, successCount.get());
}
+
+ @Test
+ public void serverMetaDataShouldBeSentOnPublish() throws InterruptedException {
+ // Given
+ final AtomicInteger requestCount = new AtomicInteger();
+ final AtomicInteger successCount = new AtomicInteger();
+ final long agentInfoSendRetryIntervalMs = 1000L;
+
+ ResponseServerMessageListener serverListener = new ResponseServerMessageListener(requestCount, successCount);
+
+ PinpointServerAcceptor serverAcceptor = createServerAcceptor(serverListener);
+
+ PinpointSocketFactory socketFactory = createPinpointSocketFactory();
+ PinpointSocket socket = createPinpointSocket(HOST, PORT, socketFactory);
+
+ TcpDataSender sender = new TcpDataSender(socket);
+ AgentInfoSender agentInfoSender = new AgentInfoSender(sender, agentInfoSendRetryIntervalMs, getAgentInfo());
+ final List<ServerMetaData> serverMetaDataObjects = new ArrayList<ServerMetaData>();
+ serverMetaDataObjects.add(new DefaultServerMetaData("server1", Collections.<String>emptyList(), Collections.<Integer, String>emptyMap(), Collections.<ServiceInfo>emptyList()));
+ serverMetaDataObjects.add(new DefaultServerMetaData("server2", Collections.<String>emptyList(), Collections.<Integer, String>emptyMap(), Collections.<ServiceInfo>emptyList()));
+ serverMetaDataObjects.add(new DefaultServerMetaData("server3", Collections.<String>emptyList(), Collections.<Integer, String>emptyMap(), Collections.<ServiceInfo>emptyList()));
+ serverMetaDataObjects.add(new DefaultServerMetaData("server4", Collections.<String>emptyList(), Collections.<Integer, String>emptyMap(), Collections.<ServiceInfo>emptyList()));
+ serverMetaDataObjects.add(new DefaultServerMetaData("server5", Collections.<String>emptyList(), Collections.<Integer, String>emptyMap(), Collections.<ServiceInfo>emptyList()));
+ // When
+ try {
+ for (ServerMetaData serverMetaData : serverMetaDataObjects) {
+ agentInfoSender.publishServerMetaData(serverMetaData);
+ }
+ Thread.sleep(10000L);
+ } finally {
+ closeAll(serverAcceptor, agentInfoSender, socket, socketFactory);
+ }
+ // Then
+ assertEquals(5, requestCount.get());
+ assertEquals(5, successCount.get());
+ }
+
+ @Test
+ public void serverMetaDataCouldBePublishedFromMultipleThreads() throws InterruptedException {
+ // Given
+ final AtomicInteger requestCount = new AtomicInteger();
+ final AtomicInteger successCount = new AtomicInteger();
+ final long agentInfoSendRetryIntervalMs = 1000L;
+ final int threadCount = 50;
+ final CountDownLatch initLatch = new CountDownLatch(threadCount);
+ final CountDownLatch startLatch = new CountDownLatch(1);
+ final CountDownLatch endLatch = new CountDownLatch(threadCount);
+ final ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
+ final Queue<Throwable> exceptions = new ConcurrentLinkedQueue<Throwable>();
+
+ ResponseServerMessageListener delayedServerListener = new ResponseServerMessageListener(requestCount, successCount);
+
+ PinpointServerAcceptor serverAcceptor = createServerAcceptor(delayedServerListener);
+
+ PinpointSocketFactory socketFactory = createPinpointSocketFactory();
+ PinpointSocket socket = createPinpointSocket(HOST, PORT, socketFactory);
+
+ TcpDataSender sender = new TcpDataSender(socket);
+ AgentInfoSender agentInfoSender = new AgentInfoSender(sender, agentInfoSendRetryIntervalMs, getAgentInfo());
+ final ServerMetaDataHolder metaDataContext = new DefaultServerMetaDataHolder(Collections.<String>emptyList());
+ metaDataContext.addListener(agentInfoSender);
+ // When
+ for (int i = 0; i < threadCount; ++i) {
+ executorService.submit(new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ initLatch.countDown();
+ try {
+ startLatch.await();
+ metaDataContext.publishServerMetaData();
+ } catch (final Throwable t) {
+ exceptions.add(t);
+ } finally {
+ endLatch.countDown();
+ }
+ return null;
+ }
+ });
+ }
+ initLatch.await();
+ startLatch.countDown();
+ endLatch.await();
+ executorService.shutdown();
+ try {
+ Thread.sleep(10000L);
+ } finally {
+ closeAll(serverAcceptor, agentInfoSender, socket, socketFactory);
+ }
+ // Then
+ assertTrue("Failed with exceptions : " + exceptions, exceptions.isEmpty());
+ assertEquals(threadCount, requestCount.get());
+ assertEquals(threadCount, successCount.get());
+ }
public void reconnectionStressTest() throws InterruptedException {
final AtomicInteger requestCount = new AtomicInteger();
@@ -176,7 +281,7 @@ public void reconnectionStressTest() throws InterruptedException {
PinpointSocket socket = createPinpointSocket(HOST, PORT, socketFactory);
TcpDataSender dataSender = new TcpDataSender(socket);
- AgentInfoSender agentInfoSender = new AgentInfoSender(dataSender, agentInfoSendRetryIntervalMs, getAgentInfo(), getServerMetaDataHolder());
+ AgentInfoSender agentInfoSender = new AgentInfoSender(dataSender, agentInfoSendRetryIntervalMs, getAgentInfo());
long startTime = System.currentTimeMillis();
@@ -242,11 +347,6 @@ private AgentInformation getAgentInfo() {
return agentInfo;
}
- private ServerMetaDataHolder getServerMetaDataHolder() {
- ServerMetaDataHolder serverMetaDataHolder = new DefaultServerMetaDataHolder(Collections.<String>emptyList());
- return serverMetaDataHolder;
- }
-
class ResponseServerMessageListener implements ServerMessageListener {
private final AtomicInteger requestCount;
private final AtomicInteger successCount;
@@ -295,7 +395,7 @@ public void handleRequest(RequestPacket requestPacket, PinpointServer pinpointSe
}
@Override
- public HandshakeResponseCode handleHandshake(Map arg0) {
+ public HandshakeResponseCode handleHandshake(@SuppressWarnings("rawtypes") Map arg0) {
return HandshakeResponseType.Success.DUPLEX_COMMUNICATION;
}
}
diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolderTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolderTest.java
index c818c8eea016..2d51b4582380 100644
--- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolderTest.java
+++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultServerMetaDataHolderTest.java
@@ -36,6 +36,7 @@
import com.navercorp.pinpoint.bootstrap.context.ServerMetaData;
import com.navercorp.pinpoint.bootstrap.context.ServerMetaDataHolder;
import com.navercorp.pinpoint.profiler.context.DefaultServerMetaDataHolder;
+import com.navercorp.pinpoint.test.TestableServerMetaDataListener;
/**
* @author hyungil.jeong
@@ -48,7 +49,7 @@ public class DefaultServerMetaDataHolderTest {
private static final List<String> VM_ARGS = Arrays.asList("testVmArgs");
private ExecutorService executorService;
-
+
@Before
public void setUp() {
this.executorService = Executors.newFixedThreadPool(THREAD_COUNT);
@@ -68,7 +69,9 @@ public void testRaceConditionWhenAddingServiceInfo() throws InterruptedException
final Queue<Throwable> exceptions = new ConcurrentLinkedQueue<Throwable>();
final String serviceName = "/test";
+ final TestableServerMetaDataListener listener = new TestableServerMetaDataListener();
final ServerMetaDataHolder metaDataContext = new DefaultServerMetaDataHolder(VM_ARGS);
+ metaDataContext.addListener(listener);
metaDataContext.setServerName(SERVER_INFO);
// When
for (int i = 0; i < THREAD_COUNT; ++i) {
@@ -80,6 +83,7 @@ public Void call() throws Exception {
try {
startLatch.await();
metaDataContext.addServiceInfo(serviceName, serviceLibs);
+ metaDataContext.publishServerMetaData();
} catch (final Throwable t) {
exceptions.add(t);
} finally {
@@ -94,7 +98,7 @@ public Void call() throws Exception {
endLatch.await();
// Then
assertTrue("Failed with exceptions : " + exceptions, exceptions.isEmpty());
- ServerMetaData metaData = metaDataContext.getServerMetaData();
+ ServerMetaData metaData = listener.getServerMetaData();
assertEquals(metaData.getServerInfo(), SERVER_INFO);
assertEquals(metaData.getVmArgs(), VM_ARGS);
assertEquals(metaData.getServiceInfos().size(), THREAD_COUNT);
@@ -108,7 +112,9 @@ public void testRaceConditionWhenAddingAndInteratingServiceInfo() throws Interru
final CountDownLatch endLatch = new CountDownLatch(THREAD_COUNT);
final Queue<Throwable> exceptions = new ConcurrentLinkedQueue<Throwable>();
+ final TestableServerMetaDataListener listener = new TestableServerMetaDataListener();
final ServerMetaDataHolder metaDataContext = new DefaultServerMetaDataHolder(VM_ARGS);
+ metaDataContext.addListener(listener);
metaDataContext.setServerName(SERVER_INFO);
// When
final List<ServerMetaData> serverMetaDatas = new Vector<ServerMetaData>(THREAD_COUNT/2);
@@ -123,6 +129,7 @@ public Void call() throws Exception {
try {
startLatch.await();
metaDataContext.addServiceInfo(serviceName, serviceLibs);
+ metaDataContext.publishServerMetaData();
} catch (Throwable t) {
exceptions.add(t);
} finally {
@@ -138,7 +145,7 @@ public Void call() throws Exception {
initLatch.countDown();
try {
startLatch.await();
- ServerMetaData serverMetaData = metaDataContext.getServerMetaData();
+ ServerMetaData serverMetaData = listener.getServerMetaData();
serverMetaDatas.add(serverMetaData);
} catch (Throwable t) {
exceptions.add(t);
@@ -155,11 +162,11 @@ public Void call() throws Exception {
endLatch.await();
// Then
assertTrue("Failed with exceptions : " + exceptions, exceptions.isEmpty());
- ServerMetaData metaData = metaDataContext.getServerMetaData();
+ ServerMetaData metaData = listener.getServerMetaData();
assertEquals(metaData.getServerInfo(), SERVER_INFO);
assertEquals(metaData.getVmArgs(), VM_ARGS);
assertEquals(metaData.getServiceInfos().size(), THREAD_COUNT/2);
assertEquals(serverMetaDatas.size(), THREAD_COUNT/2);
}
-
+
}
| train | train | "2015-03-10T06:57:20" | "2015-03-06T10:11:55Z" | Xylus | test |
iluwatar/java-design-patterns/53_54 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/53 | iluwatar/java-design-patterns/54 | [
"timestamp(timedelta=0.0, similarity=1.0000000000000002)",
"keyword_pr_to_issue"
] | b87918050c4091c9719eeaeef46edb667f83dd70 | 5ffaa138fa1524ad8bf68606898e1f32ffc918a1 | [] | [] | "2015-05-18T06:15:19Z" | [] | Documentation change in DAO pattern | Removed a redundant word and added an Acronym.
| [
"dao/src/main/java/com/iluwatar/App.java"
] | [
"dao/src/main/java/com/iluwatar/App.java"
] | [] | diff --git a/dao/src/main/java/com/iluwatar/App.java b/dao/src/main/java/com/iluwatar/App.java
index 878f7b5bfba7..29578d74ea21 100644
--- a/dao/src/main/java/com/iluwatar/App.java
+++ b/dao/src/main/java/com/iluwatar/App.java
@@ -6,7 +6,7 @@
/**
*
* With the DAO pattern, we can use various method calls to retrieve/add/delete/update data without directly
- * interacting with the data directly. The below example demonstrates basic operations: select, add, update, and delete.
+ * interacting with the data. The below example demonstrates basic operations(CRUD): select, add, update, and delete.
*/
public class App {
| null | train | train | "2015-05-17T21:04:07" | "2015-05-18T05:43:36Z" | hobbyexplorer | train |
iluwatar/java-design-patterns/181_193 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/181 | iluwatar/java-design-patterns/193 | [
"timestamp(timedelta=53733.0, similarity=0.8708915252422907)",
"keyword_pr_to_issue"
] | 3dc6b81962bcfb492752bea1a204ae0ba94c58e5 | 5f40d0a157da6343cc1167725556c8f2a29139c5 | [
"Shouldn't this be replicable in my fork?\n\nI get `This job is running on container-based infrastructure, which does not allow use of 'sudo', setuid and setguid executables.`\n",
"@mafagafogigante Yes that is normal. `sudo` is not yet supported in Travis container environment but as we don't need that we are good to go. I have already migrated my fork to container based infrastructure. But Travis is facing issues downloading dependencies for `naked-objects-intergration` and the build is failing. I need to figure out why is that so. FYI https://travis-ci.org/npathai/java-design-patterns\n",
"@npathai I think this is the same build issue I worked on yesterday, see https://github.com/iluwatar/java-design-patterns/commit/185f296a5b03f16edb62d0023441e89ad4365501. Try to catch up your fork from the master and hopefully the problem is fixed.\n",
"@iluwatar Thanks that solved the issue. It's done. Generating PR.\n",
"I had the same problem of @npathai.\n\nThanks for fixing it.\n"
] | [] | "2015-08-07T07:06:14Z" | [] | Migrate travis build to container based infrastructure | I was viewing build logs when I found out that we are running build on legacy infrastructure and got a notification for migration to container based infrastructure.
[Travis CI - Why migrate to container based infrastructure](http://docs.travis-ci.com/user/migrating-from-legacy/?utm_source=legacy-notice&utm_medium=banner&utm_campaign=legacy-upgrade)
One of the best advantages is faster build times
| [
".travis.yml"
] | [
".travis.yml"
] | [] | diff --git a/.travis.yml b/.travis.yml
index 8ae7361f3b00..e69a17a4f8e1 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -13,4 +13,7 @@ before_install:
- "sh -e /etc/init.d/xvfb start"
after_success:
- - mvn clean test jacoco:report coveralls:report
\ No newline at end of file
+ - mvn clean test jacoco:report coveralls:report
+
+# Migration to container-based infrastructure
+sudo: false
| null | train | train | "2015-08-07T07:23:10" | "2015-07-30T05:47:06Z" | npathai | train |
iluwatar/java-design-patterns/192_196 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/192 | iluwatar/java-design-patterns/196 | [
"timestamp(timedelta=0.0, similarity=0.8427068570942038)",
"keyword_pr_to_issue"
] | 3a0ee1fea5016b57732f58809caf680cd9c64d70 | 588a35077800750a19bcdea935e499e6fe8117f3 | [] | [] | "2015-08-08T13:31:45Z" | [
"type: enhancement"
] | README is ugly and could easily be fixed. | Many lines of the file are HUGE. The longest line is terribly **598** characters long!
Some of us (I can't be the only one) use text editors that work better with reasonable line lengths (70 or 80 characters per line).
Even Git diffs become much better when line lengths are moderate.
Also, the last PR I opened (#191) required me to comment in GitHub a line because the word diff was not marked by GH (I would say because the line is huge).
I am willing to hard wrap the file and will insist on this issue unless you show me a **good** reason why it shouldn't be done.
Thankful for your comprehension and common sense, Bernardo.
| [
"README.md"
] | [
"README.md"
] | [] | diff --git a/README.md b/README.md
index a7390336785f..910e9d485796 100644
--- a/README.md
+++ b/README.md
@@ -307,8 +307,8 @@ are several common situations in which the Proxy pattern is applicable
**Typical Use Case:**
-* Control access to another object
-* Lazy initialization
+* control access to another object
+* lazy initialization
* implement logging
* facilitate network connection
* to count references to an object
@@ -334,7 +334,7 @@ improves the performance of application to great extent.
**Typical Use Case:**
-* When network hits are expensive and time consuming
+* when network hits are expensive and time consuming
* lookups of services are done quite frequently
* large number of services are being used
@@ -541,7 +541,7 @@ this behavior in the common parent class - it is defined once in the Servant.
![alt text](./servant/etc/servant-pattern.png "Servant")
**Applicability:** Use the Servant pattern when
-* When we want some objects to perform a common action and don't want to define this action as a method in every class.
+* when we want some objects to perform a common action and don't want to define this action as a method in every class.
## <a name="null-object">Null Object</a> [↑](#list-of-design-patterns)
**Intent:** In most object-oriented languages, such as Java or C#, references
@@ -556,7 +556,7 @@ Object is very predictable and has no side effects: it does nothing.
![alt text](./null-object/etc/null-object.png "Null Object")
**Applicability:** Use the Null Object pattern when
-* You want to avoid explicit null checks and keep the algorithm elegant and easy to read.
+* you want to avoid explicit null checks and keep the algorithm elegant and easy to read.
## <a name="event-aggregator">Event Aggregator</a> [↑](#list-of-design-patterns)
**Intent:** A system with lots of objects can lead to complexities when a
@@ -569,7 +569,11 @@ allowing clients to register with just the aggregator.
![alt text](./event-aggregator/etc/classes.png "Event Aggregator")
**Applicability:** Use the Event Aggregator pattern when
-* Event Aggregator is a good choice when you have lots of objects that are potential event sources. Rather than have the observer deal with registering with them all, you can centralize the registration logic to the Event Aggregator. As well as simplifying registration, a Event Aggregator also simplifies the memory management issues in using observers.
+* Event Aggregator is a good choice when you have lots of objects that are
+ potential event sources. Rather than have the observer deal with registering
+ with them all, you can centralize the registration logic to the Event
+ Aggregator. As well as simplifying registration, a Event Aggregator also
+ simplifies the memory management issues in using observers.
## <a name="callback">Callback</a> [↑](#list-of-design-patterns)
**Intent:** Callback is a piece of executable code that is passed as an
@@ -579,7 +583,7 @@ at some convenient time.
![alt text](./callback/etc/callback.png "Callback")
**Applicability:** Use the Callback pattern when
-* When some arbitrary synchronous or asynchronous action must be performed after execution of some defined activity.
+* when some arbitrary synchronous or asynchronous action must be performed after execution of some defined activity.
**Real world examples:**
* [CyclicBarrier] (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html#CyclicBarrier%28int,%20java.lang.Runnable%29) constructor can accept callback that will be triggered every time when barrier is tripped.
@@ -604,7 +608,7 @@ only what to do with the resource.
![alt text](./execute-around/etc/execute-around.png "Execute Around")
**Applicability:** Use the Execute Around idiom when
-* You use an API that requires methods to be called in pairs such as open/close or allocate/deallocate.
+* you use an API that requires methods to be called in pairs such as open/close or allocate/deallocate.
## <a name="property">Property</a> [↑](#list-of-design-patterns)
**Intent:** Create hierarchy of objects and new objects using already existing
@@ -667,8 +671,8 @@ order
![alt text](./specification/etc/specification.png "Specification")
**Applicability:** Use the Specification pattern when
-* You need to select a subset of objects based on some criteria, and to refresh the selection at various times
-* You need to check that only suitable objects are used for a certain role (validation)
+* you need to select a subset of objects based on some criteria, and to refresh the selection at various times
+* you need to check that only suitable objects are used for a certain role (validation)
## <a name="tolerant-reader">Tolerant Reader</a> [↑](#list-of-design-patterns)
**Intent:** Tolerant Reader is an integration pattern that helps creating
@@ -679,7 +683,7 @@ changes, the readers must not break.
![alt text](./tolerant-reader/etc/tolerant-reader.png "Tolerant Reader")
**Applicability:** Use the Tolerant Reader pattern when
-* The communication schema can evolve and change and yet the receiving side should not break
+* the communication schema can evolve and change and yet the receiving side should not break
## <a name="model-view-controller">Model-View-Controller</a> [↑](#list-of-design-patterns)
**Intent:** Separate the user interface into three interconnected components:
@@ -701,7 +705,7 @@ logic, which updates all of the views that are affected.
![alt text](./flux/etc/flux.png "Flux")
**Applicability:** Use the Flux pattern when
-* You want to focus on creating explicit and understandable update paths for your application's data, which makes tracing changes during development simpler and makes bugs easier to track down and fix.
+* you want to focus on creating explicit and understandable update paths for your application's data, which makes tracing changes during development simpler and makes bugs easier to track down and fix.
## <a name="double-dispatch">Double Dispatch</a> [↑](#list-of-design-patterns)
**Intent:** Double Dispatch pattern is a way to create maintainable dynamic
@@ -710,7 +714,7 @@ behavior based on receiver and parameter types.
![alt text](./double-dispatch/etc/double-dispatch.png "Double Dispatch")
**Applicability:** Use the Double Dispatch pattern when
-* The dynamic behavior is not defined only based on receiving object's type but also on the receiving method's parameter type.
+* the dynamic behavior is not defined only based on receiving object's type but also on the receiving method's parameter type.
**Real world examples:**
* [ObjectOutputStream](https://docs.oracle.com/javase/8/docs/api/java/io/ObjectOutputStream.html)
@@ -742,7 +746,7 @@ and eliminating the latency of creating new threads.
![alt text](./thread-pool/etc/thread-pool.png "Thread Pool")
**Applicability:** Use the Thread Pool pattern when
-* You have a large number of short-lived tasks to be executed in parallel
+* you have a large number of short-lived tasks to be executed in parallel
## <a name="async-method-invocation">Async Method Invocation</a> [↑](#list-of-design-patterns)
**Intent:** Asynchronous method invocation is pattern where the calling thread
@@ -753,9 +757,10 @@ callbacks or waiting until everything is done.
![alt text](./async-method-invocation/etc/async-method-invocation.png "Async Method Invocation")
**Applicability:** Use async method invocation pattern when
-* You have multiple independent tasks that can run in parallel
-* You need to improve performance of running a group of sequential tasks
-* You have limited number of processing capacity or long running tasks and the caller cannot wait the tasks to be ready
+* you have multiple independent tasks that can run in parallel
+* you need to improve the performance of a group of sequential tasks
+* you have limited amount of processing capacity or long running tasks and the
+ caller should not wait the tasks to be ready
**Real world examples:**
* [FutureTask](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/FutureTask.html), [CompletableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html) and [ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html) (Java)
@@ -769,7 +774,7 @@ attributes by encapsulating them in single Data object.
![alt text](./private-class-data/etc/private-class-data.png "Private Class Data")
**Applicability:** Use the Private Class Data pattern when
-* You want to prevent write access to class data members
+* you want to prevent write access to class data members
## <a name="object-pool">Object Pool</a> [↑](#list-of-design-patterns)
**Intent:** When objects are expensive to create and they are needed only for
@@ -780,8 +785,8 @@ are in use and which are available.
![alt text](./object-pool/etc/object-pool.png "Object Pool")
**Applicability:** Use the Object Pool pattern when
-* The objects are expensive to create (allocation cost)
-* You need a large number of short-lived objects (memory fragmentation)
+* the objects are expensive to create (allocation cost)
+* you need a large number of short-lived objects (memory fragmentation)
## <a name="dependency-injection">Dependency Injection</a> [↑](#list-of-design-patterns)
**Intent:** Dependency Injection is a software design pattern in which one or
@@ -794,8 +799,8 @@ inversion of control and single responsibility principles.
![alt text](./dependency-injection/etc/dependency-injection.png "Dependency Injection")
**Applicability:** Use the Dependency Injection pattern when
-* When you need to remove knowledge of concrete implementation from object
-* To enable unit testing of classes in isolation using mock objects or stubs
+* when you need to remove knowledge of concrete implementation from object
+* to enable unit testing of classes in isolation using mock objects or stubs
## <a name="naked-objects">Naked Objects</a> [↑](#list-of-design-patterns)
**Intent:** The Naked Objects architectural pattern is well suited for rapid
@@ -805,9 +810,9 @@ everything else is autogenerated by the framework.
![alt text](./naked-objects/etc/naked-objects.png "Naked Objects")
**Applicability:** Use the Naked Objects pattern when
-* You are prototyping and need fast development cycle
-* An autogenerated user interface is good enough
-* You want to automatically publish the domain as REST services
+* you are prototyping and need fast development cycle
+* an autogenerated user interface is good enough
+* you want to automatically publish the domain as REST services
**Real world examples:**
* [Apache Isis](https://isis.apache.org/)
@@ -866,11 +871,11 @@ degrading execution efficiency.
![Half-Sync/Half-Async class diagram](./half-sync-half-async/etc/half-sync-half-async.png)
**Applicability:** Use Half-Sync/Half-Async pattern when
-* A system possesses following characteristics:
- * System must perform tasks in response to external events that occur asynchronously, like hardware interrupts in OS
- * It is inefficient to dedicate separate thread of control to perform synchronous I/O for each external source of event
- * The higher level tasks in the system can be simplified significantly if I/O is performed synchronously.
-* One or more tasks in a system must run in a single thread of control, while other tasks may benefit from multi-threading.
+* a system possesses following characteristics:
+ * the system must perform tasks in response to external events that occur asynchronously, like hardware interrupts in OS
+ * it is inefficient to dedicate separate thread of control to perform synchronous I/O for each external source of event
+ * the higher level tasks in the system can be simplified significantly if I/O is performed synchronously.
+* one or more tasks in a system must run in a single thread of control, while other tasks may benefit from multi-threading.
**Real world examples:**
* [BSD Unix networking subsystem](http://www.cs.wustl.edu/~schmidt/PDF/PLoP-95.pdf)
@@ -941,9 +946,13 @@ Flyweight.
**To work on a new pattern** you need to do the following steps:
-1. If there is no issue for the new pattern yet, raise new issue. Comment on the issue that you are working on it so that others don't start work on the same thing.
+1. If there is no issue for the new pattern yet, raise new issue. Comment on
+ the issue that you are working on it so that others don't start work on the
+ same thing.
2. Fork the repository.
-3. Implement the code changes in your fork. Remember to add sufficient comments documenting the implementation. Reference the issue id e.g. #52 in your commit messages.
+3. Implement the code changes in your fork. Remember to add sufficient comments
+ documenting the implementation. Reference the issue id e.g. #52 in your
+ commit messages.
4. Create a simple class diagram from your example code.
5. Add description of the pattern in README.md and link to the class diagram.
6. Create a pull request.
@@ -953,7 +962,9 @@ Flyweight.
1. Check that the issue has "help wanted" badge
2. Comment on the issue that you are working on it
3. Fork the repository.
-4. Implement the code changes in your fork. Remember to add sufficient comments documenting the implementation. Reference the issue id e.g. #52 in your commit messages.
+4. Implement the code changes in your fork. Remember to add sufficient comments
+ documenting the implementation. Reference the issue id e.g. #52 in your
+ commit messages.
5. Create a pull request.
**For creating/editing UML diagrams** you need [ObjectAid UML Explorer for Eclipse](http://www.objectaid.com/home).
| null | train | train | "2015-08-07T18:39:00" | "2015-08-06T23:19:24Z" | bernardosulzbach | train |
iluwatar/java-design-patterns/185_202 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/185 | iluwatar/java-design-patterns/202 | [
"timestamp(timedelta=185.0, similarity=0.8774521868148941)"
] | f14bb28db8448ef6fc5084b13e1c29f366a497b3 | fc43018684b0cb5af978db761c07c3fc856e91a2 | [
"Yes, why not. We could also setup a mailing list.\n",
"@iluwatar Great then. Let's do that. There is one more thing, I was thinking of setting up a wiki page describing usages of all design patterns. Do you think that is a good idea? IMO it would be better search optimized than README.md. We should continue doing what we do in README but we can also set up wiki. If you think it is a good idea then I can create a issue and start working on it.\n",
"@npathai Take a look at #56 This is under construction by @noobxgockel I don't think there will be wiki after this task, but nevertheless it is going to be a great step forward from `README.md` Maybe we should re-evaluate the wiki functionality after #56 is live.\n",
"I made an issue for the mailing list. It is #186 \n",
"@iluwatar Can we set up chat room on priority so that we can start having discussions on our ongoing implementations of patterns. We should also add link to add our gitter chat room in README.\n",
"Resolved with https://github.com/iluwatar/java-design-patterns/commit/76fe68f591f6b341a4b6d254a5c4d2d4b4e0cba5\n",
"Yayy :+1: \n"
] | [] | "2015-08-11T19:33:28Z" | [
"type: enhancement"
] | Integrate with Gitter chat room | I recently stumbled upon [Gitter - chat rooms for github](https://gitter.im/) and I think it would be a great idea to integrate with it, because discussions regarding design patterns can be really interesting and may be more suitable in chat format.
| [
"README.md"
] | [
"README.md"
] | [] | diff --git a/README.md b/README.md
index 358dfa3f3934..b2b72a358d2f 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,7 @@
# Design pattern samples in Java.
+[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+
![Build status](https://travis-ci.org/iluwatar/java-design-patterns.svg?branch=master) [![Coverage Status](https://coveralls.io/repos/iluwatar/java-design-patterns/badge.svg?branch=master)](https://coveralls.io/r/iluwatar/java-design-patterns?branch=master) <a href="https://scan.coverity.com/projects/5634">
<img alt="Coverity Scan Build Status"
src="https://scan.coverity.com/projects/5634/badge.svg"/>
| null | val | train | "2015-08-11T18:04:47" | "2015-08-02T07:39:26Z" | npathai | train |
iluwatar/java-design-patterns/109_204 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/109 | iluwatar/java-design-patterns/204 | [
"keyword_issue_to_pr"
] | 76fe68f591f6b341a4b6d254a5c4d2d4b4e0cba5 | 27956b0eebd322f85a324fb6cc55d2075268817d | [
"Great find, thanks for reporting this.\n",
"I am working on it. \n",
"Note to self - we also need to add reference to POSA book with this task in README\n",
"Please close this issue, if you are satisfied.\n",
"Once #204 is merged we can close this.\n"
] | [] | "2015-08-12T06:14:50Z" | [
"info: help wanted",
"epic: pattern"
] | Half Sync/Half Async pattern | This is a _concurrency_ pattern. The pattern separates asynchronous I/O from the synchronous one. Main thread doesn't block on incoming client requests and long-running operations are offloaded to a dedicated synchronous layer. Processing results are delivered by the means of callbacks.
Some resources:
- http://www.cs.wustl.edu/~schmidt/PDF/PLoP-95.pdf
- http://zezutom.blogspot.in/2014/08/concurrency-patterns-half-sync-half.html
- http://www.dre.vanderbilt.edu/~schmidt/cs282/PDFs/6-Concurrency-and-Synchronization-part10.pdf
| [
"README.md"
] | [
"README.md"
] | [] | diff --git a/README.md b/README.md
index b2b72a358d2f..dc43a2dc5855 100644
--- a/README.md
+++ b/README.md
@@ -1037,6 +1037,8 @@ other words, version numbers are used only for project planning sake.
* [Spring Data](http://www.amazon.com/Spring-Data-Mark-Pollack/dp/1449323952/ref=sr_1_1)
* [J2EE Design Patterns](http://www.amazon.com/J2EE-Design-Patterns-William-Crawford/dp/0596004273/ref=sr_1_2)
* [Marco Castigliego - Step Builder](http://rdafbn.blogspot.co.uk/2012/07/step-builder-pattern_28.html)
+* [Douglas C. Schmidt and Charles D. Cranor - Half Sync/Half Async](http://www.cs.wustl.edu/~schmidt/PDF/PLoP-95.pdf)
+* [Pattern Oriented Software Architecture Vol I-V](http://www.amazon.com/Pattern-Oriented-Software-Architecture-Volume-Patterns/dp/0471958697)
# <a name="license">License</a> [↑](#top)
| null | val | train | "2015-08-11T21:40:53" | "2015-07-23T06:07:31Z" | npathai | train |
iluwatar/java-design-patterns/143_227 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/143 | iluwatar/java-design-patterns/227 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.9779156313707427)"
] | 4135179040ba9c06b347802d51d75952284dfae7 | a3f76fe30fb010c49c174c00aff7c613eb27afe8 | [] | [
"@iluwatar Why duplicated?\n",
"Doesn't `![Message Channel](./etc/message-channel.png)` produces the same result? It is clearer, shorter and more readable.\n",
"Should we really **ensure** that all DPs have an applicability field? In this case it is redundant (Intent already said this).\n",
"Why this dependency is more indentated?\n",
"Another way of saying that would be that \"`Message Channel` decouples Message producers and Consumers\".\n",
"Can we have one more route, from `stream:in` to `direct:greetings`? This places emphasis on the point that the two endpoints don't need to know about each other.\n",
"This EIP being so trivial I scratched my head thinking of some particular use case but couldn't think of one without complicating the example. Do you have anything specific in mind?\n",
"Yes. But if producers is lowercase, consumers should also be. Not a problem in the comment, but wouldn't be right on the code.\n",
"I would also like some example use cases. A real world one would be awesome.\n",
"@mafagafogigante :+1: a typo\n",
"I think the implementation is the same across all the patterns and we have no agreed convention on this.\n",
"I wouldn't leave it out. We should strive to have content for the fields mentioned in the [pattern template](https://github.com/iluwatar/java-design-patterns/wiki/2.-Pattern-template).\n",
"This is done.\n",
"I added the second message channel and a real world example.\n"
] | "2015-08-22T16:50:29Z" | [
"epic: pattern",
"status: under review"
] | Message Channel (EIP) | [
"pom.xml"
] | [
"message-channel/.gitignore",
"message-channel/etc/message-channel.ucls",
"message-channel/index.md",
"message-channel/pom.xml",
"message-channel/src/main/java/com/iluwatar/message/channel/App.java",
"pom.xml"
] | [
"message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java"
] | diff --git a/message-channel/.gitignore b/message-channel/.gitignore
new file mode 100644
index 000000000000..b83d22266ac8
--- /dev/null
+++ b/message-channel/.gitignore
@@ -0,0 +1,1 @@
+/target/
diff --git a/message-channel/etc/message-channel.ucls b/message-channel/etc/message-channel.ucls
new file mode 100644
index 000000000000..3ef0ed4bc8fd
--- /dev/null
+++ b/message-channel/etc/message-channel.ucls
@@ -0,0 +1,320 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
+ realizations="true" associations="true" dependencies="false" nesting-relationships="true">
+ <class id="1" language="java" name="org.apache.camel.builder.RouteBuilder" project="message-channel"
+ file="C:/Users/ilkka/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="920" y="458"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </display>
+ </class>
+ <interface id="2" language="java" name="org.apache.camel.CamelContext" project="message-channel"
+ file="C:/Users/ilkka/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="674" y="458"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </display>
+ </interface>
+ <class id="3" language="java" name="org.apache.camel.model.RouteDefinition" project="message-channel"
+ file="C:/Users/ilkka/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="673" y="48"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </display>
+ </class>
+ <class id="4" language="java" name="org.apache.camel.model.ProcessorDefinition" project="message-channel"
+ file="C:/Users/ilkka/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="673" y="-96"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </display>
+ </class>
+ <class id="5" language="java" name="org.apache.camel.model.OptionalIdentifiedDefinition" project="message-channel"
+ file="C:/Users/ilkka/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="248" y="-96"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </display>
+ </class>
+ <interface id="6" language="java" name="org.apache.camel.NamedNode" project="message-channel"
+ file="C:/Users/ilkka/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="249" y="0"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </display>
+ </interface>
+ <interface id="7" language="java" name="org.apache.camel.model.Block" project="message-channel"
+ file="C:/Users/ilkka/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="464" y="13"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </display>
+ </interface>
+ <interface id="8" language="java" name="org.apache.camel.RoutesBuilder" project="message-channel"
+ file="C:/Users/ilkka/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="920" y="590"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </display>
+ </interface>
+ <class id="9" language="java" name="org.apache.camel.builder.BuilderSupport" project="message-channel"
+ file="C:/Users/ilkka/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="920" y="297"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </display>
+ </class>
+ <interface id="10" language="java" name="org.apache.camel.SuspendableService" project="message-channel"
+ file="C:/Users/ilkka/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="267" y="458"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </display>
+ </interface>
+ <interface id="11" language="java" name="org.apache.camel.Service" project="message-channel"
+ file="C:/Users/ilkka/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="267" y="297"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </display>
+ </interface>
+ <interface id="12" language="java" name="org.apache.camel.RuntimeConfiguration" project="message-channel"
+ file="C:/Users/ilkka/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="674" y="590"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </display>
+ </interface>
+ <class id="13" language="java" name="org.apache.camel.impl.DefaultCamelContext" project="message-channel"
+ file="C:/Users/ilkka/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="673" y="167"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </display>
+ </class>
+ <class id="14" language="java" name="org.apache.camel.support.ServiceSupport" project="message-channel"
+ file="C:/Users/ilkka/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="265" y="91"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </display>
+ </class>
+ <interface id="15" language="java" name="org.apache.camel.StatefulService" project="message-channel"
+ file="C:/Users/ilkka/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="5" y="188"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </display>
+ </interface>
+ <interface id="16" language="java" name="org.apache.camel.ShutdownableService" project="message-channel"
+ file="C:/Users/ilkka/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="265" y="188"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </display>
+ </interface>
+ <interface id="17" language="java" name="org.apache.camel.model.ModelCamelContext" project="message-channel"
+ file="C:/Users/ilkka/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="674" y="297"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </display>
+ </interface>
+ <generalization id="18">
+ <end type="SOURCE" refId="4"/>
+ <end type="TARGET" refId="5"/>
+ </generalization>
+ <generalization id="19">
+ <end type="SOURCE" refId="2"/>
+ <end type="TARGET" refId="10"/>
+ </generalization>
+ <realization id="20">
+ <end type="SOURCE" refId="1"/>
+ <end type="TARGET" refId="8"/>
+ </realization>
+ <association id="21">
+ <end type="SOURCE" refId="9" navigable="false">
+ <attribute id="22" name="context">
+ <position height="0" width="0" x="-583" y="-276"/>
+ </attribute>
+ <multiplicity id="23" minimum="0" maximum="1">
+ <position height="0" width="0" x="-583" y="-276"/>
+ </multiplicity>
+ </end>
+ <end type="TARGET" refId="17" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <association id="24">
+ <end type="SOURCE" refId="4" navigable="false">
+ <attribute id="25" name="blocks">
+ <position height="0" width="0" x="145" y="-462"/>
+ </attribute>
+ <multiplicity id="26" minimum="0" maximum="2147483647">
+ <position height="0" width="0" x="145" y="-462"/>
+ </multiplicity>
+ </end>
+ <end type="TARGET" refId="7" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <association id="27">
+ <end type="SOURCE" refId="13" navigable="false">
+ <attribute id="28" name="servicesToClose">
+ <position height="0" width="0" x="-409" y="37"/>
+ </attribute>
+ <multiplicity id="29" minimum="0" maximum="2147483647">
+ <position height="0" width="0" x="-409" y="37"/>
+ </multiplicity>
+ </end>
+ <end type="TARGET" refId="11" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <realization id="30">
+ <end type="SOURCE" refId="13"/>
+ <end type="TARGET" refId="17"/>
+ </realization>
+ <realization id="31">
+ <end type="SOURCE" refId="14"/>
+ <end type="TARGET" refId="15"/>
+ </realization>
+ <generalization id="32">
+ <end type="SOURCE" refId="17"/>
+ <end type="TARGET" refId="2"/>
+ </generalization>
+ <generalization id="33">
+ <end type="SOURCE" refId="15"/>
+ <end type="TARGET" refId="10"/>
+ </generalization>
+ <generalization id="34">
+ <end type="SOURCE" refId="1"/>
+ <end type="TARGET" refId="9"/>
+ </generalization>
+ <generalization id="35">
+ <end type="SOURCE" refId="3"/>
+ <end type="TARGET" refId="4"/>
+ </generalization>
+ <generalization id="36">
+ <end type="SOURCE" refId="16"/>
+ <end type="TARGET" refId="11"/>
+ </generalization>
+ <generalization id="37">
+ <end type="SOURCE" refId="15"/>
+ <end type="TARGET" refId="16"/>
+ </generalization>
+ <generalization id="38">
+ <end type="SOURCE" refId="10"/>
+ <end type="TARGET" refId="11"/>
+ </generalization>
+ <realization id="39">
+ <end type="SOURCE" refId="4"/>
+ <end type="TARGET" refId="7"/>
+ </realization>
+ <association id="40">
+ <end type="SOURCE" refId="4" navigable="false">
+ <attribute id="41" name="parent">
+ <position height="0" width="0" x="329" y="-461"/>
+ </attribute>
+ <multiplicity id="42" minimum="0" maximum="1">
+ <position height="0" width="0" x="329" y="-461"/>
+ </multiplicity>
+ </end>
+ <end type="TARGET" refId="4" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <realization id="43">
+ <end type="SOURCE" refId="5"/>
+ <end type="TARGET" refId="6"/>
+ </realization>
+ <generalization id="44">
+ <end type="SOURCE" refId="2"/>
+ <end type="TARGET" refId="12"/>
+ </generalization>
+ <generalization id="45">
+ <end type="SOURCE" refId="13"/>
+ <end type="TARGET" refId="14"/>
+ </generalization>
+ <association id="46">
+ <end type="SOURCE" refId="3" navigable="false">
+ <attribute id="47" name="outputs">
+ <position height="0" width="0" x="329" y="-461"/>
+ </attribute>
+ <multiplicity id="48" minimum="0" maximum="2147483647">
+ <position height="0" width="0" x="329" y="-461"/>
+ </multiplicity>
+ </end>
+ <end type="TARGET" refId="4" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <association id="49">
+ <end type="SOURCE" refId="13" navigable="false">
+ <attribute id="50" name="routeDefinitions">
+ <position height="0" width="0" x="291" y="-218"/>
+ </attribute>
+ <multiplicity id="51" minimum="0" maximum="2147483647">
+ <position height="0" width="0" x="291" y="-218"/>
+ </multiplicity>
+ </end>
+ <end type="TARGET" refId="3" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <realization id="52">
+ <end type="SOURCE" refId="13"/>
+ <end type="TARGET" refId="10"/>
+ </realization>
+ <classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="true"/>
+ </classifier-display>
+ <association-display labels="true" multiplicity="true"/>
+</class-diagram>
\ No newline at end of file
diff --git a/message-channel/index.md b/message-channel/index.md
new file mode 100644
index 000000000000..b5fb1761a78c
--- /dev/null
+++ b/message-channel/index.md
@@ -0,0 +1,21 @@
+---
+layout: pattern
+title: Message Channel
+folder: message-channel
+permalink: /patterns/message-channel/
+categories: Integration
+tags: Java
+---
+
+**Intent:** When two applications communicate using a messaging system they do it by using logical addresses
+of the system, so called Message Channels.
+
+![alt text](./etc/message-channel.png "Message Channel")
+
+**Applicability:** Use the Message Channel pattern when
+
+* two or more applications need to communicate using a messaging system
+
+**Real world examples:**
+
+* [akka-camel](http://doc.akka.io/docs/akka/snapshot/scala/camel.html)
diff --git a/message-channel/pom.xml b/message-channel/pom.xml
new file mode 100644
index 000000000000..ef66f240173b
--- /dev/null
+++ b/message-channel/pom.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0"?>
+<project
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
+ xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>java-design-patterns</artifactId>
+ <version>1.6.0</version>
+ </parent>
+ <artifactId>message-channel</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-stream</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
diff --git a/message-channel/src/main/java/com/iluwatar/message/channel/App.java b/message-channel/src/main/java/com/iluwatar/message/channel/App.java
new file mode 100644
index 000000000000..f9a334a8a463
--- /dev/null
+++ b/message-channel/src/main/java/com/iluwatar/message/channel/App.java
@@ -0,0 +1,53 @@
+package com.iluwatar.message.channel;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.impl.DefaultCamelContext;
+
+/**
+ *
+ * When two applications communicate with each other using a messaging system
+ * they first need to establish a communication channel that will carry the
+ * data. Message Channel decouples Message producers and consumers.
+ * <p>
+ * The sending application doesn't necessarily know what particular application
+ * will end up retrieving it, but it can be assured that the application that
+ * retrieves the information is interested in that information. This is because
+ * the messaging system has different Message Channels for different types of
+ * information the applications want to communicate. When an application sends
+ * information, it doesn't randomly add the information to any channel available;
+ * it adds it to a channel whose specific purpose is to communicate that sort of
+ * information. Likewise, an application that wants to receive particular information
+ * doesn't pull info off some random channel; it selects what channel to get information
+ * from based on what type of information it wants.
+ * <p>
+ * In this example we use Apache Camel to establish two different Message Channels. The first
+ * one reads from standard input and delivers messages to Direct endpoint. The second Message
+ * Channel is established from the Direct component to console output. No actual messages are sent,
+ * only the established routes are printed to standard output.
+ *
+ */
+public class App {
+
+ /**
+ * Program entry point
+ * @param args command line args
+ * @throws Exception
+ */
+ public static void main(String[] args) throws Exception {
+ CamelContext context = new DefaultCamelContext();
+
+ context.addRoutes(new RouteBuilder() {
+
+ @Override
+ public void configure() throws Exception {
+ from("stream:in").to("direct:greetings");
+ from("direct:greetings").to("stream:out");
+ }
+ });
+
+ context.start();
+ context.getRoutes().stream().forEach((r) -> System.out.println(r));
+ context.stop();
+ }
+}
diff --git a/pom.xml b/pom.xml
index 961d9b281a64..7b0d80bd87f4 100644
--- a/pom.xml
+++ b/pom.xml
@@ -17,6 +17,7 @@
<coveralls.version>3.1.0</coveralls.version>
<jacoco.version>0.7.2.201409121644</jacoco.version>
<commons-dbcp.version>1.4</commons-dbcp.version>
+ <camel.version>2.15.3</camel.version>
</properties>
<modules>
<module>abstract-factory</module>
@@ -75,6 +76,7 @@
<module>half-sync-half-async</module>
<module>step-builder</module>
<module>layers</module>
+ <module>message-channel</module>
</modules>
<dependencyManagement>
@@ -104,6 +106,16 @@
<artifactId>commons-dbcp</artifactId>
<version>${commons-dbcp.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-core</artifactId>
+ <version>${camel.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-stream</artifactId>
+ <version>${camel.version}</version>
+ </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
| diff --git a/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java b/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java
new file mode 100644
index 000000000000..fa3af1161dbe
--- /dev/null
+++ b/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java
@@ -0,0 +1,17 @@
+package com.iluwatar.message.channel;
+
+import org.junit.Test;
+
+/**
+ *
+ * Application test
+ *
+ */
+public class AppTest {
+
+ @Test
+ public void test() throws Exception {
+ String[] args = {};
+ App.main(args);
+ }
+}
| val | train | "2015-09-02T11:47:06" | "2015-07-27T17:14:45Z" | iluwatar | train |
|
iluwatar/java-design-patterns/208_245 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/208 | iluwatar/java-design-patterns/245 | [
"timestamp(timedelta=97.0, similarity=0.845097672222473)"
] | 9ecb1b25462402e39cdf52596669789330f9105a | 8fdba13888c25d44b6e4875f009113a2946d909e | [
":+1: \n",
"This could be its own section, like for example the \"Idioms\" is.\n",
"We should borrow some things from here http://webpro.github.io/programming-principles/\n",
"@iluwatar That's a great link. I will go through it. Yes it should be in a dedicated section something like \"Design guidelines or principles\".\n",
"I dare to say YAGNI about this very idea.\n\n@iluwatar Awesome link. Why not just reference it in the suggested section? Also keep a fork of it so that if the original repository is removed we still have our copy.\n",
"@mafagafogigante I was kinda thinking in the same line. I will change the task to just add reference to the link @iluwatar provided. How does that sound?\n",
"@mafagafogigante @npathai This is a good idea. We also may have something to contribute to that repository.\n",
"Ok I will pick this up once I am done with #74 Turns out its difficult to work with NIO :smile: \n",
"Great. I think that helping that repository would be a great thing to do.\n",
"It's done. Closing this issue.\n"
] | [] | "2015-09-08T07:29:13Z" | [
"type: enhancement",
"info: good first issue"
] | Document design principles | SOLID | YAGNI | Some of the design principles that I know of are:
- [SOLID](https://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29)
- [Tell Don't Ask](http://martinfowler.com/bliki/TellDontAsk.html)
- [YAGNI](https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it)
- [KISS](https://en.wikipedia.org/wiki/KISS_principle)
- [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself)
These are the foundational principles which lead to design patterns. I think we should document them.
| [
"README.md"
] | [
"README.md"
] | [] | diff --git a/README.md b/README.md
index a4ec970c9d9b..77282f569fb7 100644
--- a/README.md
+++ b/README.md
@@ -21,6 +21,17 @@ Reusing design patterns helps to prevent subtle issues that can cause major
problems, and it also improves code readability for coders and architects who
are familiar with the patterns.
+# Getting started
+
+Before you dive into the material, you should be familiar with various
+[Programming/Software Design Principles](http://webpro.github.io/programming-principles/).
+
+Once you are familiar with these concepts you can start drilling down into patterns by any of the following approaches
+
+ - Using difficulty tags, `Difficulty-Beginner`, `Difficulty-Intermediate` & `Difficulty-Expert`.
+ - Using pattern categories, `Creational`, `Behavioral` and others.
+ - Search for a specific pattern. Can't find one? Please report a new pattern [here](https://github.com/iluwatar/java-design-patterns/issues).
+
# How to contribute
If you are willing to contribute to the project you will find the relevant information in our [developer wiki](https://github.com/iluwatar/java-design-patterns/wiki).
| null | train | train | "2015-09-11T09:54:15" | "2015-08-14T10:57:29Z" | npathai | train |
iluwatar/java-design-patterns/247_253 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/247 | iluwatar/java-design-patterns/253 | [
"timestamp(timedelta=23.0, similarity=0.9613100109898698)"
] | b3e4e8a47bf5f88277029534456334d9e2c59432 | 9e25e7b518c98189098de17b586fbfeb6f96596e | [] | [] | "2015-09-23T17:00:37Z" | [
"info: help wanted",
"type: enhancement",
"info: good first issue"
] | add getAttackPower method to pattern decorator | Add getAttackPower method to pattern decorator may make it more easily to understand .
when the troll not add smart decorator , his attack power is 10 ,but when we build the smartTroll , his attack power is 10(the normal troll's attack power) + 20(because smart). So ,it's more easy to understand .
| [
"decorator/src/main/java/com/iluwatar/decorator/App.java",
"decorator/src/main/java/com/iluwatar/decorator/Hostile.java",
"decorator/src/main/java/com/iluwatar/decorator/SmartTroll.java",
"decorator/src/main/java/com/iluwatar/decorator/Troll.java"
] | [
"decorator/src/main/java/com/iluwatar/decorator/App.java",
"decorator/src/main/java/com/iluwatar/decorator/Hostile.java",
"decorator/src/main/java/com/iluwatar/decorator/SmartTroll.java",
"decorator/src/main/java/com/iluwatar/decorator/Troll.java"
] | [] | diff --git a/decorator/src/main/java/com/iluwatar/decorator/App.java b/decorator/src/main/java/com/iluwatar/decorator/App.java
index 88e1c7103175..a9eabf6068c0 100644
--- a/decorator/src/main/java/com/iluwatar/decorator/App.java
+++ b/decorator/src/main/java/com/iluwatar/decorator/App.java
@@ -23,11 +23,13 @@ public static void main(String[] args) {
Hostile troll = new Troll();
troll.attack();
troll.fleeBattle();
+ System.out.printf("Simple troll power %d.\n", troll.getAttackPower());
// change the behavior of the simple troll by adding a decorator
System.out.println("\nA smart looking troll surprises you.");
Hostile smart = new SmartTroll(troll);
smart.attack();
smart.fleeBattle();
+ System.out.printf("Smart troll power %d.\n", smart.getAttackPower());
}
}
diff --git a/decorator/src/main/java/com/iluwatar/decorator/Hostile.java b/decorator/src/main/java/com/iluwatar/decorator/Hostile.java
index 4df751cca69d..7090725017f4 100644
--- a/decorator/src/main/java/com/iluwatar/decorator/Hostile.java
+++ b/decorator/src/main/java/com/iluwatar/decorator/Hostile.java
@@ -9,6 +9,8 @@ public interface Hostile {
void attack();
+ int getAttackPower();
+
void fleeBattle();
}
diff --git a/decorator/src/main/java/com/iluwatar/decorator/SmartTroll.java b/decorator/src/main/java/com/iluwatar/decorator/SmartTroll.java
index 22ba88dc88b8..909f94c952ff 100644
--- a/decorator/src/main/java/com/iluwatar/decorator/SmartTroll.java
+++ b/decorator/src/main/java/com/iluwatar/decorator/SmartTroll.java
@@ -21,6 +21,12 @@ public void attack() {
decorated.attack();
}
+ @Override
+ public int getAttackPower() {
+ // decorated troll power + 20 because it is smart
+ return decorated.getAttackPower() + 20;
+ }
+
@Override
public void fleeBattle() {
System.out.println("The troll calls for help!");
diff --git a/decorator/src/main/java/com/iluwatar/decorator/Troll.java b/decorator/src/main/java/com/iluwatar/decorator/Troll.java
index 11e9b9d1afdf..85d873dbe5c1 100644
--- a/decorator/src/main/java/com/iluwatar/decorator/Troll.java
+++ b/decorator/src/main/java/com/iluwatar/decorator/Troll.java
@@ -11,6 +11,11 @@ public void attack() {
System.out.println("The troll swings at you with a club!");
}
+ @Override
+ public int getAttackPower() {
+ return 10;
+ }
+
public void fleeBattle() {
System.out.println("The troll shrieks in horror and runs away!");
}
| null | train | train | "2015-09-22T14:55:56" | "2015-09-10T10:38:26Z" | liangpengfei | train |
iluwatar/java-design-patterns/161_272 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/161 | iluwatar/java-design-patterns/272 | [
"timestamp(timedelta=331.0, similarity=0.8542647842238095)"
] | a2b8359ab5b844f9c2ae4abcff304181121545f7 | bac87ba5267ff0b74149c228e38f04ccdf30f6df | [
"This pattern is similar in intent to Observer pattern. \n\n## Observer\n- Is used for same process events\n- Subscriber is aware of the publisher's existence\n- It is one (pub) to many (subs)\n- Publisher fires the on change events\n- Events are fired in sync\n- Implementation: `Observable` and `Observer` classes in Java\n\n## Pub-Sub\n- Typically used when there are two different processes\n- Optionally there is topic based or content based filter\n- There is a middle layer (queuing layer involved)\n- Publishers and subscribers don't know about existence of each other. They just know about the existence of a channel (queue).\n",
"A friend of mine is very pleased with this pattern. So it's about time to present him an example in Java.\n\nI'll offer some testable code these days.\n",
"What is going on here?\n\nOn Mon, Oct 5, 2015 at 9:12 AM, Michael Dähnert notifications@github.com\nwrote:\n\n> A friend of mine is very pleased with this pattern. So it's about time to\n> present him an example in Java.\n> \n> I'll offer some testable code these days.\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/iluwatar/java-design-patterns/issues/161#issuecomment-145585246\n> .\n",
"I'm working on an implementation of this pattern. If you like, please alter the ticket labels.\n",
"Please note https://github.com/iluwatar/java-design-patterns/wiki/10.-Technology-selections\n\nSo you would have to implement the pattern using Apache Camel and then document how the framework implements this.\n\nLet me know if you still want to take this issue and I will update the labels.\n",
"Thanks for the information. Yeah I'll do it. Seems to be much smarter to implement it with Apache Camel then on my own.\n",
"Ok I will alter the labels.\n",
"https://docs.microsoft.com/en-us/azure/architecture/patterns/publisher-subscriber"
] | [
"You could have pluralized Subscriber. It sounds more natural.\n"
] | "2015-10-25T06:12:20Z" | [
"epic: pattern"
] | Publish-Subscribe Channel (EIP) | [
"pom.xml"
] | [
"pom.xml",
"publish-subscribe/.gitignore",
"publish-subscribe/etc/publish-subscribe.ucls",
"publish-subscribe/index.md",
"publish-subscribe/pom.xml",
"publish-subscribe/src/main/java/com/iluwatar/publish/subscribe/App.java"
] | [
"publish-subscribe/src/test/java/com/iluwatar/publish/subscribe/AppTest.java"
] | diff --git a/pom.xml b/pom.xml
index 3064f3c0dd8f..e01dc10018b6 100644
--- a/pom.xml
+++ b/pom.xml
@@ -80,6 +80,7 @@
<module>message-channel</module>
<module>fluentinterface</module>
<module>reactor</module>
+ <module>publish-subscribe</module>
</modules>
<dependencyManagement>
diff --git a/publish-subscribe/.gitignore b/publish-subscribe/.gitignore
new file mode 100644
index 000000000000..b83d22266ac8
--- /dev/null
+++ b/publish-subscribe/.gitignore
@@ -0,0 +1,1 @@
+/target/
diff --git a/publish-subscribe/etc/publish-subscribe.ucls b/publish-subscribe/etc/publish-subscribe.ucls
new file mode 100644
index 000000000000..1b121506eed8
--- /dev/null
+++ b/publish-subscribe/etc/publish-subscribe.ucls
@@ -0,0 +1,218 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<class-diagram version="1.1.8" icons="true" always-add-relationships="false" generalizations="true" realizations="true"
+ associations="true" dependencies="false" nesting-relationships="true">
+ <class id="1" language="java" name="org.apache.camel.builder.RouteBuilder" project="message-channel"
+ file="D:/Users/mdaehner/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="269" y="526"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="false"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="false"/>
+ </display>
+ </class>
+ <interface id="2" language="java" name="org.apache.camel.RoutesBuilder" project="message-channel"
+ file="D:/Users/mdaehner/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="270" y="406"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="false"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="false"/>
+ </display>
+ </interface>
+ <class id="3" language="java" name="org.apache.camel.model.RouteDefinition" project="message-channel"
+ file="D:/Users/mdaehner/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="574" y="421"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="false"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="false"/>
+ </display>
+ </class>
+ <class id="4" language="java" name="org.apache.camel.model.RoutesDefinition" project="message-channel"
+ file="D:/Users/mdaehner/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="574" y="526"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="false"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="false"/>
+ </display>
+ </class>
+ <class id="5" language="java" name="org.apache.camel.model.MulticastDefinition" project="message-channel"
+ file="D:/Users/mdaehner/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="574" y="68"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="false"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="false"/>
+ </display>
+ </class>
+ <class id="6" language="java" name="org.apache.camel.model.OutputDefinition" project="message-channel"
+ file="D:/Users/mdaehner/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="576" y="164"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="false"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="false"/>
+ </display>
+ </class>
+ <class id="7" language="java" name="org.apache.camel.model.ProcessorDefinition" project="message-channel"
+ file="D:/Users/mdaehner/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="575" y="284"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="false"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="false"/>
+ </display>
+ </class>
+ <interface id="8" language="java" name="org.apache.camel.CamelContext" project="message-channel"
+ file="D:/Users/mdaehner/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_LEFT">
+ <position height="-1" width="-1" x="1086" y="346"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="false"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="false"/>
+ </display>
+ </interface>
+ <interface id="9" language="java" name="org.apache.camel.model.ModelCamelContext" project="message-channel"
+ file="D:/Users/mdaehner/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_LEFT">
+ <position height="-1" width="-1" x="1086" y="526"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="false"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="false"/>
+ </display>
+ </interface>
+ <class id="10" language="java" name="org.apache.camel.impl.DefaultCamelContext" project="message-channel"
+ file="D:/Users/mdaehner/.m2/repository/org/apache/camel/camel-core/2.15.3/camel-core-2.15.3.jar" binary="true"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="885" y="421"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="false"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="false"/>
+ </display>
+ </class>
+ <realization id="11">
+ <end type="SOURCE" refId="10"/>
+ <end type="TARGET" refId="9"/>
+ </realization>
+ <generalization id="12">
+ <end type="SOURCE" refId="6"/>
+ <end type="TARGET" refId="7"/>
+ </generalization>
+ <association id="13">
+ <end type="SOURCE" refId="6" navigable="false">
+ <attribute id="14" name="outputs">
+ <position height="0" width="0" x="0" y="0"/>
+ </attribute>
+ <multiplicity id="15" minimum="0" maximum="2147483647">
+ <position height="0" width="0" x="0" y="0"/>
+ </multiplicity>
+ </end>
+ <end type="TARGET" refId="7" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <realization id="16">
+ <end type="SOURCE" refId="1"/>
+ <end type="TARGET" refId="2"/>
+ </realization>
+ <generalization id="17">
+ <end type="SOURCE" refId="3"/>
+ <end type="TARGET" refId="7"/>
+ </generalization>
+ <association id="18">
+ <end type="SOURCE" refId="4" navigable="false">
+ <attribute id="19" name="camelContext">
+ <position height="0" width="0" x="0" y="0"/>
+ </attribute>
+ <multiplicity id="20" minimum="0" maximum="1">
+ <position height="0" width="0" x="0" y="0"/>
+ </multiplicity>
+ </end>
+ <end type="TARGET" refId="9" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <association id="21">
+ <end type="SOURCE" refId="7" navigable="false">
+ <attribute id="22" name="parent">
+ <position height="0" width="0" x="0" y="0"/>
+ </attribute>
+ <multiplicity id="23" minimum="0" maximum="1">
+ <position height="0" width="0" x="0" y="0"/>
+ </multiplicity>
+ </end>
+ <end type="TARGET" refId="7" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <association id="24">
+ <end type="SOURCE" refId="1" navigable="false">
+ <attribute id="25" name="routeCollection">
+ <position height="0" width="0" x="0" y="0"/>
+ </attribute>
+ <multiplicity id="26" minimum="0" maximum="1">
+ <position height="0" width="0" x="0" y="0"/>
+ </multiplicity>
+ </end>
+ <end type="TARGET" refId="4" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <association id="27">
+ <end type="SOURCE" refId="10" navigable="false">
+ <attribute id="28" name="routeDefinitions">
+ <position height="0" width="0" x="0" y="0"/>
+ </attribute>
+ <multiplicity id="29" minimum="0" maximum="2147483647">
+ <position height="0" width="0" x="0" y="0"/>
+ </multiplicity>
+ </end>
+ <end type="TARGET" refId="3" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <association id="30">
+ <end type="SOURCE" refId="3" navigable="false">
+ <attribute id="31" name="outputs">
+ <position height="0" width="0" x="0" y="0"/>
+ </attribute>
+ <multiplicity id="32" minimum="0" maximum="2147483647">
+ <position height="0" width="0" x="0" y="0"/>
+ </multiplicity>
+ </end>
+ <end type="TARGET" refId="7" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <generalization id="33">
+ <end type="SOURCE" refId="9"/>
+ <end type="TARGET" refId="8"/>
+ </generalization>
+ <association id="34">
+ <end type="SOURCE" refId="4" navigable="false">
+ <attribute id="35" name="routes">
+ <position height="0" width="0" x="0" y="0"/>
+ </attribute>
+ <multiplicity id="36" minimum="0" maximum="2147483647">
+ <position height="0" width="0" x="0" y="0"/>
+ </multiplicity>
+ </end>
+ <end type="TARGET" refId="3" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <generalization id="37">
+ <end type="SOURCE" refId="5"/>
+ <end type="TARGET" refId="6"/>
+ </generalization>
+ <classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="false"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <operations public="false" package="false" protected="false" private="false" static="false"/>
+ </classifier-display>
+ <association-display labels="true" multiplicity="true"/>
+</class-diagram>
\ No newline at end of file
diff --git a/publish-subscribe/index.md b/publish-subscribe/index.md
new file mode 100644
index 000000000000..efd40f02169b
--- /dev/null
+++ b/publish-subscribe/index.md
@@ -0,0 +1,17 @@
+---
+layout: pattern
+title: Publish Subscribe
+folder: publish-subscribe
+permalink: /patterns/publish-subscribe/
+categories: Integration
+tags: Java
+---
+
+**Intent:** When applications communicate using a messaging system they do it by using logical addresses
+of the system, so called Publish Subscribe Channel. The publisher broadcasts a message to all registered Subscriber.
+
+![alt text](./etc/publish-subscribe.png "Publish Subscribe Channel")
+
+**Applicability:** Use the Publish Subscribe Channel pattern when
+
+* two or more applications need to communicate using a messaging system for broadcasts.
diff --git a/publish-subscribe/pom.xml b/publish-subscribe/pom.xml
new file mode 100644
index 000000000000..04b76690afb0
--- /dev/null
+++ b/publish-subscribe/pom.xml
@@ -0,0 +1,24 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>java-design-patterns</artifactId>
+ <version>1.7.0</version>
+ </parent>
+ <artifactId>publish-subscribe</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-stream</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </dependency>
+ </dependencies>
+</project>
\ No newline at end of file
diff --git a/publish-subscribe/src/main/java/com/iluwatar/publish/subscribe/App.java b/publish-subscribe/src/main/java/com/iluwatar/publish/subscribe/App.java
new file mode 100644
index 000000000000..1f433f5171a8
--- /dev/null
+++ b/publish-subscribe/src/main/java/com/iluwatar/publish/subscribe/App.java
@@ -0,0 +1,55 @@
+package com.iluwatar.publish.subscribe;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.impl.DefaultCamelContext;
+
+/**
+ *
+ * When applications communicate with each other using a messaging system
+ * they first need to establish a communication channel that will carry the
+ * data. Message Channel decouples Message producers (publisher) and consumers (subscriber).
+ * <p>
+ * The sending application doesn't necessarily know what particular applications
+ * will end up retrieving it, but it can be assured that the application that
+ * retrieves the information is interested in that information. This is because
+ * the messaging system has different Message Channels for different types of
+ * information the applications want to communicate. When an application sends
+ * information, it doesn't randomly add the information to any channel available;
+ * it adds it to a channel whose specific purpose is to communicate that sort of
+ * information. Likewise, an application that wants to receive particular information
+ * doesn't pull info off some random channel; it selects what channel to get information
+ * from based on what type of information it wants.
+ * <p>
+ * In this example we use Apache Camel to establish different Message Channels. The first
+ * one reads from standard input and delivers messages to Direct endpoints (Publish; Broadcast). The other Message
+ * Channels are established from the Direct component to different Endpoints (Subscriber). No actual messages are sent,
+ * only the established routes are printed to standard output.
+ *
+ */
+public class App {
+
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ * @throws Exception
+ */
+ public static void main(String[] args) throws Exception {
+ CamelContext context = new DefaultCamelContext();
+
+ context.addRoutes(new RouteBuilder() {
+
+ @Override
+ public void configure() throws Exception {
+ from("stream:in")
+ .multicast()
+ .to("direct:greetings1", "direct:greetings2", "direct:greetings3");
+ }
+ });
+
+ context.start();
+ context.getRoutes().stream().forEach((r) -> System.out.println(r));
+ context.stop();
+ }
+}
| diff --git a/publish-subscribe/src/test/java/com/iluwatar/publish/subscribe/AppTest.java b/publish-subscribe/src/test/java/com/iluwatar/publish/subscribe/AppTest.java
new file mode 100644
index 000000000000..743e4200d161
--- /dev/null
+++ b/publish-subscribe/src/test/java/com/iluwatar/publish/subscribe/AppTest.java
@@ -0,0 +1,17 @@
+package com.iluwatar.publish.subscribe;
+
+import org.junit.Test;
+
+/**
+ *
+ * Application test
+ *
+ */
+public class AppTest {
+
+ @Test
+ public void test() throws Exception {
+ String[] args = {};
+ App.main(args);
+ }
+}
\ No newline at end of file
| train | train | "2015-10-20T22:37:39" | "2015-07-27T17:21:45Z" | iluwatar | train |
|
iluwatar/java-design-patterns/286_291 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/286 | iluwatar/java-design-patterns/291 | [
"timestamp(timedelta=1791.0, similarity=0.9041927577945027)"
] | 27199325ec5c45260b9ea6849ea91bffe0ab7864 | efd771e0723357f20fe165765964e97bbc4eca49 | [
"I'm working on it!\n",
"@tainarareis do you want me to help you?\n"
] | [] | "2015-11-14T18:58:35Z" | [
"type: bug",
"info: good first issue"
] | No main method in the Abstract Factory example | There is no `main` method in the Abstract Factory example.
| [
"abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java"
] | [
"abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java"
] | [] | diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java
index 5b93f0e46b0c..9a32a091a899 100644
--- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java
+++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java
@@ -23,6 +23,7 @@ public class App {
private Castle castle;
private Army army;
+
/**
* Creates kingdom
*
@@ -77,4 +78,33 @@ public Army getArmy() {
private void setArmy(final Army army) {
this.army = army;
}
+
+
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+
+ App app = new App();
+
+ System.out.println("Elf Kingdom");
+ KingdomFactory elfKingdomFactory;
+ elfKingdomFactory = app.getElfKingdomFactory();
+ app.createKingdom(elfKingdomFactory);
+ System.out.println(app.getArmy().getDescription());
+ System.out.println(app.getCastle().getDescription());
+ System.out.println(app.getKing().getDescription());
+
+ System.out.println("\nOrc Kingdom");
+ KingdomFactory orcKingdomFactory;
+ orcKingdomFactory = app.getOrcKingdomFactory();
+ app.createKingdom(orcKingdomFactory);
+ System.out.println(app.getArmy().getDescription());
+ System.out.println(app.getCastle().getDescription());
+ System.out.println(app.getKing().getDescription());
+
+ }
+
}
| null | test | train | "2015-11-07T10:48:51" | "2015-11-11T06:05:52Z" | iluwatar | train |
iluwatar/java-design-patterns/216_305 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/216 | iluwatar/java-design-patterns/305 | [
"keyword_pr_to_issue",
"timestamp(timedelta=3.0, similarity=0.9066002615815714)"
] | 092d48d15091cb950232c44d76c0243fa8de53a2 | c1f85587d65f557e4148b5f98ee71a13716b64e9 | [
"Hi @stephen-lazarionok and thanks for pointing out the interesting article. We would like to improve the example so that it would better distinguish Repository from DAO. I noticed that the class naming could be improved and maybe add a query method that takes criteria as a parameter like they have in the article. Can you pinpoint more improvements we should apply? PRs are welcome too, if you would rather work that way.\n",
"I can work on Repository pattern and improve it. The only thing that I do not have enough time as I took some patterns to implement and in addition to that I have real projects I've been working on. So it may take some weeks to implement all the stuff on me :) If it is okay then I will go ahead.\n\nI did not review all the code I just took a look at the repository pattern implementation to find out what is a default DB is used and saw that issue :) That is why I raised it. Once I get some spare time I will check out the rest of the codebase.\n",
"I can work upon the udpates required for correcting the Repository pattern, as desired by @stephen-lazarionok. Let me know if that would be okay.\n",
"@shaileshkhose Sure go ahead. Your contribution is welcome.\n",
"The Repository Pattern is so awesome compare to the Dao Pattern, and this issue has nothing progress since Aug. \nI want to work on this issue, let me know if that would be okay.\n",
"Great @hoswey go ahead!\n"
] | [] | "2015-11-27T03:30:15Z" | [
"type: bug",
"info: help wanted",
"type: enhancement"
] | Repository vs DAO | I think that Repository pattern is not implemented in the correct way and it looks like DAO. Here is a good article about this http://thinkinginobjects.com/2012/08/26/dont-use-dao-use-repository/
| [
"pom.xml",
"repository/etc/repository.ucls",
"repository/index.md",
"repository/pom.xml",
"repository/src/main/java/com/iluwatar/repository/App.java",
"repository/src/main/java/com/iluwatar/repository/Person.java",
"repository/src/main/java/com/iluwatar/repository/PersonRepository.java",
"repository/src/main/resources/applicationContext.xml"
] | [
"pom.xml",
"repository/etc/repository.ucls",
"repository/index.md",
"repository/pom.xml",
"repository/src/main/java/com/iluwatar/repository/App.java",
"repository/src/main/java/com/iluwatar/repository/Person.java",
"repository/src/main/java/com/iluwatar/repository/PersonRepository.java",
"repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java",
"repository/src/main/resources/applicationContext.xml"
] | [
"repository/src/test/java/com/iluwatar/repository/RepositoryTest.java"
] | diff --git a/pom.xml b/pom.xml
index bcdf9affe8f1..e6603b06c58e 100644
--- a/pom.xml
+++ b/pom.xml
@@ -11,6 +11,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<hibernate.version>5.0.1.Final</hibernate.version>
+ <spring.version>4.1.7.RELEASE</spring.version>
<spring-data.version>1.9.0.RELEASE</spring-data.version>
<h2.version>1.4.188</h2.version>
<junit.version>4.12</junit.version>
@@ -20,6 +21,7 @@
<commons-dbcp.version>1.4</commons-dbcp.version>
<camel.version>2.15.3</camel.version>
<log4j.version>1.2.17</log4j.version>
+ <guava.version>18.0</guava.version>
</properties>
<modules>
<module>abstract-factory</module>
@@ -101,6 +103,11 @@
<version>${hibernate.version}</version>
</dependency>
<dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-test</artifactId>
+ <version>${spring.version}</version>
+ </dependency>
+ <dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data.version}</version>
@@ -142,6 +149,11 @@
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ <version>${guava.version}</version>
+ </dependency>
</dependencies>
</dependencyManagement>
diff --git a/repository/etc/repository.ucls b/repository/etc/repository.ucls
index 6c42019e1bd5..894e9434cccc 100644
--- a/repository/etc/repository.ucls
+++ b/repository/etc/repository.ucls
@@ -19,10 +19,48 @@
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</interface>
- <dependency id="3">
+ <class id="3" language="java" name="com.iluwatar.repository.PersonSpecifications.AgeBetweenSpec" project="repository"
+ file="/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java" binary="false"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="412" y="246"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <class id="4" language="java" name="com.iluwatar.repository.PersonSpecifications" project="repository"
+ file="/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java" binary="false"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="627" y="68"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <class id="5" language="java" name="com.iluwatar.repository.PersonSpecifications.NameEqualSpec" project="repository"
+ file="/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java" binary="false"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="834" y="238"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <nesting id="6">
+ <end type="SOURCE" refId="4"/>
+ <end type="TARGET" refId="3"/>
+ </nesting>
+ <dependency id="7">
<end type="SOURCE" refId="2"/>
<end type="TARGET" refId="1"/>
</dependency>
+ <nesting id="8">
+ <end type="SOURCE" refId="4"/>
+ <end type="TARGET" refId="5"/>
+ </nesting>
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
diff --git a/repository/index.md b/repository/index.md
index a65044d29637..8ecd16528cea 100644
--- a/repository/index.md
+++ b/repository/index.md
@@ -25,3 +25,9 @@ querying is utilized.
**Real world examples:**
* [Spring Data](http://projects.spring.io/spring-data/)
+
+**Credits:**
+
+* [Don’t use DAO, use Repository](http://thinkinginobjects.com/2012/08/26/dont-use-dao-use-repository/)
+* [Advanced Spring Data JPA - Specifications and Querydsl](https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/)
+
diff --git a/repository/pom.xml b/repository/pom.xml
index 60b51568e08a..c3adc7a922c2 100644
--- a/repository/pom.xml
+++ b/repository/pom.xml
@@ -1,35 +1,42 @@
<?xml version="1.0"?>
-<project
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
- xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>com.iluwatar</groupId>
- <artifactId>java-design-patterns</artifactId>
- <version>1.8.0-SNAPSHOT</version>
- </parent>
- <artifactId>repository</artifactId>
- <dependencies>
- <dependency>
- <groupId>org.springframework.data</groupId>
- <artifactId>spring-data-jpa</artifactId>
- </dependency>
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-entitymanager</artifactId>
- </dependency>
- <dependency>
- <groupId>commons-dbcp</groupId>
- <artifactId>commons-dbcp</artifactId>
- </dependency>
- <dependency>
- <groupId>com.h2database</groupId>
- <artifactId>h2</artifactId>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
+ xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>java-design-patterns</artifactId>
+ <version>1.8.0-SNAPSHOT</version>
+ </parent>
+ <artifactId>repository</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-test</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework.data</groupId>
+ <artifactId>spring-data-jpa</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-entitymanager</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>commons-dbcp</groupId>
+ <artifactId>commons-dbcp</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.h2database</groupId>
+ <artifactId>h2</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </dependency>
+ </dependencies>
</project>
diff --git a/repository/src/main/java/com/iluwatar/repository/App.java b/repository/src/main/java/com/iluwatar/repository/App.java
index fb9680cb6207..2442c854cd48 100644
--- a/repository/src/main/java/com/iluwatar/repository/App.java
+++ b/repository/src/main/java/com/iluwatar/repository/App.java
@@ -5,7 +5,6 @@
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
- *
* Repository pattern mediates between the domain and data mapping layers using a collection-like
* interface for accessing domain objects. A system with complex domain model often benefits from a
* layer that isolates domain objects from the details of the database access code and in such
@@ -16,9 +15,9 @@
* <p>
* In this example we utilize Spring Data to automatically generate a repository for us from the
* {@link Person} domain object. Using the {@link PersonRepository} we perform CRUD operations on
- * the entity. Underneath we have configured in-memory H2 database for which schema is created and
- * dropped on each run.
- *
+ * the entity, moreover, the query by {@link org.springframework.data.jpa.domain.Specification} are
+ * also performed. Underneath we have configured in-memory H2 database for which schema is created
+ * and dropped on each run.
*/
public class App {
@@ -28,16 +27,21 @@ public class App {
* @param args command line args
*/
public static void main(String[] args) {
+
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
PersonRepository repository = context.getBean(PersonRepository.class);
- Person peter = new Person("Peter", "Sagan");
- Person nasta = new Person("Nasta", "Kuzminova");
+ Person peter = new Person("Peter", "Sagan", 17);
+ Person nasta = new Person("Nasta", "Kuzminova", 25);
+ Person john = new Person("John", "lawrence", 35);
+ Person terry = new Person("Terry", "Law", 36);
// Add new Person records
repository.save(peter);
repository.save(nasta);
+ repository.save(john);
+ repository.save(terry);
// Count Person records
System.out.println("Count Person records: " + repository.count());
@@ -48,9 +52,6 @@ public static void main(String[] args) {
System.out.println(person);
}
- // Find Person by surname
- System.out.println("Find by surname 'Sagan': " + repository.findBySurname("Sagan"));
-
// Update Person
nasta.setName("Barbora");
nasta.setSurname("Spotakova");
@@ -61,9 +62,22 @@ public static void main(String[] args) {
// Remove record from Person
repository.delete(2L);
- // And finally count records
+ // count records
System.out.println("Count Person records: " + repository.count());
+ // find by name
+ Person p = repository.findOne(new PersonSpecifications.NameEqualSpec("John"));
+ System.out.println("Find by John is " + p);
+
+ // find by age
+ persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40));
+
+ System.out.println("Find Person with age between 20,40: ");
+ for (Person person : persons) {
+ System.out.println(person);
+ }
+
context.close();
+
}
}
diff --git a/repository/src/main/java/com/iluwatar/repository/Person.java b/repository/src/main/java/com/iluwatar/repository/Person.java
index 97d5e7120229..57439b8c0516 100644
--- a/repository/src/main/java/com/iluwatar/repository/Person.java
+++ b/repository/src/main/java/com/iluwatar/repository/Person.java
@@ -18,11 +18,14 @@ public class Person {
private String name;
private String surname;
+ private int age;
+
public Person() {}
- public Person(String name, String surname) {
+ public Person(String name, String surname, int age) {
this.name = name;
this.surname = surname;
+ this.age = age;
}
public Long getId() {
@@ -49,8 +52,59 @@ public void setSurname(String surname) {
this.surname = surname;
}
+
+ public int getAge() {
+ return age;
+ }
+
+ public void setAge(int age) {
+ this.age = age;
+ }
+
@Override
public String toString() {
- return "Person [id=" + id + ", name=" + name + ", surname=" + surname + "]";
+ return "Person [id=" + id + ", name=" + name + ", surname=" + surname + ", age=" + age + "]";
+ }
+
+ @Override
+ public int hashCode() {
+
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + age;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ result = prime * result + ((surname == null) ? 0 : surname.hashCode());
+ return result;
}
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ Person other = (Person) obj;
+ if (age != other.age)
+ return false;
+ if (id == null) {
+ if (other.id != null)
+ return false;
+ } else if (!id.equals(other.id))
+ return false;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+ if (surname == null) {
+ if (other.surname != null)
+ return false;
+ } else if (!surname.equals(other.surname))
+ return false;
+ return true;
+ }
+
}
diff --git a/repository/src/main/java/com/iluwatar/repository/PersonRepository.java b/repository/src/main/java/com/iluwatar/repository/PersonRepository.java
index 167b40d19545..98bb7abce02a 100644
--- a/repository/src/main/java/com/iluwatar/repository/PersonRepository.java
+++ b/repository/src/main/java/com/iluwatar/repository/PersonRepository.java
@@ -1,7 +1,6 @@
package com.iluwatar.repository;
-import java.util.List;
-
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@@ -11,7 +10,8 @@
*
*/
@Repository
-public interface PersonRepository extends CrudRepository<Person, Long> {
+public interface PersonRepository
+ extends CrudRepository<Person, Long>, JpaSpecificationExecutor<Person> {
- public List<Person> findBySurname(String surname);
+ public Person findByName(String name);
}
diff --git a/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java b/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java
new file mode 100644
index 000000000000..dadaae36b577
--- /dev/null
+++ b/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java
@@ -0,0 +1,50 @@
+package com.iluwatar.repository;
+
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.Predicate;
+import javax.persistence.criteria.Root;
+
+import org.springframework.data.jpa.domain.Specification;
+
+/**
+ * Helper class, includes vary Specification as the abstraction of sql query criteria
+ */
+public class PersonSpecifications {
+
+ public static class AgeBetweenSpec implements Specification<Person> {
+
+ private int from;
+
+ private int to;
+
+ public AgeBetweenSpec(int from, int to) {
+ this.from = from;
+ this.to = to;
+ }
+
+ @Override
+ public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
+
+ return cb.between(root.get("age"), from, to);
+
+ }
+
+ }
+ public static class NameEqualSpec implements Specification<Person> {
+
+ public String name;
+
+ public NameEqualSpec(String name) {
+ this.name = name;
+ }
+
+ public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
+
+ return cb.equal(root.get("name"), this.name);
+
+ }
+ }
+
+}
+
diff --git a/repository/src/main/resources/applicationContext.xml b/repository/src/main/resources/applicationContext.xml
index 3fe15b2f6269..9322c9f64c63 100644
--- a/repository/src/main/resources/applicationContext.xml
+++ b/repository/src/main/resources/applicationContext.xml
@@ -6,10 +6,10 @@
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
- http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd">
-
- <jpa:repositories base-package="com.iluwatar" />
+ http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
+ <jpa:repositories base-package="com.iluwatar" base-class="org.springframework.data.jpa.repository.support.SimpleJpaRepository" />
+
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
| diff --git a/repository/src/test/java/com/iluwatar/repository/AppTest.java b/repository/src/test/java/com/iluwatar/repository/AppTest.java
deleted file mode 100644
index 929f619414e4..000000000000
--- a/repository/src/test/java/com/iluwatar/repository/AppTest.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.iluwatar.repository;
-
-import org.junit.Test;
-
-import com.iluwatar.repository.App;
-
-/**
- *
- * Application test
- *
- */
-public class AppTest {
-
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
-}
diff --git a/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java
new file mode 100644
index 000000000000..26689321a395
--- /dev/null
+++ b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java
@@ -0,0 +1,109 @@
+package com.iluwatar.repository;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+import java.util.List;
+
+import javax.annotation.Resource;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.google.common.collect.Lists;
+
+/**
+ * Test case to test the functions of {@link PersonRepository}, beside the CRUD functions, the query
+ * by {@link org.springframework.data.jpa.domain.Specification} are also test.
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
+public class RepositoryTest {
+
+ @Resource
+ private PersonRepository repository;
+
+ Person peter = new Person("Peter", "Sagan", 17);
+ Person nasta = new Person("Nasta", "Kuzminova", 25);
+ Person john = new Person("John", "lawrence", 35);
+ Person terry = new Person("Terry", "Law", 36);
+
+ List<Person> persons = Arrays.asList(peter, nasta, john, terry);
+
+ /**
+ * Prepare data for test
+ */
+ @Before
+ public void setup() {
+
+ repository.save(persons);
+ }
+
+ @Test
+ public void testFindAll() {
+
+ List<Person> actuals = Lists.newArrayList(repository.findAll());
+ assertTrue(actuals.containsAll(persons) && persons.containsAll(actuals));
+ }
+
+ @Test
+ public void testSave() {
+
+ Person terry = repository.findByName("Terry");
+ terry.setSurname("Lee");
+ terry.setAge(47);
+ repository.save(terry);
+
+ terry = repository.findByName("Terry");
+ assertEquals(terry.getSurname(), "Lee");
+ assertEquals(47, terry.getAge());
+ }
+
+ @Test
+ public void testDelete() {
+
+ Person terry = repository.findByName("Terry");
+ repository.delete(terry);
+
+ assertEquals(3, repository.count());
+ assertNull(repository.findByName("Terry"));
+ }
+
+ @Test
+ public void testCount() {
+
+ assertEquals(4, repository.count());
+ }
+
+ @Test
+ public void testFindAllByAgeBetweenSpec() {
+
+ List<Person> persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40));
+
+ assertEquals(3, persons.size());
+ assertTrue(persons.stream().allMatch((item) -> {
+ return item.getAge() > 20 && item.getAge() < 40;
+ }));
+ }
+
+ @Test
+ public void testFindOneByNameEqualSpec() {
+
+ Person actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry"));
+ assertEquals(terry, actual);
+ }
+
+ @After
+ public void cleanup() {
+
+ repository.deleteAll();
+ }
+
+}
+
| val | train | "2015-11-22T07:44:13" | "2015-08-16T18:43:28Z" | stephen-lazarionok | train |
iluwatar/java-design-patterns/310_314 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/310 | iluwatar/java-design-patterns/314 | [
"timestamp(timedelta=33.0, similarity=0.9488786238260379)"
] | e85308fbc47202203d61ed373957003a10753c1e | d4dfcfbf6af7fa03a9d6360f63fc76d8fca212d2 | [] | [] | "2015-12-08T21:26:21Z" | [
"info: help wanted",
"type: enhancement",
"info: good first issue"
] | Functional approach to Strategy pattern | The Strategy pattern example should include Java 8 specific solution.
For inspiration, read this: http://alvinalexander.com/scala/how-scala-killed-oop-strategy-design-pattern
| [
"strategy/src/main/java/com/iluwatar/strategy/App.java",
"strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java"
] | [
"strategy/src/main/java/com/iluwatar/strategy/App.java",
"strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java"
] | [] | diff --git a/strategy/src/main/java/com/iluwatar/strategy/App.java b/strategy/src/main/java/com/iluwatar/strategy/App.java
index 272e56cf9e51..e2bcfef8a35e 100644
--- a/strategy/src/main/java/com/iluwatar/strategy/App.java
+++ b/strategy/src/main/java/com/iluwatar/strategy/App.java
@@ -5,6 +5,10 @@
* The Strategy pattern (also known as the policy pattern) is a software design pattern that enables
* an algorithm's behavior to be selected at runtime.
* <p>
+ * Before Java 8 the Strategies needed to be separate classes forcing the developer
+ * to write lots of boilerplate code. With modern Java it is easy to pass behavior
+ * with method references and lambdas making the code shorter and more readable.
+ * <p>
* In this example ({@link DragonSlayingStrategy}) encapsulates an algorithm. The containing object
* ({@link DragonSlayer}) can alter its behavior by changing its strategy.
*
@@ -17,6 +21,7 @@ public class App {
* @param args command line args
*/
public static void main(String[] args) {
+ // GoF Strategy pattern
System.out.println("Green dragon spotted ahead!");
DragonSlayer dragonSlayer = new DragonSlayer(new MeleeStrategy());
dragonSlayer.goToBattle();
@@ -26,5 +31,19 @@ public static void main(String[] args) {
System.out.println("Black dragon lands before you.");
dragonSlayer.changeStrategy(new SpellStrategy());
dragonSlayer.goToBattle();
+
+ // Java 8 Strategy pattern
+ System.out.println("Green dragon spotted ahead!");
+ dragonSlayer = new DragonSlayer(
+ () -> System.out.println("With your Excalibur you severe the dragon's head!"));
+ dragonSlayer.goToBattle();
+ System.out.println("Red dragon emerges.");
+ dragonSlayer.changeStrategy(() -> System.out.println(
+ "You shoot the dragon with the magical crossbow and it falls dead on the ground!"));
+ dragonSlayer.goToBattle();
+ System.out.println("Black dragon lands before you.");
+ dragonSlayer.changeStrategy(() -> System.out.println(
+ "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"));
+ dragonSlayer.goToBattle();
}
}
diff --git a/strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java b/strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java
index e17e5fbf00bf..aa57c34f0fc0 100644
--- a/strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java
+++ b/strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java
@@ -5,6 +5,7 @@
* Strategy interface.
*
*/
+@FunctionalInterface
public interface DragonSlayingStrategy {
void execute();
| null | train | train | "2015-12-08T19:53:15" | "2015-12-06T11:32:15Z" | iluwatar | train |
iluwatar/java-design-patterns/334_337 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/334 | iluwatar/java-design-patterns/337 | [
"timestamp(timedelta=3.0, similarity=0.8682567792127716)"
] | e0e51324dbbfdfbc54c41327ea22e25f0b849278 | dd91243ff038934f9fc888bf430a5994c67a080f | [
"I have added an example, not sure if this is really what you're asking for.\n"
] | [] | "2016-01-01T23:44:03Z" | [
"info: help wanted",
"type: enhancement",
"info: good first issue"
] | Callback implemented with lambdas | In the Callback example show how to implement the same thing with Java 8 lambdas.
| [] | [
"callback/src/main/java/com/iluwatar/callback/LambdasApp.java"
] | [
"callback/src/test/java/com/iluwatar/callback/AppTest.java"
] | diff --git a/callback/src/main/java/com/iluwatar/callback/LambdasApp.java b/callback/src/main/java/com/iluwatar/callback/LambdasApp.java
new file mode 100644
index 000000000000..19dd17eae441
--- /dev/null
+++ b/callback/src/main/java/com/iluwatar/callback/LambdasApp.java
@@ -0,0 +1,19 @@
+package com.iluwatar.callback;
+
+/**
+ *
+ * This example generates the exact same output as {@link App} however the callback has been
+ * defined as a Lambdas expression.
+ *
+ */
+public class LambdasApp {
+
+ /**
+ * Program entry point
+ */
+ public static void main(String[] args) {
+ Task task = new SimpleTask();
+ Callback c = () -> System.out.println("I'm done now.");
+ task.executeWith(c);
+ }
+}
| diff --git a/callback/src/test/java/com/iluwatar/callback/AppTest.java b/callback/src/test/java/com/iluwatar/callback/AppTest.java
index 67046a175590..28d6eaa1cea1 100644
--- a/callback/src/test/java/com/iluwatar/callback/AppTest.java
+++ b/callback/src/test/java/com/iluwatar/callback/AppTest.java
@@ -36,4 +36,22 @@ public void call() {
assertEquals("Callback called twice", new Integer(2), callingCount);
}
+
+ @Test
+ public void testWithLambdasExample() {
+ Callback callback = () -> callingCount++;
+
+ Task task = new SimpleTask();
+
+ assertEquals("Initial calling count of 0", new Integer(0), callingCount);
+
+ task.executeWith(callback);
+
+ assertEquals("Callback called once", new Integer(1), callingCount);
+
+ task.executeWith(callback);
+
+ assertEquals("Callback called twice", new Integer(2), callingCount);
+
+ }
}
| train | train | "2016-01-01T19:39:20" | "2015-12-31T09:46:51Z" | iluwatar | train |
iluwatar/java-design-patterns/264_340 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/264 | iluwatar/java-design-patterns/340 | [
"timestamp(timedelta=79.0, similarity=0.981666368921619)"
] | 4c5f9ae44c36f7fcc9dd8e2b4ef7bcfca0207720 | 2d4e1118113926ff91062d8a5d826b56462d9fd6 | [
"I would suggest that we change the example so that `SmartTroll extends Troll`. It wouldn't hurt to add `Goblin` to the example too :smile: \n",
"@iluwatar \nThat would be a possible solution too, but the SmartTroll doesn't do anything Troll-specific (allthough the string \"The troll throws a rock at you!\" is hardcoded). It just increases the attack power.\n",
"Pl tell me what should I do....I am new to Open source and i want to make it as my first commit\nThankyou\n",
"@opg7371 \nYou could rename the SmartTroll-class to SmartHostile and replace the hardcoded strings in that class with generic examples (e.g. \"It throws a rock at you!\").\n",
"Since this issue hasn't been update for a while, I would like to give it a try. I renamed the SmartTroll-class to SmartHostile and replaced the hardcoded strings in that class to \"It throws a rock at you!\"\nI also updated the class naming in the UML digram.\n\n I would like to submit a pull request. :)\n"
] | [
"This method should be renamed to testSmartHostile\n"
] | "2016-01-04T15:12:59Z" | [
"info: help wanted",
"info: good first issue"
] | Decorator pattern: SmartTroll should be SmartHostile | As the SmartTroll decorates any Hostile object, it should be named SmartHostile instead. Because if there's a Goblin class implementing the Hostile interface, the SmartTroll class is technically able to decorate it too, even though it is named SmartTroll (which indicates that it should only be a Troll).
| [
"decorator/etc/decorator.ucls",
"decorator/src/main/java/com/iluwatar/decorator/App.java",
"decorator/src/main/java/com/iluwatar/decorator/SmartTroll.java"
] | [
"decorator/etc/decorator.ucls",
"decorator/src/main/java/com/iluwatar/decorator/App.java",
"decorator/src/main/java/com/iluwatar/decorator/SmartHostile.java"
] | [
"decorator/src/test/java/com/iluwatar/decorator/SmartHostileTest.java"
] | diff --git a/decorator/etc/decorator.ucls b/decorator/etc/decorator.ucls
index 7adb8c3a685a..a5353d4ecf4a 100644
--- a/decorator/etc/decorator.ucls
+++ b/decorator/etc/decorator.ucls
@@ -1,18 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
-<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
- realizations="true" associations="true" dependencies="false" nesting-relationships="true">
+<class-diagram version="1.1.9" icons="true" always-add-relationships="false" generalizations="true" realizations="true"
+ associations="true" dependencies="false" nesting-relationships="true" router="FAN">
<interface id="1" language="java" name="com.iluwatar.decorator.Hostile" project="decorator"
file="/decorator/src/main/java/com/iluwatar/decorator/Hostile.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="106" width="134" x="116" y="408"/>
+ <position height="-1" width="-1" x="554" y="188"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</interface>
- <class id="2" language="java" name="com.iluwatar.decorator.SmartTroll" project="decorator"
- file="/decorator/src/main/java/com/iluwatar/decorator/SmartTroll.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="124" width="134" x="116" y="244"/>
+ <class id="2" language="java" name="com.iluwatar.decorator.App" project="decorator"
+ file="/decorator/src/main/java/com/iluwatar/decorator/App.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="117" y="202"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
@@ -21,29 +21,46 @@
</class>
<class id="3" language="java" name="com.iluwatar.decorator.Troll" project="decorator"
file="/decorator/src/main/java/com/iluwatar/decorator/Troll.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="124" width="134" x="290" y="244"/>
+ <position height="-1" width="-1" x="315" y="100"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
- <realization id="4">
+ <class id="4" language="java" name="com.iluwatar.decorator.SmartHostile" project="decorator"
+ file="/decorator/src/main/java/com/iluwatar/decorator/SmartHostile.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="318" y="315"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <dependency id="5">
<end type="SOURCE" refId="2"/>
+ <end type="TARGET" refId="4"/>
+ </dependency>
+ <realization id="6">
+ <end type="SOURCE" refId="3"/>
<end type="TARGET" refId="1"/>
</realization>
- <association id="5">
- <end type="SOURCE" refId="2" navigable="false">
- <attribute id="6" name="decorated"/>
- <multiplicity id="7" minimum="0" maximum="1"/>
+ <association id="7">
+ <end type="SOURCE" refId="4" navigable="false">
+ <attribute id="8" name="decorated"/>
+ <multiplicity id="9" minimum="0" maximum="1"/>
</end>
<end type="TARGET" refId="1" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
- <realization id="8">
- <end type="SOURCE" refId="3"/>
+ <realization id="10">
+ <end type="SOURCE" refId="4"/>
<end type="TARGET" refId="1"/>
</realization>
+ <dependency id="11">
+ <end type="SOURCE" refId="2"/>
+ <end type="TARGET" refId="3"/>
+ </dependency>
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
diff --git a/decorator/src/main/java/com/iluwatar/decorator/App.java b/decorator/src/main/java/com/iluwatar/decorator/App.java
index d58d3b61a930..242e72d11bbf 100644
--- a/decorator/src/main/java/com/iluwatar/decorator/App.java
+++ b/decorator/src/main/java/com/iluwatar/decorator/App.java
@@ -8,7 +8,7 @@
* runtime.
* <p>
* In this example we show how the simple {@link Troll} first attacks and then flees the battle.
- * Then we decorate the {@link Troll} with a {@link SmartTroll} and perform the attack again. You
+ * Then we decorate the {@link Troll} with a {@link SmartHostile} and perform the attack again. You
* can see how the behavior changes after the decoration.
*
*/
@@ -30,7 +30,7 @@ public static void main(String[] args) {
// change the behavior of the simple troll by adding a decorator
System.out.println("\nA smart looking troll surprises you.");
- Hostile smart = new SmartTroll(troll);
+ Hostile smart = new SmartHostile(troll);
smart.attack();
smart.fleeBattle();
System.out.printf("Smart troll power %d.\n", smart.getAttackPower());
diff --git a/decorator/src/main/java/com/iluwatar/decorator/SmartTroll.java b/decorator/src/main/java/com/iluwatar/decorator/SmartHostile.java
similarity index 56%
rename from decorator/src/main/java/com/iluwatar/decorator/SmartTroll.java
rename to decorator/src/main/java/com/iluwatar/decorator/SmartHostile.java
index 93927237dfd8..93f494688e1a 100644
--- a/decorator/src/main/java/com/iluwatar/decorator/SmartTroll.java
+++ b/decorator/src/main/java/com/iluwatar/decorator/SmartHostile.java
@@ -1,34 +1,34 @@
package com.iluwatar.decorator;
/**
- * SmartTroll is a decorator for {@link Hostile} objects. The calls to the {@link Hostile} interface
+ * SmartHostile is a decorator for {@link Hostile} objects. The calls to the {@link Hostile} interface
* are intercepted and decorated. Finally the calls are delegated to the decorated {@link Hostile}
* object.
*
*/
-public class SmartTroll implements Hostile {
+public class SmartHostile implements Hostile {
private Hostile decorated;
- public SmartTroll(Hostile decorated) {
+ public SmartHostile(Hostile decorated) {
this.decorated = decorated;
}
@Override
public void attack() {
- System.out.println("The troll throws a rock at you!");
+ System.out.println("It throws a rock at you!");
decorated.attack();
}
@Override
public int getAttackPower() {
- // decorated troll power + 20 because it is smart
+ // decorated hostile's power + 20 because it is smart
return decorated.getAttackPower() + 20;
}
@Override
public void fleeBattle() {
- System.out.println("The troll calls for help!");
+ System.out.println("It calls for help!");
decorated.fleeBattle();
}
}
| diff --git a/decorator/src/test/java/com/iluwatar/decorator/SmartTrollTest.java b/decorator/src/test/java/com/iluwatar/decorator/SmartHostileTest.java
similarity index 85%
rename from decorator/src/test/java/com/iluwatar/decorator/SmartTrollTest.java
rename to decorator/src/test/java/com/iluwatar/decorator/SmartHostileTest.java
index faafc4a824f0..e5be32eae15a 100644
--- a/decorator/src/test/java/com/iluwatar/decorator/SmartTrollTest.java
+++ b/decorator/src/test/java/com/iluwatar/decorator/SmartHostileTest.java
@@ -11,15 +11,15 @@
*
* @author Jeroen Meulemeester
*/
-public class SmartTrollTest {
+public class SmartHostileTest {
@Test
- public void testSmartTroll() throws Exception {
+ public void testSmartHostile() throws Exception {
// Create a normal troll first, but make sure we can spy on it later on.
final Hostile simpleTroll = spy(new Troll());
// Now we want to decorate the troll to make it smarter ...
- final Hostile smartTroll = new SmartTroll(simpleTroll);
+ final Hostile smartTroll = new SmartHostile(simpleTroll);
assertEquals(30, smartTroll.getAttackPower());
verify(simpleTroll, times(1)).getAttackPower();
| train | train | "2016-01-04T02:15:37" | "2015-10-12T13:41:41Z" | Niko-O | train |
iluwatar/java-design-patterns/343_344 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/343 | iluwatar/java-design-patterns/344 | [
"timestamp(timedelta=8211.0, similarity=0.9325257067946403)",
"keyword_pr_to_issue"
] | 150c4e0d5d6f4e1831f997cfbb018ede3b6bd8d1 | 2fdc1d099bffbaa19e947595b2096b6e90dba93d | [
"From the log file of [Travis-Ci](https://api.travis-ci.org/jobs/101915401/log.txt?deansi=true), it pointouts that reader thread submited to the thread pool cannot be executed in 149(99+50)ms. I suspect that the Travis-Ci has a high load and it can't assume the read can executed in accurate time. I have revised the test case with another form. \n\n> Failed tests: \n> ReaderAndWriterTest.testReadAndWrite:45 \n> Wanted but not invoked:\n> reader.read();\n> -> at com.iluwatar.reader.writer.lock.ReaderAndWriterTest.testReadAndWrite(ReaderAndWriterTest.java:45)\n> \n> However, there were other interactions with this mock:\n> reader.run();\n> -> at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)\n\n``` java\n @Test\n public void testReadAndWrite() throws Exception {\n\n ReaderWriterLock lock = new ReaderWriterLock();\n\n Reader reader1 = spy(new Reader(\"Reader 1\", lock.readLock()));\n Writer writer1 = spy(new Writer(\"Writer 1\", lock.writeLock()));\n\n executeService.submit(reader1);\n // Let reader1 execute first\n Thread.sleep(50);\n executeService.submit(writer1);\n\n45: verify(reader1, timeout(99).atLeastOnce()).read();\n verify(writer1, after(10).never()).write();\n verify(writer1, timeout(100).atLeastOnce()).write();\n\n }\n```\n",
"@hoswey just create pull request when ready\n"
] | [] | "2016-01-14T01:01:02Z" | [
"type: bug"
] | ReaderWriterLock unit tests fail on CI | Something wrong with the ReaderWriterLock unit tests.
See Travis builds:
https://travis-ci.org/iluwatar/java-design-patterns/builds/101906103
https://travis-ci.org/iluwatar/java-design-patterns/builds/101915400
https://travis-ci.org/iluwatar/java-design-patterns/builds/101917864
| [
"reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java",
"reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java",
"reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java"
] | [
"reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java",
"reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java",
"reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java"
] | [
"reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java",
"reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java",
"reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/StdOutTest.java",
"reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java"
] | diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java
index 1d02b6cadc96..b11b11be76ca 100644
--- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java
+++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java
@@ -18,8 +18,7 @@
* readers will be blocked until the writer is finished writing.
*
* <p>
- * This example use two mutex to demonstrate the concurrent access of multiple readers and
- * writers.
+ * This example use two mutex to demonstrate the concurrent access of multiple readers and writers.
*
*
* @author hongshuwei@gmail.com
@@ -33,15 +32,15 @@ public class App {
*/
public static void main(String[] args) {
- ExecutorService executeService = Executors.newFixedThreadPool(1000);
+ ExecutorService executeService = Executors.newFixedThreadPool(10);
ReaderWriterLock lock = new ReaderWriterLock();
- // Start 10 readers
- IntStream.range(0, 10)
+ // Start 5 readers
+ IntStream.range(0, 5)
.forEach(i -> executeService.submit(new Reader("Reader " + i, lock.readLock())));
- // Start 10 writers
- IntStream.range(0, 10)
+ // Start 5 writers
+ IntStream.range(0, 5)
.forEach(i -> executeService.submit(new Writer("Writer " + i, lock.writeLock())));
// In the system console, it can see that the read operations are executed concurrently while
// write operations are exclusive.
diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java
index 5704fdf28a81..214528080810 100644
--- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java
+++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java
@@ -34,7 +34,7 @@ public void run() {
*/
public void read() throws InterruptedException {
System.out.println(name + " begin");
- Thread.sleep(100);
+ Thread.sleep(250);
System.out.println(name + " finish");
}
}
diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java
index d7afa385a5c2..ae7b17080ab2 100644
--- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java
+++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java
@@ -34,7 +34,7 @@ public void run() {
*/
public void write() throws InterruptedException {
System.out.println(name + " begin");
- Thread.sleep(100);
+ Thread.sleep(250);
System.out.println(name + " finish");
}
}
| diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java
index 3f3809be9b38..e29f578894b5 100644
--- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java
+++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java
@@ -1,87 +1,81 @@
package com.iluwatar.reader.writer.lock;
-import static org.mockito.Mockito.after;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.timeout;
-import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.inOrder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
import org.junit.Test;
+import org.mockito.InOrder;
/**
* @author hongshuwei@gmail.com
*/
-public class ReaderAndWriterTest {
+public class ReaderAndWriterTest extends StdOutTest {
- ExecutorService executeService;
- @Before
- public void setup() {
- executeService = Executors.newFixedThreadPool(2);
- }
/**
* Verify reader and writer can only get the lock to read and write orderly
*/
- @Ignore // intermittent failures when executed on CI
@Test
public void testReadAndWrite() throws Exception {
ReaderWriterLock lock = new ReaderWriterLock();
- Reader reader1 = spy(new Reader("Reader 1", lock.readLock()));
- Writer writer1 = spy(new Writer("Writer 1", lock.writeLock()));
+ Reader reader1 = new Reader("Reader 1", lock.readLock());
+ Writer writer1 = new Writer("Writer 1", lock.writeLock());
+ ExecutorService executeService = Executors.newFixedThreadPool(2);
executeService.submit(reader1);
// Let reader1 execute first
- Thread.sleep(50);
+ Thread.sleep(150);
executeService.submit(writer1);
- verify(reader1, timeout(99).atLeastOnce()).read();
- verify(writer1, after(10).never()).write();
- verify(writer1, timeout(100).atLeastOnce()).write();
+ executeService.shutdown();
+ try {
+ executeService.awaitTermination(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ System.out.println("Error waiting for ExecutorService shutdown");
+ }
+ final InOrder inOrder = inOrder(getStdOutMock());
+ inOrder.verify(getStdOutMock()).println("Reader 1 begin");
+ inOrder.verify(getStdOutMock()).println("Reader 1 finish");
+ inOrder.verify(getStdOutMock()).println("Writer 1 begin");
+ inOrder.verify(getStdOutMock()).println("Writer 1 finish");
}
/**
* Verify reader and writer can only get the lock to read and write orderly
*/
- @Ignore // intermittent failures when executed on CI
@Test
public void testWriteAndRead() throws Exception {
ExecutorService executeService = Executors.newFixedThreadPool(2);
ReaderWriterLock lock = new ReaderWriterLock();
- Reader reader1 = spy(new Reader("Reader 1", lock.readLock()));
- Writer writer1 = spy(new Writer("Writer 1", lock.writeLock()));
+ Reader reader1 = new Reader("Reader 1", lock.readLock());
+ Writer writer1 = new Writer("Writer 1", lock.writeLock());
executeService.submit(writer1);
- // Let reader1 execute first
- Thread.sleep(50);
+ // Let writer1 execute first
+ Thread.sleep(150);
executeService.submit(reader1);
- verify(writer1, timeout(99).atLeastOnce()).write();
- verify(reader1, after(10).never()).read();
- verify(reader1, timeout(100).atLeastOnce()).read();
-
-
- }
-
- @After
- public void tearDown() {
executeService.shutdown();
try {
executeService.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
System.out.println("Error waiting for ExecutorService shutdown");
}
+
+ final InOrder inOrder = inOrder(getStdOutMock());
+ inOrder.verify(getStdOutMock()).println("Writer 1 begin");
+ inOrder.verify(getStdOutMock()).println("Writer 1 finish");
+ inOrder.verify(getStdOutMock()).println("Reader 1 begin");
+ inOrder.verify(getStdOutMock()).println("Reader 1 finish");
}
}
diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java
index f4cfbeb93403..e76fe29c249d 100644
--- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java
+++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java
@@ -1,25 +1,23 @@
package com.iluwatar.reader.writer.lock;
+import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.timeout;
-import static org.mockito.Mockito.verify;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
-import org.junit.Ignore;
import org.junit.Test;
+import org.mockito.InOrder;
/**
* @author hongshuwei@gmail.com
*/
-public class ReaderTest {
+public class ReaderTest extends StdOutTest {
/**
* Verify that multiple readers can get the read lock concurrently
*/
- @Ignore // intermittent failures when executed on CI
@Test
public void testRead() throws Exception {
@@ -30,18 +28,23 @@ public void testRead() throws Exception {
Reader reader2 = spy(new Reader("Reader 2", lock.readLock()));
executeService.submit(reader1);
+ Thread.sleep(150);
executeService.submit(reader2);
- // Read operation will hold the read lock 100 milliseconds, so here we guarantee that each
- // readers can read in 99 milliseconds to prove that multiple read can perform in the same time.
- verify(reader1, timeout(99).atLeastOnce()).read();
- verify(reader2, timeout(99).atLeastOnce()).read();
-
executeService.shutdown();
try {
executeService.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
System.out.println("Error waiting for ExecutorService shutdown");
}
+
+ // Read operation will hold the read lock 250 milliseconds, so here we prove that multiple reads
+ // can be performed in the same time.
+ final InOrder inOrder = inOrder(getStdOutMock());
+ inOrder.verify(getStdOutMock()).println("Reader 1 begin");
+ inOrder.verify(getStdOutMock()).println("Reader 2 begin");
+ inOrder.verify(getStdOutMock()).println("Reader 1 finish");
+ inOrder.verify(getStdOutMock()).println("Reader 2 finish");
+
}
}
diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/StdOutTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/StdOutTest.java
new file mode 100644
index 000000000000..762574b66bb0
--- /dev/null
+++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/StdOutTest.java
@@ -0,0 +1,53 @@
+package com.iluwatar.reader.writer.lock;
+
+import org.junit.After;
+import org.junit.Before;
+
+import java.io.PrintStream;
+
+import static org.mockito.Mockito.mock;
+
+/**
+ * Date: 12/10/15 - 8:37 PM
+ *
+ * @author Jeroen Meulemeester
+ */
+public abstract class StdOutTest {
+
+ /**
+ * The mocked standard out {@link PrintStream}, required since some actions don't have any
+ * influence on accessible objects, except for writing to std-out using {@link System#out}
+ */
+ private final PrintStream stdOutMock = mock(PrintStream.class);
+
+ /**
+ * Keep the original std-out so it can be restored after the test
+ */
+ private final PrintStream stdOutOrig = System.out;
+
+ /**
+ * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test
+ */
+ @Before
+ public void setUp() {
+ System.setOut(this.stdOutMock);
+ }
+
+ /**
+ * Removed the mocked std-out {@link PrintStream} again from the {@link System} class
+ */
+ @After
+ public void tearDown() {
+ System.setOut(this.stdOutOrig);
+ }
+
+ /**
+ * Get the mocked stdOut {@link PrintStream}
+ *
+ * @return The stdOut print stream mock, renewed before each test
+ */
+ final PrintStream getStdOutMock() {
+ return this.stdOutMock;
+ }
+
+}
diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java
index 97879025d59b..ed37bf3e51aa 100644
--- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java
+++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java
@@ -1,26 +1,23 @@
package com.iluwatar.reader.writer.lock;
-import static org.mockito.Mockito.after;
+import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.timeout;
-import static org.mockito.Mockito.verify;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
-import org.junit.Ignore;
import org.junit.Test;
+import org.mockito.InOrder;
/**
* @author hongshuwei@gmail.com
*/
-public class WriterTest {
+public class WriterTest extends StdOutTest {
/**
* Verify that multiple writers will get the lock in order.
*/
- @Ignore // intermittent failures when executed on CI
@Test
public void testWrite() throws Exception {
@@ -32,23 +29,22 @@ public void testWrite() throws Exception {
executeService.submit(writer1);
// Let write1 execute first
- Thread.sleep(50);
+ Thread.sleep(150);
executeService.submit(writer2);
- // Write operation will hold the write lock 100 milliseconds, so here we verify that when two
- // write excute concurrently
- // 1. The first write will get the lock and and write in 60ms
- // 2. The second writer will cannot get the lock when first writer get the lock
- // 3. The second writer will get the lock as last
- verify(writer1, timeout(10).atLeastOnce()).write();
- verify(writer2, after(10).never()).write();
- verify(writer2, timeout(100).atLeastOnce()).write();
-
executeService.shutdown();
try {
executeService.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
System.out.println("Error waiting for ExecutorService shutdown");
}
+ // Write operation will hold the write lock 250 milliseconds, so here we verify that when two
+ // writer execute concurrently, the second writer can only writes only when the first one is
+ // finished.
+ final InOrder inOrder = inOrder(getStdOutMock());
+ inOrder.verify(getStdOutMock()).println("Writer 1 begin");
+ inOrder.verify(getStdOutMock()).println("Writer 1 finish");
+ inOrder.verify(getStdOutMock()).println("Writer 2 begin");
+ inOrder.verify(getStdOutMock()).println("Writer 2 finish");
}
}
| val | train | "2016-01-12T20:16:39" | "2016-01-12T19:23:25Z" | iluwatar | train |
iluwatar/java-design-patterns/349_362 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/349 | iluwatar/java-design-patterns/362 | [
"timestamp(timedelta=96.0, similarity=0.9023621712956228)"
] | 33224dd7d7b6d4d3a0845ba8f9ecdf5d699ca2e9 | a3a075b38e6dd437a976822ecfceb0c24c4110ea | [
"I think the definition of the Value Object is fairly comprehensive.\nThinking of implementing a pattern. How about this : VALJO - Value Java Objects\nwhich has more strict set of rules for a correctly defined immutable value object. \nSuggested by Stephen Colebourne.\nhttp://blog.joda.org/2014/03/valjos-value-java-objects.html\nIf this is not bad I want to work on this.\n",
"This is a good specification. I think we're still talking about the same Value Object pattern even though the author mr. Colebourne invents this new term VALJO. So my suggestion would be to implement the Value Object pattern using the VALJO specs. Does this sound reasonable?\n",
":+1: Yes it is. I will get these details in the code and documentation. Can I work on this?\n",
"@JuhoKang Sure go ahead. :+1: I will update the labels.\n"
] | [
"Did you mean to change this file?\n",
"Did you mean to change this?\n",
"Please describe the pattern and the example here. For reference, see other pattern examples.\n",
"I don't know why these blanks exist and make differences in this file. I only added one line <module>value-object</module>.\n"
] | "2016-01-28T16:01:16Z" | [
"epic: pattern"
] | Value Object pattern | http://martinfowler.com/bliki/ValueObject.html
| [
"pom.xml"
] | [
"pom.xml",
"value-object/etc/value-object.ucls",
"value-object/index.md",
"value-object/pom.xml",
"value-object/src/main/java/com/iluwatar/value/object/App.java",
"value-object/src/main/java/com/iluwatar/value/object/HeroStat.java"
] | [
"value-object/src/test/java/com/iluwatar/value/object/AppTest.java",
"value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java"
] | diff --git a/pom.xml b/pom.xml
index 482110e64d06..c15ca20cfb1c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -120,6 +120,7 @@
<module>delegation</module>
<module>event-driven-architecture</module>
<module>feature-toggle</module>
+ <module>value-object</module>
</modules>
<dependencyManagement>
@@ -199,8 +200,8 @@
<build>
<pluginManagement>
<plugins>
- <!-- This plugin's configuration is used to store Eclipse m2e settings
- only. It has no influence on the Maven build itself. TODO: Remove when the
+ <!-- This plugin's configuration is used to store Eclipse m2e settings
+ only. It has no influence on the Maven build itself. TODO: Remove when the
m2e plugin can correctly bind to Maven lifecycle -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
@@ -256,10 +257,10 @@
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
- <!-- The following exclude configuration was added because error occurred
+ <!-- The following exclude configuration was added because error occurred
when executing "mvn clean test jacoco:report coveralls:report" -->
- <!-- [ERROR] Failed to execute goal org.eluder.coveralls:coveralls-maven-plugin:3.1.0:report
- (default-cli) on project java-design-patterns: I/O operation failed: No source
+ <!-- [ERROR] Failed to execute goal org.eluder.coveralls:coveralls-maven-plugin:3.1.0:report
+ (default-cli) on project java-design-patterns: I/O operation failed: No source
found for domainapp/dom/modules/simple/QSimpleObject.java -> [Help 1] -->
<configuration>
<excludes>
@@ -354,7 +355,7 @@
<excludeFromFailureFile>exclude-pmd.properties</excludeFromFailureFile>
</configuration>
</execution>
- </executions>
+ </executions>
</plugin>
<plugin>
@@ -390,5 +391,5 @@
</plugin>
</plugins>
</reporting>
-
+
</project>
diff --git a/value-object/etc/value-object.ucls b/value-object/etc/value-object.ucls
new file mode 100644
index 000000000000..7bbf5e47cfbd
--- /dev/null
+++ b/value-object/etc/value-object.ucls
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<class-diagram version="1.1.9" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
+ realizations="true" associations="true" dependencies="true" nesting-relationships="true" router="FAN">
+ <class id="1" language="java" name="com.iluwatar.value.object.HeroStat" project="value-object"
+ file="/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="520" y="337"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </classifier-display>
+ <association-display labels="true" multiplicity="true"/>
+</class-diagram>
\ No newline at end of file
diff --git a/value-object/index.md b/value-object/index.md
new file mode 100644
index 000000000000..83223d8a2377
--- /dev/null
+++ b/value-object/index.md
@@ -0,0 +1,34 @@
+---
+layout: pattern
+title: Value Object
+folder: value-object
+permalink: /patterns/value-object/
+categories: Creational
+tags:
+ - Java
+ - Difficulty-Beginner
+---
+
+## Intent
+Provide objects which follow value semantics rather than reference semantics.
+This means value objects' equality are not based on identity. Two value objects are
+equal when they have the same value, not necessarily being the same object.
+
+![alt text](./etc/value-object.png "Value Object")
+
+## Applicability
+Use the Value Object when
+
+* you need to measure the objects' equality based on the objects' value
+
+## Real world examples
+
+* [java.util.Optional](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html)
+* [java.time.LocalDate](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html)
+* [joda-time, money, beans](http://www.joda.org/)
+
+## Credits
+
+* [Patterns of Enterprise Application Architecture](http://www.martinfowler.com/books/eaa.html)
+* [VALJOs - Value Java Objects : Stephen Colebourne's blog](http://blog.joda.org/2014/03/valjos-value-java-objects.html)
+* [Value Object : Wikipedia](https://en.wikipedia.org/wiki/Value_object)
diff --git a/value-object/pom.xml b/value-object/pom.xml
new file mode 100644
index 000000000000..1ed2adb4377c
--- /dev/null
+++ b/value-object/pom.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0"?>
+<project
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
+ xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>java-design-patterns</artifactId>
+ <version>1.11.0-SNAPSHOT</version>
+ </parent>
+ <artifactId>value-object</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava-testlib</artifactId>
+ <version>19.0</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
diff --git a/value-object/src/main/java/com/iluwatar/value/object/App.java b/value-object/src/main/java/com/iluwatar/value/object/App.java
new file mode 100644
index 000000000000..85779fcb78ac
--- /dev/null
+++ b/value-object/src/main/java/com/iluwatar/value/object/App.java
@@ -0,0 +1,32 @@
+package com.iluwatar.value.object;
+
+/**
+ * A Value Object are objects which follow value semantics rather than reference semantics. This
+ * means value objects' equality are not based on identity. Two value objects are equal when they
+ * have the same value, not necessarily being the same object..
+ *
+ * Value Objects must override equals(), hashCode() to check the equality with values.
+ * Value Objects should be immutable so declare members final.
+ * Obtain instances by static factory methods.
+ * The elements of the state must be other values, including primitive types.
+ * Provide methods, typically simple getters, to get the elements of the state.
+ * A Value Object must check equality with equals() not ==
+ *
+ * For more specific and strict rules to implement value objects check the rules from Stephen
+ * Colebourne's term VALJO : http://blog.joda.org/2014/03/valjos-value-java-objects.html
+ */
+public class App {
+ /**
+ * This practice creates three HeroStats(Value object) and checks equality between those.
+ */
+ public static void main(String[] args) {
+ HeroStat statA = HeroStat.valueOf(10, 5, 0);
+ HeroStat statB = HeroStat.valueOf(10, 5, 0);
+ HeroStat statC = HeroStat.valueOf(5, 1, 8);
+
+ System.out.println(statA.toString());
+
+ System.out.println("Is statA and statB equal : " + statA.equals(statB));
+ System.out.println("Is statA and statC equal : " + statA.equals(statC));
+ }
+}
diff --git a/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java b/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java
new file mode 100644
index 000000000000..101837db068b
--- /dev/null
+++ b/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java
@@ -0,0 +1,90 @@
+package com.iluwatar.value.object;
+
+/**
+ * HeroStat is a value object
+ *
+ * {@link http://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html}
+ */
+public class HeroStat {
+
+ // Stats for a hero
+
+ private final int strength;
+ private final int intelligence;
+ private final int luck;
+
+ // All constructors must be private.
+ private HeroStat(int strength, int intelligence, int luck) {
+ super();
+ this.strength = strength;
+ this.intelligence = intelligence;
+ this.luck = luck;
+ }
+
+ // Static factory method to create new instances.
+ public static HeroStat valueOf(int strength, int intelligence, int luck) {
+ return new HeroStat(strength, intelligence, luck);
+ }
+
+ public int getStrength() {
+ return strength;
+ }
+
+ public int getIntelligence() {
+ return intelligence;
+ }
+
+ public int getLuck() {
+ return luck;
+ }
+
+ /*
+ * Recommended to provide a static factory method capable of creating an instance from the formal
+ * string representation declared like this. public static HeroStat parse(String string) {}
+ */
+
+ // toString, hashCode, equals
+
+ @Override
+ public String toString() {
+ return "HeroStat [strength=" + strength + ", intelligence=" + intelligence
+ + ", luck=" + luck + "]";
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + intelligence;
+ result = prime * result + luck;
+ result = prime * result + strength;
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ HeroStat other = (HeroStat) obj;
+ if (intelligence != other.intelligence) {
+ return false;
+ }
+ if (luck != other.luck) {
+ return false;
+ }
+ if (strength != other.strength) {
+ return false;
+ }
+ return true;
+ }
+
+ // The clone() method should not be public. Just don't override it.
+
+}
| diff --git a/value-object/src/test/java/com/iluwatar/value/object/AppTest.java b/value-object/src/test/java/com/iluwatar/value/object/AppTest.java
new file mode 100644
index 000000000000..aed3c2f20511
--- /dev/null
+++ b/value-object/src/test/java/com/iluwatar/value/object/AppTest.java
@@ -0,0 +1,15 @@
+package com.iluwatar.value.object;
+
+import org.junit.Test;
+
+/**
+ * Application test
+ */
+public class AppTest {
+
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
+}
diff --git a/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java b/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java
new file mode 100644
index 000000000000..785a4d8fefb0
--- /dev/null
+++ b/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java
@@ -0,0 +1,44 @@
+package com.iluwatar.value.object;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+
+import static org.junit.Assert.assertThat;
+
+import com.google.common.testing.EqualsTester;
+
+import org.junit.Test;
+
+/**
+ * Unit test for HeroStat.
+ */
+public class HeroStatTest {
+
+ /**
+ * Tester for equals() and hashCode() methods of a class. Using guava's EqualsTester.
+ *
+ * @see http://static.javadoc.io/com.google.guava/guava-testlib/19.0/com/google/common/testing/
+ * EqualsTester.html
+ */
+ @Test
+ public void testEquals() {
+ HeroStat heroStatA = HeroStat.valueOf(3, 9, 2);
+ HeroStat heroStatB = HeroStat.valueOf(3, 9, 2);
+ new EqualsTester().addEqualityGroup(heroStatA, heroStatB).testEquals();
+ }
+
+ /**
+ * The toString() for two equal values must be the same. For two non-equal values it must be
+ * different.
+ */
+ @Test
+ public void testToString() {
+ HeroStat heroStatA = HeroStat.valueOf(3, 9, 2);
+ HeroStat heroStatB = HeroStat.valueOf(3, 9, 2);
+ HeroStat heroStatC = HeroStat.valueOf(3, 9, 8);
+
+ assertThat(heroStatA.toString(), is(heroStatB.toString()));
+ assertThat(heroStatA.toString(), is(not(heroStatC.toString())));
+ }
+
+}
| test | train | "2016-02-02T21:14:20" | "2016-01-16T10:48:23Z" | iluwatar | train |
iluwatar/java-design-patterns/333_377 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/333 | iluwatar/java-design-patterns/377 | [
"timestamp(timedelta=94187.0, similarity=0.8532308169437328)"
] | 823dc6395fbba21d77d793ac8997381b045824e9 | 985232ceaa1e0ac0ec2ea14a706b9063218edad7 | [] | [] | "2016-02-12T10:25:05Z" | [
"info: help wanted",
"epic: pattern",
"type: enhancement"
] | Abstract Factory implemented with lambdas | In the Abstract Factory example show how to implement the pattern with Java 8 lambdas.
There is an example in this talk: https://youtu.be/-k2X7guaArU
| [
"abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java",
"factory-method/src/main/java/com/iluwatar/factory/method/App.java"
] | [
"abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java",
"factory-method/src/main/java/com/iluwatar/factory/method/App.java"
] | [
"abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java",
"factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java"
] | diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java
index 15265c0d4e8f..aae396f1dc26 100644
--- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java
+++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java
@@ -52,14 +52,6 @@ public void createKingdom(final KingdomFactory factory) {
setArmy(factory.createArmy());
}
- ElfKingdomFactory getElfKingdomFactory() {
- return new ElfKingdomFactory();
- }
-
- OrcKingdomFactory getOrcKingdomFactory() {
- return new OrcKingdomFactory();
- }
-
King getKing(final KingdomFactory factory) {
return factory.createKing();
}
@@ -107,17 +99,13 @@ public static void main(String[] args) {
App app = new App();
System.out.println("Elf Kingdom");
- KingdomFactory elfKingdomFactory;
- elfKingdomFactory = app.getElfKingdomFactory();
- app.createKingdom(elfKingdomFactory);
+ app.createKingdom(new ElfKingdomFactory());
System.out.println(app.getArmy().getDescription());
System.out.println(app.getCastle().getDescription());
System.out.println(app.getKing().getDescription());
System.out.println("\nOrc Kingdom");
- KingdomFactory orcKingdomFactory;
- orcKingdomFactory = app.getOrcKingdomFactory();
- app.createKingdom(orcKingdomFactory);
+ app.createKingdom(new OrcKingdomFactory());
System.out.println(app.getArmy().getDescription());
System.out.println(app.getCastle().getDescription());
System.out.println(app.getKing().getDescription());
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/App.java b/factory-method/src/main/java/com/iluwatar/factory/method/App.java
index 4056f335c703..cd7a6e6e7045 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/App.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/App.java
@@ -38,25 +38,40 @@
*/
public class App {
+ private final Blacksmith blacksmith;
+
+ /**
+ * Creates an instance of <code>App</code> which will use <code>blacksmith</code> to manufacture
+ * the weapons for war.
+ * <code>App</code> is unaware which concrete implementation of {@link Blacksmith} it is using.
+ * The decision of which blacksmith implementation to use may depend on configuration, or
+ * the type of rival in war.
+ * @param blacksmith a non-null implementation of blacksmith
+ */
+ public App(Blacksmith blacksmith) {
+ this.blacksmith = blacksmith;
+ }
+
/**
* Program entry point
*
* @param args command line args
*/
public static void main(String[] args) {
- Blacksmith blacksmith;
+ // Lets go to war with Orc weapons
+ App app = new App(new OrcBlacksmith());
+ app.manufactureWeapons();
+
+ // Lets go to war with Elf weapons
+ app = new App(new ElfBlacksmith());
+ app.manufactureWeapons();
+ }
+
+ private void manufactureWeapons() {
Weapon weapon;
-
- blacksmith = new OrcBlacksmith();
weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
System.out.println(weapon);
weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
System.out.println(weapon);
-
- blacksmith = new ElfBlacksmith();
- weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD);
- System.out.println(weapon);
- weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
- System.out.println(weapon);
}
}
| diff --git a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java
index 5eb083deb2ef..216f0443ae1c 100644
--- a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java
+++ b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java
@@ -36,8 +36,8 @@ public class AbstractFactoryTest {
@Before
public void setUp() {
- elfFactory = app.getElfKingdomFactory();
- orcFactory = app.getOrcKingdomFactory();
+ elfFactory = new ElfKingdomFactory();
+ orcFactory = new OrcKingdomFactory();
}
@Test
diff --git a/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java b/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java
index 40515d4c940c..2f8d1c9bbe8d 100644
--- a/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java
+++ b/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java
@@ -93,7 +93,7 @@ public void testElfBlacksmithWithSpear() {
* @param expectedWeaponType expected WeaponType of the weapon
* @param clazz expected class of the weapon
*/
- private void verifyWeapon(Weapon weapon, WeaponType expectedWeaponType, Class clazz) {
+ private void verifyWeapon(Weapon weapon, WeaponType expectedWeaponType, Class<?> clazz) {
assertTrue("Weapon must be an object of: " + clazz.getName(), clazz.isInstance(weapon));
assertEquals("Weapon must be of weaponType: " + clazz.getName(), expectedWeaponType,
weapon.getWeaponType());
| test | train | "2016-02-12T11:14:31" | "2015-12-31T09:41:49Z" | iluwatar | train |
iluwatar/java-design-patterns/335_388 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/335 | iluwatar/java-design-patterns/388 | [
"timestamp(timedelta=57.0, similarity=1.0000000000000002)"
] | dfef28e93eb942fc8e9ca12eca64e0ae568aa6b2 | 885018b7485f20d8817246a73df819e21fb1e8e6 | [
"One more useful link: https://channel9.msdn.com/Shows/Going+Deep/Brian-Beckman-Dont-fear-the-Monads\n\nA rather detailed discussion explaining the fundamentals of monads.\n",
"I will work on that issue tomorrow \n",
"Ok @Crossy147 I will update the issue tags.\n"
] | [] | "2016-02-19T18:14:15Z" | [
"epic: pattern"
] | Monad pattern | It is described in this talk: https://youtu.be/-k2X7guaArU
| [
"pom.xml"
] | [
"monad/etc/monad.ucls",
"monad/index.md",
"monad/pom.xml",
"monad/src/main/java/com/iluwatar/monad/App.java",
"monad/src/main/java/com/iluwatar/monad/Sex.java",
"monad/src/main/java/com/iluwatar/monad/User.java",
"monad/src/main/java/com/iluwatar/monad/Validator.java",
"pom.xml"
] | [
"monad/src/test/java/com/iluwatar/monad/AppTest.java",
"monad/src/test/java/com/iluwatar/monad/MonadTest.java"
] | diff --git a/monad/etc/monad.ucls b/monad/etc/monad.ucls
new file mode 100644
index 000000000000..9c98df7c6331
--- /dev/null
+++ b/monad/etc/monad.ucls
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<class-diagram version="1.1.9" icons="true" always-add-relationships="false" generalizations="true" realizations="true"
+ associations="true" dependencies="false" nesting-relationships="true" router="FAN">
+ <class id="1" language="java" name="com.iluwatar.monad.App" project="monad"
+ file="/monad/src/main/java/com/iluwatar/monad/App.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="101" width="125" x="631" y="37"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <enumeration id="2" language="java" name="com.iluwatar.monad.Sex" project="monad"
+ file="/monad/src/main/java/com/iluwatar/monad/Sex.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="119" width="137" x="424" y="286"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </enumeration>
+ <class id="3" language="java" name="com.iluwatar.monad.User" project="monad"
+ file="/monad/src/main/java/com/iluwatar/monad/User.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="209" width="167" x="424" y="37"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <class id="4" language="java" name="com.iluwatar.monad.Validator" project="monad"
+ file="/monad/src/main/java/com/iluwatar/monad/Validator.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="191" width="343" x="41" y="37"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <association id="5">
+ <end type="SOURCE" refId="3" navigable="false">
+ <attribute id="6" name="sex"/>
+ <multiplicity id="7" minimum="0" maximum="1"/>
+ </end>
+ <end type="TARGET" refId="2" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </classifier-display>
+ <association-display labels="true" multiplicity="true"/>
+</class-diagram>
\ No newline at end of file
diff --git a/monad/index.md b/monad/index.md
new file mode 100644
index 000000000000..82deba9222a6
--- /dev/null
+++ b/monad/index.md
@@ -0,0 +1,35 @@
+---
+layout: pattern
+title: Monad
+folder: monad
+permalink: /patterns/monad/
+categories: Other
+tags:
+ - Java
+ - Difficulty-Advanced
+ - Functional
+---
+
+## Intent
+
+Monad pattern based on monad from linear algebra represents the way of chaining operations
+together step by step. Binding functions can be described as passing one's output to another's input
+basing on the 'same type' contract. Formally, monad consists of a type constructor M and two
+operations:
+bind - that takes monadic object and a function from plain object to monadic value and returns monadic value
+return - that takes plain type object and returns this object wrapped in a monadic value.
+
+![alt text](./etc/monad.png "Monad")
+
+## Applicability
+
+Use the Monad in any of the following situations
+
+* when you want to chain operations easily
+* when you want to apply each function regardless of the result of any of them
+
+## Credits
+
+* [Design Pattern Reloaded by Remi Forax](https://youtu.be/-k2X7guaArU)
+* [Brian Beckman: Don't fear the Monad](https://channel9.msdn.com/Shows/Going+Deep/Brian-Beckman-Dont-fear-the-Monads)
+* [Monad on Wikipedia](https://en.wikipedia.org/wiki/Monad_(functional_programming))
\ No newline at end of file
diff --git a/monad/pom.xml b/monad/pom.xml
new file mode 100644
index 000000000000..ec5a14a8c19c
--- /dev/null
+++ b/monad/pom.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0"?>
+<!--
+
+ The MIT License
+ Copyright (c) 2014 Ilkka Seppälä
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+
+-->
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>java-design-patterns</artifactId>
+ <version>1.11.0-SNAPSHOT</version>
+ </parent>
+ <artifactId>monad</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
+
diff --git a/monad/src/main/java/com/iluwatar/monad/App.java b/monad/src/main/java/com/iluwatar/monad/App.java
new file mode 100644
index 000000000000..e330cfa64bfc
--- /dev/null
+++ b/monad/src/main/java/com/iluwatar/monad/App.java
@@ -0,0 +1,35 @@
+package com.iluwatar.monad;
+
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.function.Predicate;
+
+/**
+ * The Monad pattern defines a monad structure, that enables chaining operations
+ * in pipelines and processing data step by step.
+ * Formally, monad consists of a type constructor M and two operations:
+ * <br>bind - that takes monadic object and a function from plain object to the
+ * monadic value and returns monadic value.
+ * <br>return - that takes plain type object and returns this object wrapped in a monadic value.
+ * <p>
+ * In the given example, the Monad pattern is represented as a {@link Validator} that takes an instance
+ * of a plain object with {@link Validator#of(Object)}
+ * and validates it {@link Validator#validate(Function, Predicate, String)} against given predicates.
+ * <p>As a validation result {@link Validator#get()} it either returns valid object {@link Validator#t}
+ * or throws a list of exceptions {@link Validator#exceptions} collected during validation.
+ */
+public class App {
+
+ /**
+ * Program entry point.
+ *
+ * @param args @param args command line args
+ */
+ public static void main(String[] args) {
+ User user = new User("user", 24, Sex.FEMALE, "foobar.com");
+ System.out.println(Validator.of(user).validate(User::getName, Objects::nonNull, "name is null")
+ .validate(User::getName, name -> !name.isEmpty(), "name is empty")
+ .validate(User::getEmail, email -> !email.contains("@"), "email doesn't containt '@'")
+ .validate(User::getAge, age -> age > 20 && age < 30, "age isn't between...").get().toString());
+ }
+}
diff --git a/monad/src/main/java/com/iluwatar/monad/Sex.java b/monad/src/main/java/com/iluwatar/monad/Sex.java
new file mode 100644
index 000000000000..8b7e43f3ccf3
--- /dev/null
+++ b/monad/src/main/java/com/iluwatar/monad/Sex.java
@@ -0,0 +1,5 @@
+package com.iluwatar.monad;
+
+public enum Sex {
+ MALE, FEMALE
+}
diff --git a/monad/src/main/java/com/iluwatar/monad/User.java b/monad/src/main/java/com/iluwatar/monad/User.java
new file mode 100644
index 000000000000..edd29964327a
--- /dev/null
+++ b/monad/src/main/java/com/iluwatar/monad/User.java
@@ -0,0 +1,38 @@
+package com.iluwatar.monad;
+
+public class User {
+
+ private String name;
+ private int age;
+ private Sex sex;
+ private String email;
+
+ /**
+ * @param name - name
+ * @param age - age
+ * @param sex - sex
+ * @param email - email address
+ */
+ public User(String name, int age, Sex sex, String email) {
+ this.name = name;
+ this.age = age;
+ this.sex = sex;
+ this.email = email;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getAge() {
+ return age;
+ }
+
+ public Sex getSex() {
+ return sex;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+}
diff --git a/monad/src/main/java/com/iluwatar/monad/Validator.java b/monad/src/main/java/com/iluwatar/monad/Validator.java
new file mode 100644
index 000000000000..2298a4d8e324
--- /dev/null
+++ b/monad/src/main/java/com/iluwatar/monad/Validator.java
@@ -0,0 +1,91 @@
+package com.iluwatar.monad;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.function.Predicate;
+
+/**
+ * Class representing Monad design pattern. Monad is a way of chaining operations on the
+ * given object together step by step. In Validator each step results in either success or
+ * failure indicator, giving a way of receiving each of them easily and finally getting
+ * validated object or list of exceptions.
+ *
+ * @param <T> Placeholder for an object.
+ */
+public class Validator<T> {
+ /**
+ * Object that is validated
+ */
+ private final T t;
+
+ /**
+ * List of exception thrown during validation.
+ */
+ private final List<Throwable> exceptions = new ArrayList<>();
+
+ /**
+ * Creates a monadic value of given object.
+ * @param t object to be validated
+ */
+ private Validator(T t) {
+ this.t = t;
+ }
+
+ /**
+ * Creates validator against given object
+ *
+ * @param t object to be validated
+ * @param <T> object's type
+ * @return new instance of a validator
+ */
+ public static <T> Validator<T> of(T t) {
+ return new Validator<>(Objects.requireNonNull(t));
+ }
+
+ /**
+ * @param validation one argument boolean-valued function that
+ * represents one step of validation. Adds exception to main validation exception
+ * list when single step validation ends with failure.
+ * @param message error message when object is invalid
+ * @return this
+ */
+ public Validator<T> validate(Predicate<T> validation, String message) {
+ if (!validation.test(t)) {
+ exceptions.add(new IllegalStateException(message));
+ }
+ return this;
+ }
+
+ /**
+ * Extension for the {@link Validator#validate(Function, Predicate, String)} method,
+ * dedicated for objects, that need to be projected before requested validation.
+ *
+ * @param projection function that gets an objects, and returns projection representing
+ * element to be validated.
+ * @param validation see {@link Validator#validate(Function, Predicate, String)}
+ * @param message see {@link Validator#validate(Function, Predicate, String)}
+ * @param <U> see {@link Validator#validate(Function, Predicate, String)}
+ * @return this
+ */
+ public <U> Validator<T> validate(Function<T, U> projection, Predicate<U> validation,
+ String message) {
+ return validate(projection.andThen(validation::test)::apply, message);
+ }
+
+ /**
+ * Receives validated object or throws exception when invalid.
+ *
+ * @return object that was validated
+ * @throws IllegalStateException when any validation step results with failure
+ */
+ public T get() throws IllegalStateException {
+ if (exceptions.isEmpty()) {
+ return t;
+ }
+ IllegalStateException e = new IllegalStateException();
+ exceptions.forEach(e::addSuppressed);
+ throw e;
+ }
+}
diff --git a/pom.xml b/pom.xml
index c15ca20cfb1c..0b587fd06133 100644
--- a/pom.xml
+++ b/pom.xml
@@ -121,6 +121,7 @@
<module>event-driven-architecture</module>
<module>feature-toggle</module>
<module>value-object</module>
+ <module>monad</module>
</modules>
<dependencyManagement>
| diff --git a/monad/src/test/java/com/iluwatar/monad/AppTest.java b/monad/src/test/java/com/iluwatar/monad/AppTest.java
new file mode 100644
index 000000000000..5d23b41a6759
--- /dev/null
+++ b/monad/src/test/java/com/iluwatar/monad/AppTest.java
@@ -0,0 +1,13 @@
+package com.iluwatar.monad;
+
+import org.junit.Test;
+
+public class AppTest {
+
+ @Test
+ public void testMain() {
+ String[] args = {};
+ App.main(args);
+ }
+
+}
diff --git a/monad/src/test/java/com/iluwatar/monad/MonadTest.java b/monad/src/test/java/com/iluwatar/monad/MonadTest.java
new file mode 100644
index 000000000000..ae78572f87f7
--- /dev/null
+++ b/monad/src/test/java/com/iluwatar/monad/MonadTest.java
@@ -0,0 +1,42 @@
+package com.iluwatar.monad;
+
+
+import junit.framework.Assert;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+
+import java.util.Objects;
+
+public class MonadTest {
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void testForInvalidName() {
+ thrown.expect(IllegalStateException.class);
+ User tom = new User(null, 21, Sex.MALE, "tom@foo.bar");
+ Validator.of(tom).validate(User::getName, Objects::nonNull, "name cannot be null").get();
+ }
+
+ @Test
+ public void testForInvalidAge() {
+ thrown.expect(IllegalStateException.class);
+ User john = new User("John", 17, Sex.MALE, "john@qwe.bar");
+ Validator.of(john).validate(User::getName, Objects::nonNull, "name cannot be null")
+ .validate(User::getAge, age -> age > 21, "user is underaged")
+ .get();
+ }
+
+ @Test
+ public void testForValid() {
+ User sarah = new User("Sarah", 42, Sex.FEMALE, "sarah@det.org");
+ User validated = Validator.of(sarah).validate(User::getName, Objects::nonNull, "name cannot be null")
+ .validate(User::getAge, age -> age > 21, "user is underaged")
+ .validate(User::getSex, sex -> sex == Sex.FEMALE, "user is not female")
+ .validate(User::getEmail, email -> email.contains("@"), "email does not contain @ sign")
+ .get();
+ Assert.assertSame(validated, sarah);
+ }
+}
| train | train | "2016-02-18T08:09:06" | "2015-12-31T09:51:48Z" | iluwatar | train |
iluwatar/java-design-patterns/385_402 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/385 | iluwatar/java-design-patterns/402 | [
"timestamp(timedelta=165318.0, similarity=0.9157572033852361)"
] | 2f5a2be27a9541b894b94049e02010f6dabd5b76 | 100a72a5e2d2675b6f9c4624219658a73af2a3f7 | [
"Have used this idiom numerous times. On it.\n\nI will be creating two mute methods:\n- `mute()` throws `AssertionError` if unexpected exception occurs. Should be used when some class declares exception but should never throw exception.\n- `loggedMute()` swallows exception by logging it on err stream. Should be used when all you can do about exception is trace it.\n"
] | [
"Check indentation\n"
] | "2016-03-16T07:22:39Z" | [
"epic: pattern"
] | Mute idiom | http://blog.jooq.org/2016/02/18/the-mute-design-pattern/
| [
"pom.xml"
] | [
"mute-idiom/README.md",
"mute-idiom/etc/mute-idiom.ucls",
"mute-idiom/pom.xml",
"mute-idiom/src/main/java/com/iluwatar/mute/App.java",
"mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java",
"mute-idiom/src/main/java/com/iluwatar/mute/Mute.java",
"mute-idiom/src/main/java/com/iluwatar/mute/Resource.java",
"pom.xml"
] | [
"mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java",
"mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java"
] | diff --git a/mute-idiom/README.md b/mute-idiom/README.md
new file mode 100644
index 000000000000..efc09f3069d0
--- /dev/null
+++ b/mute-idiom/README.md
@@ -0,0 +1,28 @@
+---
+layout: pattern
+title: Mute Idiom
+folder: mute-idiom
+permalink: /patterns/mute-idiom/
+categories: Other
+tags:
+ - Java
+ - Difficulty-Beginner
+ - Idiom
+---
+
+## Intent
+Provide a template to supress any exceptions that either are declared but cannot occur or should only be logged;
+while executing some business logic. The template removes the need to write repeated `try-catch` blocks.
+
+
+![alt text](./etc/mute-idiom.png "Mute Idiom")
+
+## Applicability
+Use this idiom when
+
+* an API declares some exception but can never throw that exception. Eg. ByteArrayOutputStream bulk write method.
+* you need to suppress some exception just by logging it, such as closing a resource.
+
+## Credits
+
+* [JOOQ: Mute Design Pattern](http://blog.jooq.org/2016/02/18/the-mute-design-pattern/)
diff --git a/mute-idiom/etc/mute-idiom.ucls b/mute-idiom/etc/mute-idiom.ucls
new file mode 100644
index 000000000000..7b4d2f9165e1
--- /dev/null
+++ b/mute-idiom/etc/mute-idiom.ucls
@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
+ realizations="true" associations="true" dependencies="true" nesting-relationships="true">
+ <class id="1" language="java" name="com.iluwatar.mute.App" project="mute-idiom"
+ file="/mute-idiom/src/main/java/com/iluwatar/mute/App.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="168" y="234"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="false" static="true"/>
+ <operations public="true" package="true" protected="true" private="false" static="true"/>
+ </display>
+ </class>
+ <class id="2" language="java" name="com.iluwatar.mute.Mute" project="mute-idiom"
+ file="/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="115" width="203" x="70" y="375"/>
+ <display autosize="false" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="false" static="true"/>
+ </display>
+ </class>
+ <interface id="3" language="java" name="com.iluwatar.mute.CheckedRunnable" project="mute-idiom"
+ file="/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="407" y="432"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </interface>
+ <interface id="4" language="java" name="com.iluwatar.mute.Resource" project="mute-idiom"
+ file="/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="383" y="235"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </interface>
+ <interface id="5" language="java" name="java.io.Closeable" project="dao"
+ file="/opt/Softwares/Eclipses/MARS/eclipse/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="384" y="109"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </interface>
+ <dependency id="6">
+ <end type="SOURCE" refId="1"/>
+ <end type="TARGET" refId="4"/>
+ </dependency>
+ <dependency id="7">
+ <end type="SOURCE" refId="1"/>
+ <end type="TARGET" refId="2"/>
+ </dependency>
+ <dependency id="8">
+ <end type="SOURCE" refId="2"/>
+ <end type="TARGET" refId="3"/>
+ </dependency>
+ <generalization id="9">
+ <end type="SOURCE" refId="4"/>
+ <end type="TARGET" refId="5"/>
+ </generalization>
+ <classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </classifier-display>
+ <association-display labels="true" multiplicity="true"/>
+</class-diagram>
\ No newline at end of file
diff --git a/mute-idiom/pom.xml b/mute-idiom/pom.xml
new file mode 100644
index 000000000000..bad6cb8c75d1
--- /dev/null
+++ b/mute-idiom/pom.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0"?>
+<!-- The MIT License Copyright (c) 2014 Ilkka Seppälä Permission is hereby
+ granted, free of charge, to any person obtaining a copy of this software
+ and associated documentation files (the "Software"), to deal in the Software
+ without restriction, including without limitation the rights to use, copy,
+ modify, merge, publish, distribute, sublicense, and/or sell copies of the
+ Software, and to permit persons to whom the Software is furnished to do so,
+ subject to the following conditions: The above copyright notice and this
+ permission notice shall be included in all copies or substantial portions
+ of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE. -->
+<project
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
+ xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>java-design-patterns</artifactId>
+ <version>1.11.0-SNAPSHOT</version>
+ </parent>
+ <artifactId>mute-idiom</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/App.java b/mute-idiom/src/main/java/com/iluwatar/mute/App.java
new file mode 100644
index 000000000000..8a2aca41efd0
--- /dev/null
+++ b/mute-idiom/src/main/java/com/iluwatar/mute/App.java
@@ -0,0 +1,103 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.mute;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.sql.SQLException;
+
+/**
+ * Mute pattern is utilized when we need to suppress an exception due to an API flaw or in
+ * situation when all we can do to handle the exception is to log it.
+ * This pattern should not be used everywhere. It is very important to logically handle the
+ * exceptions in a system, but some situations like the ones described above require this pattern,
+ * so that we don't need to repeat
+ * <pre>
+ * <code>
+ * try {
+ * // code that may throwing exception we need to ignore or may never be thrown
+ * } catch (Exception ex) {
+ * // ignore by logging or throw error if unexpected exception occurs
+ * }
+ * </code>
+ * </pre> every time we need to ignore an exception.
+ *
+ */
+public class App {
+
+ /**
+ * Program entry point.
+ *
+ * @param args command line args.
+ * @throws Exception if any exception occurs
+ */
+ public static void main(String[] args) throws Exception {
+
+ useOfLoggedMute();
+
+ useOfMute();
+ }
+
+ /*
+ * Typically used when the API declares some exception but cannot do so. Usually a
+ * signature mistake.In this example out is not supposed to throw exception as it is a
+ * ByteArrayOutputStream. So we utilize mute, which will throw AssertionError if unexpected
+ * exception occurs.
+ */
+ private static void useOfMute() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ Mute.mute(() -> out.write("Hello".getBytes()));
+ }
+
+ private static void useOfLoggedMute() throws SQLException {
+ Resource resource = null;
+ try {
+ resource = acquireResource();
+ utilizeResource(resource);
+ } finally {
+ closeResource(resource);
+ }
+ }
+
+ /*
+ * All we can do while failed close of a resource is to log it.
+ */
+ private static void closeResource(Resource resource) {
+ Mute.loggedMute(() -> resource.close());
+ }
+
+ private static void utilizeResource(Resource resource) throws SQLException {
+ System.out.println("Utilizing acquired resource: " + resource);
+ }
+
+ private static Resource acquireResource() throws SQLException {
+ return new Resource() {
+
+ @Override
+ public void close() throws IOException {
+ throw new IOException("Error in closing resource: " + this);
+ }
+ };
+ }
+}
diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java b/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java
new file mode 100644
index 000000000000..d1440636f208
--- /dev/null
+++ b/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java
@@ -0,0 +1,37 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.mute;
+
+/**
+ * A runnable which may throw exception on execution.
+ *
+ */
+@FunctionalInterface
+public interface CheckedRunnable {
+ /**
+ * Same as {@link Runnable#run()} with a possibility of exception in execution.
+ * @throws Exception if any exception occurs.
+ */
+ void run() throws Exception;
+}
diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java b/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java
new file mode 100644
index 000000000000..64169a8f508f
--- /dev/null
+++ b/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java
@@ -0,0 +1,68 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.mute;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+/**
+ * A utility class that allows you to utilize mute idiom.
+ */
+public final class Mute {
+
+ // The constructor is never meant to be called.
+ private Mute() {}
+
+ /**
+ * Executes the <code>runnable</code> and throws the exception occurred within a {@link AssertionError}.
+ * This method should be utilized to mute the operations that are guaranteed not to throw an exception.
+ * For instance {@link ByteArrayOutputStream#write(byte[])} declares in it's signature that it can throw
+ * an {@link IOException}, but in reality it cannot. This is because the bulk write method is not overridden
+ * in {@link ByteArrayOutputStream}.
+ *
+ * @param runnable a runnable that should never throw an exception on execution.
+ */
+ public static void mute(CheckedRunnable runnable) {
+ try {
+ runnable.run();
+ } catch (Exception e) {
+ throw new AssertionError(e);
+ }
+ }
+
+ /**
+ * Executes the <code>runnable</code> and logs the exception occurred on {@link System#err}.
+ * This method should be utilized to mute the operations about which most you can do is log.
+ * For instance while closing a connection to database, or cleaning up a resource,
+ * all you can do is log the exception occurred.
+ *
+ * @param runnable a runnable that may throw an exception on execution.
+ */
+ public static void loggedMute(CheckedRunnable runnable) {
+ try {
+ runnable.run();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+}
diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java b/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java
new file mode 100644
index 000000000000..6970d06bce77
--- /dev/null
+++ b/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java
@@ -0,0 +1,35 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.mute;
+
+import java.io.Closeable;
+
+/**
+ * Represents any resource that the application might acquire and that must be closed
+ * after it is utilized. Example of such resources can be a database connection, open
+ * files, sockets.
+ */
+public interface Resource extends Closeable {
+
+}
diff --git a/pom.xml b/pom.xml
index 5558446601c8..57d030756bc4 100644
--- a/pom.xml
+++ b/pom.xml
@@ -123,6 +123,7 @@
<module>feature-toggle</module>
<module>value-object</module>
<module>monad</module>
+ <module>mute-idiom</module>
</modules>
<dependencyManagement>
| diff --git a/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java b/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java
new file mode 100644
index 000000000000..8075d9c855fa
--- /dev/null
+++ b/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java
@@ -0,0 +1,38 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.mute;
+
+import org.junit.Test;
+
+/**
+ * Tests that Mute idiom example runs without errors.
+ *
+ */
+public class AppTest {
+
+ @Test
+ public void test() throws Exception {
+ App.main(null);
+ }
+}
diff --git a/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java b/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java
new file mode 100644
index 000000000000..58cbfe8938b0
--- /dev/null
+++ b/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java
@@ -0,0 +1,78 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.mute;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+
+public class MuteTest {
+
+ private static final String MESSAGE = "should not occur";
+
+ @Rule public ExpectedException exception = ExpectedException.none();
+
+ @Test
+ public void muteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() {
+ Mute.mute(() -> methodNotThrowingAnyException());
+ }
+
+ @Test
+ public void muteShouldRethrowUnexpectedExceptionAsAssertionError() throws Exception {
+ exception.expect(AssertionError.class);
+ exception.expectMessage(MESSAGE);
+
+ Mute.mute(() -> methodThrowingException());
+ }
+
+ @Test
+ public void loggedMuteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() {
+ Mute.loggedMute(() -> methodNotThrowingAnyException());
+ }
+
+ @Test
+ public void loggedMuteShouldLogExceptionTraceBeforeSwallowingIt() throws IOException {
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ System.setErr(new PrintStream(stream));
+
+ Mute.loggedMute(() -> methodThrowingException());
+
+ assertTrue(new String(stream.toByteArray()).contains(MESSAGE));
+ }
+
+
+ private void methodNotThrowingAnyException() {
+ System.out.println("Executed successfully");
+ }
+
+ private void methodThrowingException() throws Exception {
+ throw new Exception(MESSAGE);
+ }
+}
| test | train | "2016-03-25T21:00:08" | "2016-02-18T16:33:13Z" | iluwatar | train |
iluwatar/java-design-patterns/463_464 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/463 | iluwatar/java-design-patterns/464 | [
"timestamp(timedelta=122.0, similarity=0.862426888756227)"
] | 9f0320aeaf31e9376da44b53e3e6ecdad7cbbfde | d4c2f0392d2588c1de95659b90bd356d7a057a2e | [
"Thanks @pnowy Please create a pull request and we'll review it.\n",
"Pull request has been created!\n"
] | [] | "2016-07-17T14:08:35Z" | [
"type: enhancement",
"epic: web site"
] | Chain of responsiblity pattern - javax.servlet.Filter as real example is missed | I think that on the chain of responsibility pattern on the section real word examples the most important java real word example is missed.
I suggest to add there **javax.servlet.Filter** as the best patter for the people who meet this patter the first time.
I could create the pull request if it is needed.
| [
"intercepting-filter/README.md"
] | [
"intercepting-filter/README.md"
] | [] | diff --git a/intercepting-filter/README.md b/intercepting-filter/README.md
index 327f091b1e93..7d53472a077f 100644
--- a/intercepting-filter/README.md
+++ b/intercepting-filter/README.md
@@ -24,6 +24,7 @@ Use the Intercepting Filter pattern when
## Real world examples
+* [javax.servlet.FilterChain](https://tomcat.apache.org/tomcat-8.0-doc/servletapi/javax/servlet/FilterChain.html) and [javax.servlet.Filter](https://tomcat.apache.org/tomcat-8.0-doc/servletapi/javax/servlet/Filter.html)
* [Struts 2 - Interceptors](https://struts.apache.org/docs/interceptors.html)
## Credits
| null | train | train | "2016-07-12T23:02:20" | "2016-07-17T09:55:03Z" | pnowy | train |
iluwatar/java-design-patterns/440_495 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/440 | iluwatar/java-design-patterns/495 | [
"timestamp(timedelta=324.0, similarity=0.8920156408089317)"
] | 6026eedd51b9753250051b620312bbedd2ccd6ef | 64bdab46b9771d1d8aa7497b6e30cd3843ba011e | [
"Thanks for an excellent project, I thought I should contribute something back and this one seemed like a low-hanging fruit.\n\nWould it make sense to simply add two helper methods in AppManager, e.g. `saveAside` and `findAside`\n\n``` java\nprivate static void saveAside(UserAccount userAccount) {\n DbManager.updateDb(userAccount);\n CacheStore.invalidate(userAccount.getUserId());\n}\n```\n\nand then either delegate `CacheStore.(get,set,invalidate)` to `cache`\n\n``` java\npublic static void invalidate(String userId) {\n cache.invalidate(userId);\n}\n```\n\nor simply expose `cache` with a `CacheStore.getCache()` getter?\n\nAnd then add a new case:\n\n``` java\npublic static void save(UserAccount userAccount) {\n if (cachingPolicy == CachingPolicy.THROUGH) {\n CacheStore.writeThrough(userAccount);\n } else if (cachingPolicy == CachingPolicy.AROUND) {\n CacheStore.writeAround(userAccount);\n } else if (cachingPolicy == CachingPolicy.BEHIND) {\n CacheStore.writeBehind(userAccount);\n } else if (cachingPolicy == CachingPolicy.ASIDE) {\n saveAside(userAccount);\n}\n```\n\nWould that make sense, @iluwatar? \n",
"@christofferh the plan looks reasonable. Just create a pull request and we'll review.\n"
] | [
"Is there any reason for not using logging framework like SLF4J or LOG4J Or Common logging?\n",
"@chinnachalam you are right, using a logging framework would give some advantages such as ability to redirect output and filter output based on logging levels. But I think we should handle this issue on a more general level since there are multiple patterns not using a logging framework at the moment. Would you raise an issue about this matter, please?\n"
] | "2016-09-22T18:54:46Z" | [
"epic: pattern"
] | Cache Aside pattern | https://msdn.microsoft.com/en-us/library/dn589799.aspx
This pattern could be incorporated into https://github.com/iluwatar/java-design-patterns/tree/master/caching example.
| [
"caching/README.md",
"caching/etc/caching.ucls",
"caching/src/main/java/com/iluwatar/caching/App.java",
"caching/src/main/java/com/iluwatar/caching/AppManager.java",
"caching/src/main/java/com/iluwatar/caching/CacheStore.java",
"caching/src/main/java/com/iluwatar/caching/CachingPolicy.java",
"caching/src/main/java/com/iluwatar/caching/DbManager.java",
"caching/src/main/java/com/iluwatar/caching/LruCache.java",
"caching/src/main/java/com/iluwatar/caching/UserAccount.java"
] | [
"caching/README.md",
"caching/etc/caching.ucls",
"caching/src/main/java/com/iluwatar/caching/App.java",
"caching/src/main/java/com/iluwatar/caching/AppManager.java",
"caching/src/main/java/com/iluwatar/caching/CacheStore.java",
"caching/src/main/java/com/iluwatar/caching/CachingPolicy.java",
"caching/src/main/java/com/iluwatar/caching/DbManager.java",
"caching/src/main/java/com/iluwatar/caching/LruCache.java",
"caching/src/main/java/com/iluwatar/caching/UserAccount.java"
] | [
"caching/src/test/java/com/iluwatar/caching/CachingTest.java"
] | diff --git a/caching/README.md b/caching/README.md
index 6432ffcea26e..b48d060f0012 100644
--- a/caching/README.md
+++ b/caching/README.md
@@ -27,3 +27,4 @@ Use the Caching pattern(s) when
* [Write-through, write-around, write-back: Cache explained](http://www.computerweekly.com/feature/Write-through-write-around-write-back-Cache-explained)
* [Read-Through, Write-Through, Write-Behind, and Refresh-Ahead Caching](https://docs.oracle.com/cd/E15357_01/coh.360/e15723/cache_rtwtwbra.htm#COHDG5177)
+* [Cache-Aside](https://msdn.microsoft.com/en-us/library/dn589799.aspx)
diff --git a/caching/etc/caching.ucls b/caching/etc/caching.ucls
index 815a62ec99ce..a058277ea2fd 100644
--- a/caching/etc/caching.ucls
+++ b/caching/etc/caching.ucls
@@ -1,106 +1,90 @@
<?xml version="1.0" encoding="UTF-8"?>
-<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
- realizations="true" associations="true" dependencies="false" nesting-relationships="true">
- <class id="1" language="java" name="main.java.com.wssia.caching.App" project="CachingPatterns"
- file="/CachingPatterns/src/main/java/com/wssia/caching/App.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="249" y="150"/>
- <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
- sort-features="false" accessors="true" visibility="true">
- <attributes public="true" package="true" protected="true" private="true" static="true"/>
- <operations public="true" package="true" protected="true" private="true" static="true"/>
- </display>
+<class-diagram version="1.1.11" icons="true" automaticImage="PNG" always-add-relationships="false"
+ generalizations="true" realizations="true" associations="true" dependencies="false" nesting-relationships="true"
+ router="FAN">
+ <class id="1" language="java" name="com.iluwatar.caching.CacheStore" project="caching"
+ file="/caching/src/main/java/com/iluwatar/caching/CacheStore.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="322" y="444"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <class id="2" language="java" name="com.iluwatar.caching.LruCache" project="caching"
+ file="/caching/src/main/java/com/iluwatar/caching/LruCache.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="700" y="446"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <enumeration id="3" language="java" name="com.iluwatar.caching.CachingPolicy" project="caching"
+ file="/caching/src/main/java/com/iluwatar/caching/CachingPolicy.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="943" y="122"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </enumeration>
+ <class id="4" language="java" name="com.iluwatar.caching.DbManager" project="caching"
+ file="/caching/src/main/java/com/iluwatar/caching/DbManager.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="1011" y="426"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <class id="5" language="java" name="com.iluwatar.caching.App" project="caching"
+ file="/caching/src/main/java/com/iluwatar/caching/App.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="304" y="95"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <class id="6" language="java" name="com.iluwatar.caching.AppManager" project="caching"
+ file="/caching/src/main/java/com/iluwatar/caching/AppManager.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="604" y="122"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <class id="7" language="java" name="com.iluwatar.caching.UserAccount" project="caching"
+ file="/caching/src/main/java/com/iluwatar/caching/UserAccount.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="1161" y="139"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
</class>
- <class id="2" language="java" name="main.java.com.wssia.caching.AppManager" project="CachingPatterns"
- file="/CachingPatterns/src/main/java/com/wssia/caching/AppManager.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="502" y="163"/>
- <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
- sort-features="false" accessors="true" visibility="true">
- <attributes public="true" package="true" protected="true" private="true" static="true"/>
- <operations public="true" package="true" protected="true" private="true" static="true"/>
- </display>
- </class>
- <class id="3" language="java" name="main.java.com.wssia.caching.CacheStore" project="CachingPatterns"
- file="/CachingPatterns/src/main/java/com/wssia/caching/CacheStore.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="537" y="436"/>
- <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
- sort-features="false" accessors="true" visibility="true">
- <attributes public="true" package="true" protected="true" private="true" static="true"/>
- <operations public="true" package="true" protected="true" private="true" static="true"/>
- </display>
- </class>
- <enumeration id="4" language="java" name="main.java.com.wssia.caching.CachingPolicy" project="CachingPatterns"
- file="/CachingPatterns/src/main/java/com/wssia/caching/CachingPolicy.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="789" y="162"/>
- <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
- sort-features="false" accessors="true" visibility="true">
- <attributes public="true" package="true" protected="true" private="true" static="true"/>
- <operations public="true" package="true" protected="true" private="true" static="true"/>
- </display>
- </enumeration>
- <class id="5" language="java" name="main.java.com.wssia.caching.DBManager" project="CachingPatterns"
- file="/CachingPatterns/src/main/java/com/wssia/caching/DBManager.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="1137" y="134"/>
- <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
- sort-features="false" accessors="true" visibility="true">
- <attributes public="true" package="true" protected="true" private="true" static="true"/>
- <operations public="true" package="true" protected="true" private="true" static="true"/>
- </display>
- </class>
- <class id="6" language="java" name="main.java.com.wssia.caching.LRUCache" project="CachingPatterns"
- file="/CachingPatterns/src/main/java/com/wssia/caching/LRUCache.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="884" y="435"/>
- <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
- sort-features="false" accessors="true" visibility="true">
- <attributes public="true" package="true" protected="true" private="true" static="true"/>
- <operations public="true" package="true" protected="true" private="true" static="true"/>
- </display>
- </class>
- <class id="7" language="java" name="main.java.com.wssia.caching.UserAccount" project="CachingPatterns"
- file="/CachingPatterns/src/main/java/com/wssia/caching/UserAccount.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="1140" y="405"/>
- <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
- sort-features="false" accessors="true" visibility="true">
- <attributes public="true" package="true" protected="true" private="true" static="true"/>
- <operations public="true" package="true" protected="true" private="true" static="true"/>
- </display>
- </class>
- <class id="8" language="java" name="test.java.com.wssia.caching.AppTest" project="CachingPatterns"
- file="/CachingPatterns/src/test/java/com/wssia/caching/AppTest.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="251" y="374"/>
- <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
- sort-features="false" accessors="true" visibility="true">
- <attributes public="true" package="true" protected="true" private="true" static="true"/>
- <operations public="true" package="true" protected="true" private="true" static="true"/>
- </display>
- </class>
- <association id="9">
- <end type="SOURCE" refId="2" navigable="false">
- <attribute id="10" name="cachingPolicy"/>
- <multiplicity id="11" minimum="0" maximum="1"/>
- </end>
- <end type="TARGET" refId="4" navigable="true"/>
- <display labels="true" multiplicity="true"/>
- </association>
- <association id="12">
- <end type="SOURCE" refId="8" navigable="false">
- <attribute id="13" name="app"/>
- <multiplicity id="14" minimum="0" maximum="1"/>
- </end>
- <end type="TARGET" refId="1" navigable="true"/>
- <display labels="true" multiplicity="true"/>
- </association>
- <association id="15">
- <end type="SOURCE" refId="3" navigable="false">
- <attribute id="16" name="cache"/>
- <multiplicity id="17" minimum="0" maximum="1"/>
- </end>
- <end type="TARGET" refId="6" navigable="true"/>
- <display labels="true" multiplicity="true"/>
- </association>
- <classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
- sort-features="false" accessors="true" visibility="true">
- <attributes public="true" package="true" protected="true" private="true" static="true"/>
- <operations public="true" package="true" protected="true" private="true" static="true"/>
- </classifier-display>
+ <association id="8">
+ <end type="SOURCE" refId="1" navigable="false">
+ <attribute id="9" name="cache"/>
+ <multiplicity id="10" minimum="0" maximum="1"/>
+ </end>
+ <end type="TARGET" refId="2" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <association id="11">
+ <end type="SOURCE" refId="6" navigable="false">
+ <attribute id="12" name="cachingPolicy"/>
+ <multiplicity id="13" minimum="0" maximum="1"/>
+ </end>
+ <end type="TARGET" refId="3" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </classifier-display>
<association-display labels="true" multiplicity="true"/>
-</class-diagram>
\ No newline at end of file
+</class-diagram>
diff --git a/caching/src/main/java/com/iluwatar/caching/App.java b/caching/src/main/java/com/iluwatar/caching/App.java
index 8e5a84085ff9..1b1b5e1cac91 100644
--- a/caching/src/main/java/com/iluwatar/caching/App.java
+++ b/caching/src/main/java/com/iluwatar/caching/App.java
@@ -26,22 +26,23 @@
*
* The Caching pattern describes how to avoid expensive re-acquisition of resources by not releasing
* the resources immediately after their use. The resources retain their identity, are kept in some
- * fast-access storage, and are re-used to avoid having to acquire them again. There are three main
- * caching strategies/techniques in this pattern; each with their own pros and cons. They are:
+ * fast-access storage, and are re-used to avoid having to acquire them again. There are four main
+ * caching strategies/techniques in this pattern; each with their own pros and cons. They are;
* <code>write-through</code> which writes data to the cache and DB in a single transaction,
- * <code>write-around</code> which writes data immediately into the DB instead of the cache, and
+ * <code>write-around</code> which writes data immediately into the DB instead of the cache,
* <code>write-behind</code> which writes data into the cache initially whilst the data is only
- * written into the DB when the cache is full. The <code>read-through</code> strategy is also
- * included in the mentioned three strategies -- returns data from the cache to the caller <b>if</b>
- * it exists <b>else</b> queries from DB and stores it into the cache for future use. These
- * strategies determine when the data in the cache should be written back to the backing store (i.e.
- * Database) and help keep both data sources synchronized/up-to-date. This pattern can improve
- * performance and also helps to maintain consistency between data held in the cache and the data in
- * the underlying data store.
+ * written into the DB when the cache is full, and <code>cache-aside</code> which pushes the
+ * responsibility of keeping the data synchronized in both data sources to the application itself.
+ * The <code>read-through</code> strategy is also included in the mentioned four strategies --
+ * returns data from the cache to the caller <b>if</b> it exists <b>else</b> queries from DB and
+ * stores it into the cache for future use. These strategies determine when the data in the cache
+ * should be written back to the backing store (i.e. Database) and help keep both data sources
+ * synchronized/up-to-date. This pattern can improve performance and also helps to maintain
+ * consistency between data held in the cache and the data in the underlying data store.
* <p>
* In this example, the user account ({@link UserAccount}) entity is used as the underlying
* application data. The cache itself is implemented as an internal (Java) data structure. It adopts
- * a Least-Recently-Used (LRU) strategy for evicting data from itself when its full. The three
+ * a Least-Recently-Used (LRU) strategy for evicting data from itself when its full. The four
* strategies are individually tested. The testing of the cache is restricted towards saving and
* querying of user accounts from the underlying data store ( {@link DbManager}). The main class (
* {@link App} is not aware of the underlying mechanics of the application (i.e. save and query) and
@@ -74,6 +75,7 @@ public static void main(String[] args) {
app.useReadAndWriteThroughStrategy();
app.useReadThroughAndWriteAroundStrategy();
app.useReadThroughAndWriteBehindStrategy();
+ app.useCacheAsideStategy();
}
/**
@@ -136,4 +138,26 @@ public void useReadThroughAndWriteBehindStrategy() {
AppManager.find("004");
System.out.println(AppManager.printCacheContent());
}
+
+ /**
+ * Cache-Aside
+ */
+ public void useCacheAsideStategy() {
+ System.out.println("# CachingPolicy.ASIDE");
+ AppManager.initCachingPolicy(CachingPolicy.ASIDE);
+ System.out.println(AppManager.printCacheContent());
+
+ UserAccount userAccount3 = new UserAccount("003", "Adam", "He likes food.");
+ UserAccount userAccount4 = new UserAccount("004", "Rita", "She hates cats.");
+ UserAccount userAccount5 = new UserAccount("005", "Isaac", "He is allergic to mustard.");
+ AppManager.save(userAccount3);
+ AppManager.save(userAccount4);
+ AppManager.save(userAccount5);
+
+ System.out.println(AppManager.printCacheContent());
+ AppManager.find("003");
+ System.out.println(AppManager.printCacheContent());
+ AppManager.find("004");
+ System.out.println(AppManager.printCacheContent());
+ }
}
diff --git a/caching/src/main/java/com/iluwatar/caching/AppManager.java b/caching/src/main/java/com/iluwatar/caching/AppManager.java
index 2967c759f7b7..2d6a424a35b4 100644
--- a/caching/src/main/java/com/iluwatar/caching/AppManager.java
+++ b/caching/src/main/java/com/iluwatar/caching/AppManager.java
@@ -64,12 +64,7 @@ public static void initDb(boolean useMongoDb) {
public static void initCachingPolicy(CachingPolicy policy) {
cachingPolicy = policy;
if (cachingPolicy == CachingPolicy.BEHIND) {
- Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
- @Override
- public void run() {
- CacheStore.flushCache();
- }
- }));
+ Runtime.getRuntime().addShutdownHook(new Thread(CacheStore::flushCache));
}
CacheStore.clearCache();
}
@@ -86,6 +81,8 @@ public static UserAccount find(String userId) {
return CacheStore.readThrough(userId);
} else if (cachingPolicy == CachingPolicy.BEHIND) {
return CacheStore.readThroughWithWriteBackPolicy(userId);
+ } else if (cachingPolicy == CachingPolicy.ASIDE) {
+ return findAside(userId);
}
return null;
}
@@ -100,10 +97,37 @@ public static void save(UserAccount userAccount) {
CacheStore.writeAround(userAccount);
} else if (cachingPolicy == CachingPolicy.BEHIND) {
CacheStore.writeBehind(userAccount);
+ } else if (cachingPolicy == CachingPolicy.ASIDE) {
+ saveAside(userAccount);
}
}
public static String printCacheContent() {
return CacheStore.print();
}
+
+ /**
+ * Cache-Aside save user account helper
+ */
+ private static void saveAside(UserAccount userAccount) {
+ DbManager.updateDb(userAccount);
+ CacheStore.invalidate(userAccount.getUserId());
+ }
+
+ /**
+ * Cache-Aside find user account helper
+ */
+ private static UserAccount findAside(String userId) {
+ UserAccount userAccount = CacheStore.get(userId);
+ if (userAccount != null) {
+ return userAccount;
+ }
+
+ userAccount = DbManager.readFromDb(userId);
+ if (userAccount != null) {
+ CacheStore.set(userId, userAccount);
+ }
+
+ return userAccount;
+ }
}
diff --git a/caching/src/main/java/com/iluwatar/caching/CacheStore.java b/caching/src/main/java/com/iluwatar/caching/CacheStore.java
index 5903f82193e9..c2b95a1bdb55 100644
--- a/caching/src/main/java/com/iluwatar/caching/CacheStore.java
+++ b/caching/src/main/java/com/iluwatar/caching/CacheStore.java
@@ -40,7 +40,7 @@ private CacheStore() {
* Init cache capacity
*/
public static void initCapacity(int capacity) {
- if (null == cache) {
+ if (cache == null) {
cache = new LruCache(capacity);
} else {
cache.setCapacity(capacity);
@@ -121,7 +121,7 @@ public static void writeBehind(UserAccount userAccount) {
* Clears cache
*/
public static void clearCache() {
- if (null != cache) {
+ if (cache != null) {
cache.clear();
}
}
@@ -153,4 +153,25 @@ public static String print() {
sb.append("----\n");
return sb.toString();
}
+
+ /**
+ * Delegate to backing cache store
+ */
+ public static UserAccount get(String userId) {
+ return cache.get(userId);
+ }
+
+ /**
+ * Delegate to backing cache store
+ */
+ public static void set(String userId, UserAccount userAccount) {
+ cache.set(userId, userAccount);
+ }
+
+ /**
+ * Delegate to backing cache store
+ */
+ public static void invalidate(String userId) {
+ cache.invalidate(userId);
+ }
}
diff --git a/caching/src/main/java/com/iluwatar/caching/CachingPolicy.java b/caching/src/main/java/com/iluwatar/caching/CachingPolicy.java
index 490113baa3d9..5ad32f6993a5 100644
--- a/caching/src/main/java/com/iluwatar/caching/CachingPolicy.java
+++ b/caching/src/main/java/com/iluwatar/caching/CachingPolicy.java
@@ -24,11 +24,11 @@
/**
*
- * Enum class containing the three caching strategies implemented in the pattern.
+ * Enum class containing the four caching strategies implemented in the pattern.
*
*/
public enum CachingPolicy {
- THROUGH("through"), AROUND("around"), BEHIND("behind");
+ THROUGH("through"), AROUND("around"), BEHIND("behind"), ASIDE("aside");
private String policy;
diff --git a/caching/src/main/java/com/iluwatar/caching/DbManager.java b/caching/src/main/java/com/iluwatar/caching/DbManager.java
index c12461d0c690..455302106b57 100644
--- a/caching/src/main/java/com/iluwatar/caching/DbManager.java
+++ b/caching/src/main/java/com/iluwatar/caching/DbManager.java
@@ -82,7 +82,7 @@ public static UserAccount readFromDb(String userId) {
}
return null;
}
- if (null == db) {
+ if (db == null) {
try {
connect();
} catch (ParseException e) {
@@ -106,7 +106,7 @@ public static void writeToDb(UserAccount userAccount) {
virtualDB.put(userAccount.getUserId(), userAccount);
return;
}
- if (null == db) {
+ if (db == null) {
try {
connect();
} catch (ParseException e) {
@@ -126,7 +126,7 @@ public static void updateDb(UserAccount userAccount) {
virtualDB.put(userAccount.getUserId(), userAccount);
return;
}
- if (null == db) {
+ if (db == null) {
try {
connect();
} catch (ParseException e) {
@@ -148,7 +148,7 @@ public static void upsertDb(UserAccount userAccount) {
virtualDB.put(userAccount.getUserId(), userAccount);
return;
}
- if (null == db) {
+ if (db == null) {
try {
connect();
} catch (ParseException e) {
diff --git a/caching/src/main/java/com/iluwatar/caching/LruCache.java b/caching/src/main/java/com/iluwatar/caching/LruCache.java
index 5c5549afd9d7..00e27ccf1fc1 100644
--- a/caching/src/main/java/com/iluwatar/caching/LruCache.java
+++ b/caching/src/main/java/com/iluwatar/caching/LruCache.java
@@ -73,7 +73,6 @@ public UserAccount get(String userId) {
}
/**
- *
* Remove node from linked list.
*/
public void remove(Node node) {
@@ -90,7 +89,6 @@ public void remove(Node node) {
}
/**
- *
* Move node to the front of the list.
*/
public void setHead(Node node) {
@@ -136,10 +134,11 @@ public boolean contains(String userId) {
* Invalidate cache for user
*/
public void invalidate(String userId) {
- System.out.println("# " + userId + " has been updated! Removing older version from cache...");
- Node toBeRemoved = cache.get(userId);
- remove(toBeRemoved);
- cache.remove(userId);
+ Node toBeRemoved = cache.remove(userId);
+ if (toBeRemoved != null) {
+ System.out.println("# " + userId + " has been updated! Removing older version from cache...");
+ remove(toBeRemoved);
+ }
}
public boolean isFull() {
@@ -160,7 +159,6 @@ public void clear() {
}
/**
- *
* Returns cache data in list form.
*/
public List<UserAccount> getCacheDataInListForm() {
diff --git a/caching/src/main/java/com/iluwatar/caching/UserAccount.java b/caching/src/main/java/com/iluwatar/caching/UserAccount.java
index e2444ad72769..657f12fa33f1 100644
--- a/caching/src/main/java/com/iluwatar/caching/UserAccount.java
+++ b/caching/src/main/java/com/iluwatar/caching/UserAccount.java
@@ -23,9 +23,7 @@
package com.iluwatar.caching;
/**
- *
* Entity class (stored in cache and DB) used in the application.
- *
*/
public class UserAccount {
private String userId;
| diff --git a/caching/src/test/java/com/iluwatar/caching/CachingTest.java b/caching/src/test/java/com/iluwatar/caching/CachingTest.java
index 19262a3b6e35..9d2299902a8c 100644
--- a/caching/src/test/java/com/iluwatar/caching/CachingTest.java
+++ b/caching/src/test/java/com/iluwatar/caching/CachingTest.java
@@ -60,4 +60,9 @@ public void testReadThroughAndWriteAroundStrategy() {
public void testReadThroughAndWriteBehindStrategy() {
app.useReadThroughAndWriteBehindStrategy();
}
+
+ @Test
+ public void testCacheAsideStrategy() {
+ app.useCacheAsideStategy();
+ }
}
| train | train | "2016-09-18T16:51:09" | "2016-07-02T16:56:23Z" | iluwatar | train |
iluwatar/java-design-patterns/437_500 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/437 | iluwatar/java-design-patterns/500 | [
"timestamp(timedelta=6.0, similarity=0.8973045866339322)"
] | 4ca205c03cc03ea5bc80fe27c0a4594f0d087582 | a37a29e12b43055dea72902e6bae1f3b72bddd41 | [
"https://sites.google.com/site/steveyegge2/singleton-considered-stupid\n",
"http://www.yegor256.com/2016/06/27/singletons-must-die.html\n",
"http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/\n",
"HI!\n\nI would like to pick this one and #436 as well.\n",
"@dmitraver you're good to go!\n"
] | [] | "2016-10-04T12:37:44Z" | [
"type: enhancement",
"info: good first issue"
] | Add criticism to Singleton | http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons
| [
"service-locator/README.md",
"singleton/README.md"
] | [
"service-locator/README.md",
"singleton/README.md"
] | [] | diff --git a/service-locator/README.md b/service-locator/README.md
index 31d82b13f8bd..479c9ed0f942 100644
--- a/service-locator/README.md
+++ b/service-locator/README.md
@@ -33,6 +33,12 @@ improves the performance of application to great extent.
* lookups of services are done quite frequently
* large number of services are being used
+## Consequences
+
+* Violates Interface Segregation Principle (ISP) by providing pattern consumers with an access
+to a number of services that they don't potentially need.
+* Creates hidden dependencies that can break the clients at runtime.
+
## Credits
* [J2EE Design Patterns](http://www.amazon.com/J2EE-Design-Patterns-William-Crawford/dp/0596004273/ref=sr_1_2)
diff --git a/singleton/README.md b/singleton/README.md
index e1bb42a45eab..4032ffaed03b 100644
--- a/singleton/README.md
+++ b/singleton/README.md
@@ -36,6 +36,13 @@ Use the Singleton pattern when
* [java.lang.System#getSecurityManager()](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getSecurityManager--)
+## Consequences
+
+* Violates Single Responsibility Principle (SRP) by controlling their own creation and lifecycle.
+* Encourages using a global shared instance which prevents an object and resources used by this object from being deallocated.
+* Creates tightly coupled code that is difficult to test.
+* Makes it almost impossible to subclass a Singleton.
+
## Credits
* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612)
| null | train | train | "2016-09-30T18:40:28" | "2016-06-28T18:36:46Z" | iluwatar | train |
iluwatar/java-design-patterns/436_500 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/436 | iluwatar/java-design-patterns/500 | [
"timestamp(timedelta=0.0, similarity=0.9452600425800433)"
] | 4ca205c03cc03ea5bc80fe27c0a4594f0d087582 | a37a29e12b43055dea72902e6bae1f3b72bddd41 | [
"Assigned to @dmitraver\n"
] | [] | "2016-10-04T12:37:44Z" | [
"type: enhancement",
"info: good first issue"
] | Add criticism to Service Locator | More information could be added to `Consequences` section of the Service Locator pattern.
http://criticalsoftwareblog.com/index.php/2015/10/25/object-composability-another-reason-why-the-service-locator-is-an-anti-pattern/
See the pattern template here: https://github.com/iluwatar/java-design-patterns/wiki/02.-Pattern-template
| [
"service-locator/README.md",
"singleton/README.md"
] | [
"service-locator/README.md",
"singleton/README.md"
] | [] | diff --git a/service-locator/README.md b/service-locator/README.md
index 31d82b13f8bd..479c9ed0f942 100644
--- a/service-locator/README.md
+++ b/service-locator/README.md
@@ -33,6 +33,12 @@ improves the performance of application to great extent.
* lookups of services are done quite frequently
* large number of services are being used
+## Consequences
+
+* Violates Interface Segregation Principle (ISP) by providing pattern consumers with an access
+to a number of services that they don't potentially need.
+* Creates hidden dependencies that can break the clients at runtime.
+
## Credits
* [J2EE Design Patterns](http://www.amazon.com/J2EE-Design-Patterns-William-Crawford/dp/0596004273/ref=sr_1_2)
diff --git a/singleton/README.md b/singleton/README.md
index e1bb42a45eab..4032ffaed03b 100644
--- a/singleton/README.md
+++ b/singleton/README.md
@@ -36,6 +36,13 @@ Use the Singleton pattern when
* [java.lang.System#getSecurityManager()](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getSecurityManager--)
+## Consequences
+
+* Violates Single Responsibility Principle (SRP) by controlling their own creation and lifecycle.
+* Encourages using a global shared instance which prevents an object and resources used by this object from being deallocated.
+* Creates tightly coupled code that is difficult to test.
+* Makes it almost impossible to subclass a Singleton.
+
## Credits
* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612)
| null | train | train | "2016-09-30T18:40:28" | "2016-06-26T07:56:03Z" | iluwatar | train |
iluwatar/java-design-patterns/498_503 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/498 | iluwatar/java-design-patterns/503 | [
"timestamp(timedelta=72.0, similarity=0.9380508949000216)"
] | 19cb715d20f269eb00aa6569244bf090459eb6b7 | cc02ff472b217a9b19d07dd4af84fa888ef469cb | [
"Hi! Great library :+1: \nI want to take this one but what is the main difference to a simple [factory pattern](https://www.tutorialspoint.com/design_pattern/factory_pattern.htm)?\n\nSince the link you shared was working with employees i have thought for something like this:\n\n``` java\nEmployeeMother mother = new EmployeeMother();\nEmployee heather = mother.bear(EmployeeName.HEATHER);\nEmployee heather = mother.bear(EmployeeName.JOHN);\n```\n\nwhere EmployeeName is an enumeration of names. Is this the right approach?\n",
"@igeligel some elaboration here http://stackoverflow.com/questions/923319/what-is-an-objectmother. I'll change to labels to indicate you're working on it.\n",
"Yeah i want to work on this. I will probably code it the next days and check for a code review here then (i will announce if i think it is ready).\n\nEdit: Thanks for the response :+1: \n",
"I have made the first try. The only thing that has not worked yet is the PlantUML diagram. I will try to make this tomorrow and commit to the fork again. A code review would be appreciated :)\n",
"Don't worry about the PlantUML diagram - it is still experimental and we don't check it when you make the pull request. ObjectAid diagram is the one you should generate, as per instructions here https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute\n"
] | [
"Confusing naming here\n",
"Confusing naming here\n",
"Confusing naming here\n"
] | "2016-10-06T18:15:38Z" | [
"epic: pattern",
"info: good first issue"
] | Object Mother pattern | http://martinfowler.com/bliki/ObjectMother.html
| [
"pom.xml"
] | [
"object-mother/README.md",
"object-mother/etc/object-mother.ucls",
"object-mother/etc/object-mother.urm.puml",
"object-mother/pom.xml",
"object-mother/src/main/java/com/iluwatar/objectmother/King.java",
"object-mother/src/main/java/com/iluwatar/objectmother/Queen.java",
"object-mother/src/main/java/com/iluwatar/objectmother/Royalty.java",
"object-mother/src/main/java/com/iluwatar/objectmother/RoyaltyObjectMother.java",
"pom.xml"
] | [
"object-mother/src/test/java/com/iluwatar/objectmother/test/RoyaltyObjectMotherTest.java"
] | diff --git a/object-mother/README.md b/object-mother/README.md
new file mode 100644
index 000000000000..9188c8b4128d
--- /dev/null
+++ b/object-mother/README.md
@@ -0,0 +1,31 @@
+---
+layout: pattern
+title: Object Mother
+folder: object-mother
+permalink: /patterns/object-mother/
+pumlid:
+categories: Creational
+tags:
+ - Java
+ - Difficulty-Beginner
+---
+
+## Object Mother
+Define a factory of immutable content with separated builder and factory interfaces.
+
+![alt text](./etc/object-mother.png "Object Mother")
+
+## Applicability
+Use the Object Mother pattern when
+
+* You want consistent objects over several tests
+* you want to reduce code for creation of objects in tests
+* every test should run with fresh data
+
+## Credits
+
+* [Answer by David Brown](http://stackoverflow.com/questions/923319/what-is-an-objectmother) to the stackoverflow question: [What is an ObjectMother?](http://stackoverflow.com/questions/923319/what-is-an-objectmother)
+
+* [c2wiki - Object Mother](http://c2.com/cgi/wiki?ObjectMother)
+
+* [Nat Pryce - Test Data Builders: an alternative to the Object Mother pattern](http://www.natpryce.com/articles/000714.html)
\ No newline at end of file
diff --git a/object-mother/etc/object-mother.ucls b/object-mother/etc/object-mother.ucls
new file mode 100644
index 000000000000..ef6cee5eff45
--- /dev/null
+++ b/object-mother/etc/object-mother.ucls
@@ -0,0 +1,56 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<class-diagram version="1.1.11" icons="true" automaticImage="PNG" always-add-relationships="false"
+ generalizations="true" realizations="true" associations="true" dependencies="false" nesting-relationships="true"
+ router="FAN">
+ <class id="1" language="java" name="com.iluwatar.objectmother.RoyaltyObjectMother" project="object-mother"
+ file="/object-mother/src/main/java/com/iluwatar/objectmother/RoyaltyObjectMother.java" binary="false"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="535" y="366"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <class id="2" language="java" name="com.iluwatar.objectmother.King" project="object-mother"
+ file="/object-mother/src/main/java/com/iluwatar/objectmother/King.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="285" y="141"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <class id="3" language="java" name="com.iluwatar.objectmother.Queen" project="object-mother"
+ file="/object-mother/src/main/java/com/iluwatar/objectmother/Queen.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="783" y="143"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <interface id="4" language="java" name="com.iluwatar.objectmother.Royalty" project="object-mother"
+ file="/object-mother/src/main/java/com/iluwatar/objectmother/Royalty.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="536" y="142"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </interface>
+ <realization id="5">
+ <end type="SOURCE" refId="2"/>
+ <end type="TARGET" refId="4"/>
+ </realization>
+ <realization id="6">
+ <end type="SOURCE" refId="3"/>
+ <end type="TARGET" refId="4"/>
+ </realization>
+ <classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </classifier-display>
+ <association-display labels="true" multiplicity="true"/>
+</class-diagram>
\ No newline at end of file
diff --git a/object-mother/etc/object-mother.urm.puml b/object-mother/etc/object-mother.urm.puml
new file mode 100644
index 000000000000..9b26450f065f
--- /dev/null
+++ b/object-mother/etc/object-mother.urm.puml
@@ -0,0 +1,45 @@
+@startuml
+package com.iluwatar.objectmother {
+ class RoyaltyObjectMother {
+ + RoyaltyObjectMother()
+ + createDrunkKing() : King {static}
+ + createFlirtyQueen() : Queen {static}
+ + createHappyDrunkKing() : King {static}
+ + createHappyKing() : King {static}
+ + createNotFlirtyQueen() : Queen {static}
+ + createSoberUnhappyKing() : King {static}
+ }
+ class Queen {
+ - isDrunk : boolean
+ - isFlirty : boolean
+ - isHappy : boolean
+ + Queen()
+ + getFlirted(king : King) : boolean
+ + isFlirty() : boolean
+ + makeDrunk()
+ + makeHappy()
+ + makeSober()
+ + makeUnhappy()
+ + setFlirtiness(flirtiness : boolean)
+ }
+ interface Royalty {
+ + makeDrunk() {abstract}
+ + makeHappy() {abstract}
+ + makeSober() {abstract}
+ + makeUnhappy() {abstract}
+ }
+ class King {
+ ~ isDrunk : boolean
+ ~ isHappy : boolean
+ + King()
+ + flirt(queen : Queen)
+ + isHappy() : boolean
+ + makeDrunk()
+ + makeHappy()
+ + makeSober()
+ + makeUnhappy()
+ }
+}
+Queen ..|> Royalty
+King ..|> Royalty
+@enduml
\ No newline at end of file
diff --git a/object-mother/pom.xml b/object-mother/pom.xml
new file mode 100644
index 000000000000..91bdff8e24dc
--- /dev/null
+++ b/object-mother/pom.xml
@@ -0,0 +1,48 @@
+<?xml version="1.0"?>
+<!--
+
+ The MIT License
+ Copyright (c) 2016 Ilkka Seppälä
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+
+-->
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
+ xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>java-design-patterns</artifactId>
+ <version>1.14.0-SNAPSHOT</version>
+ </parent>
+ <artifactId>object-mother</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
\ No newline at end of file
diff --git a/object-mother/src/main/java/com/iluwatar/objectmother/King.java b/object-mother/src/main/java/com/iluwatar/objectmother/King.java
new file mode 100644
index 000000000000..544b0bacba8c
--- /dev/null
+++ b/object-mother/src/main/java/com/iluwatar/objectmother/King.java
@@ -0,0 +1,66 @@
+/**
+ * The MIT License
+ * Copyright (c) 2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.objectmother;
+
+public class King implements Royalty {
+ boolean isDrunk = false;
+ boolean isHappy = false;
+
+ @Override
+ public void makeDrunk() {
+ isDrunk = true;
+ }
+
+ @Override
+ public void makeSober() {
+ isDrunk = false;
+ }
+
+ @Override
+ public void makeHappy() {
+ isHappy = true;
+ }
+
+ @Override
+ public void makeUnhappy() {
+ isHappy = false;
+ }
+
+ public boolean isHappy() {
+ return isHappy;
+ }
+
+ /**
+ * Method to flirt to a queen.
+ * @param queen Queen which should be flirted.
+ */
+ public void flirt(Queen queen) {
+ boolean flirtStatus = queen.getFlirted(this);
+ if (flirtStatus == false) {
+ this.makeUnhappy();
+ } else {
+ this.makeHappy();
+ }
+
+ }
+}
diff --git a/object-mother/src/main/java/com/iluwatar/objectmother/Queen.java b/object-mother/src/main/java/com/iluwatar/objectmother/Queen.java
new file mode 100644
index 000000000000..3e18fbf3a902
--- /dev/null
+++ b/object-mother/src/main/java/com/iluwatar/objectmother/Queen.java
@@ -0,0 +1,69 @@
+/**
+ * The MIT License
+ * Copyright (c) 2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.objectmother;
+
+public class Queen implements Royalty {
+ private boolean isDrunk = false;
+ private boolean isHappy = false;
+ private boolean isFlirty = false;
+
+ @Override
+ public void makeDrunk() {
+ isDrunk = true;
+ }
+
+ @Override
+ public void makeSober() {
+ isDrunk = false;
+ }
+
+ @Override
+ public void makeHappy() {
+ isHappy = true;
+ }
+
+ @Override
+ public void makeUnhappy() {
+ isHappy = false;
+ }
+
+ public boolean isFlirty() {
+ return isFlirty;
+ }
+
+ public void setFlirtiness(boolean flirtiness) {
+ this.isFlirty = flirtiness;
+ }
+
+ /**
+ * Method which is called when the king is flirting to a queen.
+ * @param king King who initialized the flirt.
+ * @return A value which describes if the flirt was successful or not.
+ */
+ public boolean getFlirted(King king) {
+ if (this.isFlirty && king.isHappy && !king.isDrunk) {
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/object-mother/src/main/java/com/iluwatar/objectmother/Royalty.java b/object-mother/src/main/java/com/iluwatar/objectmother/Royalty.java
new file mode 100644
index 000000000000..2bebc093991f
--- /dev/null
+++ b/object-mother/src/main/java/com/iluwatar/objectmother/Royalty.java
@@ -0,0 +1,33 @@
+/**
+ * The MIT License
+ * Copyright (c) 2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.objectmother;
+
+public interface Royalty {
+ void makeDrunk();
+
+ void makeSober();
+
+ void makeHappy();
+
+ void makeUnhappy();
+}
diff --git a/object-mother/src/main/java/com/iluwatar/objectmother/RoyaltyObjectMother.java b/object-mother/src/main/java/com/iluwatar/objectmother/RoyaltyObjectMother.java
new file mode 100644
index 000000000000..624a29132531
--- /dev/null
+++ b/object-mother/src/main/java/com/iluwatar/objectmother/RoyaltyObjectMother.java
@@ -0,0 +1,83 @@
+/**
+ * The MIT License
+ * Copyright (c) 2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.objectmother;
+
+public final class RoyaltyObjectMother {
+
+ /**
+ * Method to create a sober and unhappy king. The standard paramters are set.
+ * @return An instance of {@link com.iluwatar.objectmother.King} with the standard properties.
+ */
+ public static King createSoberUnhappyKing() {
+ return new King();
+ }
+
+ /**
+ * Method of the object mother to create a drunk king.
+ * @return A drunk {@link com.iluwatar.objectmother.King}.
+ */
+ public static King createDrunkKing() {
+ King king = new King();
+ king.makeDrunk();
+ return king;
+ }
+
+ /**
+ * Method to create a happy king.
+ * @return A happy {@link com.iluwatar.objectmother.King}.
+ */
+ public static King createHappyKing() {
+ King king = new King();
+ king.makeHappy();
+ return king;
+ }
+
+ /**
+ * Method to create a happy and drunk king.
+ * @return A drunk and happy {@link com.iluwatar.objectmother.King}.
+ */
+ public static King createHappyDrunkKing() {
+ King king = new King();
+ king.makeHappy();
+ king.makeDrunk();
+ return king;
+ }
+
+ /**
+ * Method to create a flirty queen.
+ * @return A flirty {@link com.iluwatar.objectmother.Queen}.
+ */
+ public static Queen createFlirtyQueen() {
+ Queen queen = new Queen();
+ queen.setFlirtiness(true);
+ return queen;
+ }
+
+ /**
+ * Method to create a not flirty queen.
+ * @return A not flirty {@link com.iluwatar.objectmother.Queen}.
+ */
+ public static Queen createNotFlirtyQueen() {
+ return new Queen();
+ }
+}
diff --git a/pom.xml b/pom.xml
index 538058a81988..76e108a57c50 100644
--- a/pom.xml
+++ b/pom.xml
@@ -133,7 +133,8 @@
<module>promise</module>
<module>page-object</module>
<module>event-asynchronous</module>
- </modules>
+ <module>object-mother</module>
+ </modules>
<dependencyManagement>
<dependencies>
| diff --git a/object-mother/src/test/java/com/iluwatar/objectmother/test/RoyaltyObjectMotherTest.java b/object-mother/src/test/java/com/iluwatar/objectmother/test/RoyaltyObjectMotherTest.java
new file mode 100644
index 000000000000..ebe536d24bcc
--- /dev/null
+++ b/object-mother/src/test/java/com/iluwatar/objectmother/test/RoyaltyObjectMotherTest.java
@@ -0,0 +1,89 @@
+/**
+ * The MIT License
+ * Copyright (c) 2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.objectmother.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+import com.iluwatar.objectmother.King;
+import com.iluwatar.objectmother.Queen;
+import com.iluwatar.objectmother.Royalty;
+import com.iluwatar.objectmother.RoyaltyObjectMother;
+
+public class RoyaltyObjectMotherTest {
+
+ @Test
+ public void unsuccessfulKingFlirt() {
+ King soberUnhappyKing = RoyaltyObjectMother.createSoberUnhappyKing();
+ Queen flirtyQueen = RoyaltyObjectMother.createFlirtyQueen();
+ soberUnhappyKing.flirt(flirtyQueen);
+ assertFalse(soberUnhappyKing.isHappy());
+ }
+
+ @Test
+ public void queenIsBlockingFlirtCauseDrunkKing() {
+ King drunkUnhappyKing = RoyaltyObjectMother.createDrunkKing();
+ Queen notFlirtyQueen = RoyaltyObjectMother.createNotFlirtyQueen();
+ drunkUnhappyKing.flirt(notFlirtyQueen);
+ assertFalse(drunkUnhappyKing.isHappy());
+ }
+
+ @Test
+ public void queenIsBlockingFlirt() {
+ King soberHappyKing = RoyaltyObjectMother.createHappyKing();
+ Queen notFlirtyQueen = RoyaltyObjectMother.createNotFlirtyQueen();
+ soberHappyKing.flirt(notFlirtyQueen);
+ assertFalse(soberHappyKing.isHappy());
+ }
+
+ @Test
+ public void successfullKingFlirt() {
+ King soberHappyKing = RoyaltyObjectMother.createHappyKing();
+ Queen flirtyQueen = RoyaltyObjectMother.createFlirtyQueen();
+ soberHappyKing.flirt(flirtyQueen);
+ assertTrue(soberHappyKing.isHappy());
+ }
+
+ @Test
+ public void testQueenType() {
+ Royalty flirtyQueen = RoyaltyObjectMother.createFlirtyQueen();
+ Royalty notFlirtyQueen = RoyaltyObjectMother.createNotFlirtyQueen();
+ assertEquals(flirtyQueen.getClass(), Queen.class);
+ assertEquals(notFlirtyQueen.getClass(), Queen.class);
+ }
+
+ @Test
+ public void testKingType() {
+ Royalty drunkKing = RoyaltyObjectMother.createDrunkKing();
+ Royalty happyDrunkKing = RoyaltyObjectMother.createHappyDrunkKing();
+ Royalty happyKing = RoyaltyObjectMother.createHappyKing();
+ Royalty soberUnhappyKing = RoyaltyObjectMother.createSoberUnhappyKing();
+ assertEquals(drunkKing.getClass(), King.class);
+ assertEquals(happyDrunkKing.getClass(), King.class);
+ assertEquals(happyKing.getClass(), King.class);
+ assertEquals(soberUnhappyKing.getClass(), King.class);
+ }
+}
| train | train | "2016-10-19T22:08:51" | "2016-10-02T04:36:47Z" | iluwatar | train |
iluwatar/java-design-patterns/621_623 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/621 | iluwatar/java-design-patterns/623 | [
"keyword_pr_to_issue"
] | f28ed7b46e5897f53efb20041e92f13a90fb9209 | 6c9e005a799fddd0200b4276d96b338dcb13b488 | [
"I'm happy to submit a PR for this"
] | [] | "2017-09-01T01:29:35Z" | [
"type: bug",
"info: help wanted",
"info: good first issue"
] | Missing synchronized keyword | Hi,
https://github.com/iluwatar/java-design-patterns/blob/master/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java#L58 - the method should also be `synchronized`.
Best regards,
Martin | [
"object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java"
] | [
"object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java"
] | [] | diff --git a/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java b/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java
index df6e887b86f1..e76d003521a5 100644
--- a/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java
+++ b/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java
@@ -55,7 +55,7 @@ public synchronized void checkIn(T instance) {
}
@Override
- public String toString() {
+ public synchronized String toString() {
return String.format("Pool available=%d inUse=%d", available.size(), inUse.size());
}
}
| null | train | train | "2017-08-31T21:11:58" | "2017-08-29T21:18:36Z" | MartyIX | train |
iluwatar/java-design-patterns/631_636 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/631 | iluwatar/java-design-patterns/636 | [
"timestamp(timedelta=79.0, similarity=0.88090052548208)"
] | 1b0f55c3eb398fb12591619bd7e822beabd48825 | 99de0e1644aa1e2c1f6cfc47d87f088b562fdaf4 | [
"@iluwatar: I am picking this up for development.",
"Ok @gopinath-langote "
] | [
"Please keep the copyright unchanged e.g. Copyright (c) 2014-2017 Ilkka Seppälä. Check the other files for this too.",
"The class looks immutable the private fields should be declared final.",
"Can we name this class just `App` for consistency? This way it is easier for users to find the main class where to start looking at the example.",
"This could be one-liner e.g. `VideoResource videoResource = new VideoResource(new FieldJsonMapper(), videos);`",
"@iluwatar : Updated copyright header to contain year range e.g. Copyright (c) 2014-2017 Gopinath Langote",
"@iluwatar : Done. Made it final. Thanks for pointing it.",
"@iluwatar : Make sense to keep to consistent. updated it. Thanks for pointing out.",
"@iluwatar : Done. Thanks for pointing out this."
] | "2017-09-19T13:40:06Z" | [
"epic: pattern"
] | Partial Response pattern | Pattern where an API lets clients specify the structure of the response.
http://yaoganglian.com/2013/07/01/partial-response/ | [
"pom.xml"
] | [
"partial-response/README.md",
"partial-response/etc/partial-response.ucls",
"partial-response/etc/partial-response.urm.puml",
"partial-response/pom.xml",
"partial-response/src/main/java/com/iluwatar/partialresponse/App.java",
"partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java",
"partial-response/src/main/java/com/iluwatar/partialresponse/Video.java",
"partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java",
"pom.xml"
] | [
"partial-response/src/test/java/com/iluwatar/partialresponse/AppTest.java",
"partial-response/src/test/java/com/iluwatar/partialresponse/FieldJsonMapperTest.java",
"partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java"
] | diff --git a/partial-response/README.md b/partial-response/README.md
new file mode 100644
index 000000000000..5d03cb359fb2
--- /dev/null
+++ b/partial-response/README.md
@@ -0,0 +1,29 @@
+---
+layout: pattern
+title: Partial Response
+folder: partial-response
+permalink: /patterns/partial-response/
+categories: Architectural
+tags:
+ - Java
+ - KISS
+ - YAGNI
+ - Difficulty-Beginner
+---
+
+## Intent
+Send partial response from server to client on need basis. Client will specify the the fields
+that it need to server, instead of serving all details for resource.
+
+![alt text](./etc/partial-response.urm.png "partial-response")
+
+## Applicability
+Use the Partial Response pattern when
+
+* Client need only subset of data from resource.
+* To avoid too much data transfer over wire
+
+## Credits
+
+* [Common Design Patterns](https://cloud.google.com/apis/design/design_patterns)
+* [Partial Response in RESTful API Design](http://yaoganglian.com/2013/07/01/partial-response/)
diff --git a/partial-response/etc/partial-response.ucls b/partial-response/etc/partial-response.ucls
new file mode 100644
index 000000000000..a0b029496352
--- /dev/null
+++ b/partial-response/etc/partial-response.ucls
@@ -0,0 +1,65 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<class-diagram version="1.2.1" icons="true" always-add-relationships="false" generalizations="true" realizations="true"
+ associations="true" dependencies="false" nesting-relationships="true" router="FAN">
+ <class id="1" language="java" name="com.iluwatar.partialresponse.Video" project="partial-response"
+ file="/partial-response/src/main/java/com/iluwatar/partialresponse/Video.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="322" y="457"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <class id="2" language="java" name="com.iluwatar.partialresponse.FieldJsonMapper" project="partial-response"
+ file="/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java" binary="false"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="772" y="412"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <class id="3" language="java" name="com.iluwatar.partialresponse.VideoClientApp" project="partial-response"
+ file="/partial-response/src/main/java/com/iluwatar/partialresponse/VideoClientApp.java" binary="false"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="215" y="125"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <class id="4" language="java" name="com.iluwatar.partialresponse.VideoResource" project="partial-response"
+ file="/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java" binary="false"
+ corner="BOTTOM_RIGHT">
+ <position height="101" width="319" x="476" y="66"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <association id="5">
+ <end type="SOURCE" refId="4" navigable="false">
+ <attribute id="6" name="videos"/>
+ <multiplicity id="7" minimum="0" maximum="2147483647"/>
+ </end>
+ <end type="TARGET" refId="1" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <association id="8">
+ <end type="SOURCE" refId="4" navigable="false">
+ <attribute id="9" name="fieldJsonMapper"/>
+ <multiplicity id="10" minimum="0" maximum="1"/>
+ </end>
+ <end type="TARGET" refId="2" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </classifier-display>
+ <association-display labels="true" multiplicity="true"/>
+</class-diagram>
\ No newline at end of file
diff --git a/partial-response/etc/partial-response.urm.puml b/partial-response/etc/partial-response.urm.puml
new file mode 100644
index 000000000000..69efd04548ef
--- /dev/null
+++ b/partial-response/etc/partial-response.urm.puml
@@ -0,0 +1,31 @@
+@startuml
+package com.iluwatar.partialresponse {
+ class FieldJsonMapper {
+ + FieldJsonMapper()
+ - getString(video : Video, declaredField : Field) : String
+ + toJson(video : Video, fields : String[]) : String
+ }
+ class Video {
+ - description : String
+ - director : String
+ - id : Integer
+ - language : String
+ - length : Integer
+ - title : String
+ + Video(id : Integer, title : String, length : Integer, description : String, director : String, language : String)
+ + toString() : String
+ }
+ class VideoClientApp {
+ - LOGGER : Logger {static}
+ + VideoClientApp()
+ + main(args : String[]) {static}
+ }
+ class VideoResource {
+ - fieldJsonMapper : FieldJsonMapper
+ - videos : Map<Integer, Video>
+ + VideoResource(fieldJsonMapper : FieldJsonMapper, videos : Map<Integer, Video>)
+ + getDetails(id : Integer, fields : String[]) : String
+ }
+}
+VideoResource --> "-fieldJsonMapper" FieldJsonMapper
+@enduml
\ No newline at end of file
diff --git a/partial-response/pom.xml b/partial-response/pom.xml
new file mode 100644
index 000000000000..7ce36ecec054
--- /dev/null
+++ b/partial-response/pom.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <parent>
+ <artifactId>java-design-patterns</artifactId>
+ <groupId>com.iluwatar</groupId>
+ <version>1.17.0-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+
+ <artifactId>partial-response</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ </dependency>
+ </dependencies>
+
+
+</project>
\ No newline at end of file
diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/App.java b/partial-response/src/main/java/com/iluwatar/partialresponse/App.java
new file mode 100644
index 000000000000..2977b50a71d1
--- /dev/null
+++ b/partial-response/src/main/java/com/iluwatar/partialresponse/App.java
@@ -0,0 +1,74 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2017 Gopinath Langote
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package com.iluwatar.partialresponse;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * The Partial response pattern is a design pattern in which client specifies fields to fetch to serve.
+ * Here {@link App} is playing as client for {@link VideoResource} server.
+ * Client ask for specific fields information in video to server.
+ * <p>
+ * <p>
+ * {@link VideoResource} act as server to serve video information.
+ */
+
+public class App {
+ private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
+
+ /**
+ * Method as act client and request to server for video details.
+ *
+ * @param args program argument.
+ */
+ public static void main(String[] args) throws Exception {
+ Map<Integer, Video> videos = new HashMap<>();
+ videos.put(1, new Video(1, "Avatar", 178, "epic science fiction film", "James Cameron", "English"));
+ videos.put(2, new Video(2, "Godzilla Resurgence", 120, "Action & drama movie|", "Hideaki Anno", "Japanese"));
+ videos.put(3, new Video(3, "Interstellar", 169, "Adventure & Sci-Fi", "Christopher Nolan", "English"));
+ VideoResource videoResource = new VideoResource(new FieldJsonMapper(), videos);
+
+
+ LOGGER.info("Retrieving full response from server:-");
+ LOGGER.info("Get all video information:");
+ String videoDetails = videoResource.getDetails(1);
+ LOGGER.info(videoDetails);
+
+ LOGGER.info("----------------------------------------------------------");
+
+ LOGGER.info("Retrieving partial response from server:-");
+ LOGGER.info("Get video @id, @title, @director:");
+ String specificFieldsDetails = videoResource.getDetails(3, "id", "title", "director");
+ LOGGER.info(specificFieldsDetails);
+
+ LOGGER.info("Get video @id, @length:");
+ String videoLength = videoResource.getDetails(3, "id", "length");
+ LOGGER.info(videoLength);
+ }
+}
diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java b/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java
new file mode 100644
index 000000000000..9283cfa698f0
--- /dev/null
+++ b/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java
@@ -0,0 +1,60 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2017 Gopinath Langote
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package com.iluwatar.partialresponse;
+
+import java.lang.reflect.Field;
+
+/**
+ * Map a video to json
+ */
+public class FieldJsonMapper {
+
+ /**
+ * @param video object containing video information
+ * @param fields fields information to get
+ * @return json of required fields from video
+ */
+ public String toJson(Video video, String[] fields) throws Exception {
+ StringBuilder json = new StringBuilder().append("{");
+
+ for (int i = 0, fieldsLength = fields.length; i < fieldsLength; i++) {
+ json.append(getString(video, Video.class.getDeclaredField(fields[i])));
+ if (i != fieldsLength - 1) {
+ json.append(",");
+ }
+ }
+ json.append("}");
+ return json.toString();
+ }
+
+ private String getString(Video video, Field declaredField) throws IllegalAccessException {
+ declaredField.setAccessible(true);
+ Object value = declaredField.get(video);
+ if (declaredField.get(video) instanceof Integer) {
+ return "\"" + declaredField.getName() + "\"" + ": " + value;
+ }
+ return "\"" + declaredField.getName() + "\"" + ": " + "\"" + value.toString() + "\"";
+ }
+}
diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/Video.java b/partial-response/src/main/java/com/iluwatar/partialresponse/Video.java
new file mode 100644
index 000000000000..e242965e3660
--- /dev/null
+++ b/partial-response/src/main/java/com/iluwatar/partialresponse/Video.java
@@ -0,0 +1,70 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2017 Gopinath Langote
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package com.iluwatar.partialresponse;
+
+/**
+ * {@link Video} is a entity to serve from server.It contains all video related information..
+ * <p>
+ */
+public class Video {
+ private final Integer id;
+ private final String title;
+ private final Integer length;
+ private final String description;
+ private final String director;
+ private final String language;
+
+ /**
+ * @param id video unique id
+ * @param title video title
+ * @param length video length in minutes
+ * @param description video description by publisher
+ * @param director video director name
+ * @param language video language {private, public}
+ */
+ public Video(Integer id, String title, Integer length, String description, String director, String language) {
+ this.id = id;
+ this.title = title;
+ this.length = length;
+ this.description = description;
+ this.director = director;
+ this.language = language;
+ }
+
+ /**
+ * @return json representaion of video
+ */
+ @Override
+ public String toString() {
+ return "{"
+ + "\"id\": " + id + ","
+ + "\"title\": \"" + title + "\","
+ + "\"length\": " + length + ","
+ + "\"description\": \"" + description + "\","
+ + "\"director\": \"" + director + "\","
+ + "\"language\": \"" + language + "\","
+ + "}";
+ }
+}
diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java b/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java
new file mode 100644
index 000000000000..2bf7a73c1f1b
--- /dev/null
+++ b/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java
@@ -0,0 +1,57 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2017 Gopinath Langote
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package com.iluwatar.partialresponse;
+
+import java.util.Map;
+
+/**
+ * The resource class which serves video information.
+ * This class act as server in the demo. Which has all video details.
+ */
+public class VideoResource {
+ private FieldJsonMapper fieldJsonMapper;
+ private Map<Integer, Video> videos;
+
+ /**
+ * @param fieldJsonMapper map object to json.
+ * @param videos initialize resource with existing videos. Act as database.
+ */
+ public VideoResource(FieldJsonMapper fieldJsonMapper, Map<Integer, Video> videos) {
+ this.fieldJsonMapper = fieldJsonMapper;
+ this.videos = videos;
+ }
+
+ /**
+ * @param id video id
+ * @param fields fields to get information about
+ * @return full response if no fields specified else partial response for given field.
+ */
+ public String getDetails(Integer id, String... fields) throws Exception {
+ if (fields.length == 0) {
+ return videos.get(id).toString();
+ }
+ return fieldJsonMapper.toJson(videos.get(id), fields);
+ }
+}
diff --git a/pom.xml b/pom.xml
index f2b6b7ccb69f..59b7cf0785a6 100644
--- a/pom.xml
+++ b/pom.xml
@@ -146,7 +146,8 @@
<module>event-sourcing</module>
<module>data-transfer-object</module>
<module>throttling</module>
- </modules>
+ <module>partial-response</module>
+ </modules>
<dependencyManagement>
<dependencies>
| diff --git a/partial-response/src/test/java/com/iluwatar/partialresponse/AppTest.java b/partial-response/src/test/java/com/iluwatar/partialresponse/AppTest.java
new file mode 100644
index 000000000000..2ac34dd0d0a3
--- /dev/null
+++ b/partial-response/src/test/java/com/iluwatar/partialresponse/AppTest.java
@@ -0,0 +1,40 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2017 Gopinath Langote
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package com.iluwatar.partialresponse;
+
+import org.junit.Test;
+
+/**
+ * Application test
+ */
+public class AppTest {
+
+ @Test
+ public void main() throws Exception {
+ String[] args = {};
+ App.main(args);
+ }
+
+}
\ No newline at end of file
diff --git a/partial-response/src/test/java/com/iluwatar/partialresponse/FieldJsonMapperTest.java b/partial-response/src/test/java/com/iluwatar/partialresponse/FieldJsonMapperTest.java
new file mode 100644
index 000000000000..9bc078b571c9
--- /dev/null
+++ b/partial-response/src/test/java/com/iluwatar/partialresponse/FieldJsonMapperTest.java
@@ -0,0 +1,53 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2017 Gopinath Langote
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package com.iluwatar.partialresponse;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * tests {@link FieldJsonMapper}.
+ */
+public class FieldJsonMapperTest {
+ private FieldJsonMapper mapper;
+
+ @Before
+ public void setUp() {
+ mapper = new FieldJsonMapper();
+ }
+
+ @Test
+ public void shouldReturnJsonForSpecifiedFieldsInVideo() throws Exception {
+ String[] fields = new String[]{"id", "title", "length"};
+ Video video = new Video(2, "Godzilla Resurgence", 120, "Action & drama movie|", "Hideaki Anno", "Japanese");
+
+ String jsonFieldResponse = mapper.toJson(video, fields);
+
+ String expectedDetails = "{\"id\": 2,\"title\": \"Godzilla Resurgence\",\"length\": 120}";
+ assertEquals(expectedDetails, jsonFieldResponse);
+ }
+}
\ No newline at end of file
diff --git a/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java b/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java
new file mode 100644
index 000000000000..0453e8ffdf66
--- /dev/null
+++ b/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java
@@ -0,0 +1,80 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2017 Gopinath Langote
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package com.iluwatar.partialresponse;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.when;
+
+/**
+ * tests {@link VideoResource}.
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class VideoResourceTest {
+ @Mock
+ private FieldJsonMapper fieldJsonMapper;
+
+ private VideoResource resource;
+
+ @Before
+ public void setUp() {
+ Map<Integer, Video> videos = new HashMap<>();
+ videos.put(1, new Video(1, "Avatar", 178, "epic science fiction film", "James Cameron", "English"));
+ videos.put(2, new Video(2, "Godzilla Resurgence", 120, "Action & drama movie|", "Hideaki Anno", "Japanese"));
+ videos.put(3, new Video(3, "Interstellar", 169, "Adventure & Sci-Fi", "Christopher Nolan", "English"));
+ resource = new VideoResource(fieldJsonMapper, videos);
+ }
+
+ @Test
+ public void shouldGiveVideoDetailsById() throws Exception {
+ String actualDetails = resource.getDetails(1);
+
+ String expectedDetails = "{\"id\": 1,\"title\": \"Avatar\",\"length\": 178,\"description\": "
+ + "\"epic science fiction film\",\"director\": \"James Cameron\",\"language\": \"English\",}";
+ assertEquals(expectedDetails, actualDetails);
+ }
+
+ @Test
+ public void shouldGiveSpecifiedFieldsInformationOfVideo() throws Exception {
+ String[] fields = new String[]{"id", "title", "length"};
+
+ String expectedDetails = "{\"id\": 1,\"title\": \"Avatar\",\"length\": 178}";
+ when(fieldJsonMapper.toJson(any(Video.class), eq(fields))).thenReturn(expectedDetails);
+
+ String actualFieldsDetails = resource.getDetails(2, fields);
+
+ assertEquals(expectedDetails, actualFieldsDetails);
+ }
+}
\ No newline at end of file
| train | train | "2017-09-19T07:48:23" | "2017-09-12T14:58:23Z" | gopinath-langote | train |
iluwatar/java-design-patterns/176_651 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/176 | iluwatar/java-design-patterns/651 | [
"timestamp(timedelta=70.0, similarity=0.8823058885599248)"
] | dfb43299a88507211e9acb9a9f21a8ba54f0205a | 41710cbe9e3cb1f83e5f8eb9fce8bf2d4323aba0 | [
"Some Informations:\n- Description from EIP: http://www.enterpriseintegrationpatterns.com/patterns/messaging/WireTap.html\n- Implementation inside Apache Camel: http://camel.apache.org/wire-tap.html\n",
"I can help you out with most EIP patterns, starting from this one.",
"Thanks @codinghog go ahead :+1: "
] | [] | "2017-10-04T17:12:58Z" | [
"epic: pattern"
] | Wire Tap (EIP) | [
"pom.xml"
] | [
"eip-wire-tap/README.md",
"eip-wire-tap/pom.xml",
"eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java",
"eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java",
"eip-wire-tap/src/main/resources/application.properties",
"eip-wire-tap/src/test/resources/application-test.properties",
"pom.xml"
] | [
"eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java",
"eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java"
] | diff --git a/eip-wire-tap/README.md b/eip-wire-tap/README.md
new file mode 100644
index 000000000000..d2742aa313f9
--- /dev/null
+++ b/eip-wire-tap/README.md
@@ -0,0 +1,29 @@
+---
+layout: pattern
+title: EIP Wire Tap
+folder: eip-wire-tap
+permalink: /patterns/eip-wire-tap/
+categories: Enterprise integration
+tags:
+ - Java
+ - Difficulty-Intermittent
+ - Enterprise integration
+---
+
+## Intent
+In most integration cases there is a need to monitor the messages flowing through the system. It is usually achieved
+by intercepting the message and redirecting it to a different location like console, filesystem or the database.
+It is important that such functionality should not modify the original message and influence the processing path.
+
+![alt text](./etc/wiretap.gif "Wire Tap")
+
+## Applicability
+Use the Wire Tap pattern when
+
+* You need to monitor messages flowing through the system
+* You need to redirect the same, unchanged message to two different endpoints/paths
+
+## Credits
+
+* [Gregor Hohpe, Bobby Woolf - Enterprise Integration Patterns](http://www.enterpriseintegrationpatterns.com/patterns/messaging/WireTap.html)
+* [Apache Camel - Documentation](http://camel.apache.org/wire-tap.html)
diff --git a/eip-wire-tap/pom.xml b/eip-wire-tap/pom.xml
new file mode 100644
index 000000000000..b3bc678b0f4d
--- /dev/null
+++ b/eip-wire-tap/pom.xml
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ The MIT License
+ Copyright (c) 2014-2016 Ilkka Seppälä
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>eip-wire-tap</artifactId>
+ <parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>java-design-patterns</artifactId>
+ <version>1.18.0-SNAPSHOT</version>
+ </parent>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter-web</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-core</artifactId>
+ <version>${camel.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-spring-boot</artifactId>
+ <version>${camel.version}</version>
+ </dependency>
+
+ <!-- Testing -->
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter-test</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-test-spring</artifactId>
+ <version>${camel.version}</version>
+ </dependency>
+
+ </dependencies>
+</project>
\ No newline at end of file
diff --git a/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java
new file mode 100644
index 000000000000..7bf4ce0d4991
--- /dev/null
+++ b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java
@@ -0,0 +1,51 @@
+package com.iluwatar.eip.wiretap;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.builder.RouteBuilder;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.ConfigurableApplicationContext;
+
+/**
+ * In most integration cases there is a need to monitor the messages flowing through the system. It is usually achieved
+ * by intercepting the message and redirecting it to a different location like console, filesystem or the database.
+ * It is important that such functionality should not modify the original message and influence the processing path.
+ *
+ * <p>
+ * Wire Tap allows you to route messages to a separate location while they are being forwarded to the ultimate
+ * destination. It basically consumes messages of the input channel and publishes the unmodified message to both
+ * output channels.
+ * </p>
+ */
+@SpringBootApplication
+public class App {
+
+ /**
+ * Program entry point. It starts Spring Boot application and using Apache Camel it auto-configures routes.
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) throws Exception {
+ // Run Spring Boot application and obtain ApplicationContext
+ ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
+
+ // Get CamelContext from ApplicationContext
+ CamelContext camelContext = (CamelContext) context.getBean("camelContext");
+
+ // Add a new routes that will handle endpoints form WireTapRoute class.
+ camelContext.addRoutes(new RouteBuilder() {
+
+ @Override
+ public void configure() throws Exception {
+ from("{{endpoint}}").log("ENDPOINT: ${body}");
+ from("{{wireTapEndpoint}}").log("WIRETAPPED ENDPOINT: ${body}");
+ }
+
+ });
+
+ // Add producer that will send test message to an entry point in WireTapRoute
+ camelContext.createProducerTemplate().sendBody("{{entry}}", "Test message");
+
+ SpringApplication.exit(context);
+ }
+}
diff --git a/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java
new file mode 100644
index 000000000000..c744295ee52e
--- /dev/null
+++ b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java
@@ -0,0 +1,32 @@
+package com.iluwatar.eip.wiretap.routes;
+
+import org.apache.camel.builder.RouteBuilder;
+import org.springframework.stereotype.Component;
+
+/**
+ * Sample wire tap route definition.
+ *
+ * <p>
+ * It consumes messages out of the <i>direct:entry</i> entry point and forwards them to <i>direct:endpoint</i>.
+ * Wire Tap intercepts the message and sends it to <i>direct:wireTap</i>, which in turn forwards it to
+ * <i>direct:wireTapEndpoint</i>.
+ * </p>
+ *
+ * In this example input/output endpoints names are stored in <i>application.properties</i> file.
+ */
+@Component
+public class WireTapRoute extends RouteBuilder {
+
+ /**
+ * Configures the route
+ * @throws Exception in case of exception during configuration
+ */
+ @Override
+ public void configure() throws Exception {
+ // Main route
+ from("{{entry}}").wireTap("direct:wireTap").to("{{endpoint}}");
+
+ // Wire tap route
+ from("direct:wireTap").log("Message: ${body}").to("{{wireTapEndpoint}}");
+ }
+}
diff --git a/eip-wire-tap/src/main/resources/application.properties b/eip-wire-tap/src/main/resources/application.properties
new file mode 100644
index 000000000000..6dabe6ccc9ee
--- /dev/null
+++ b/eip-wire-tap/src/main/resources/application.properties
@@ -0,0 +1,3 @@
+entry=direct:entry
+endpoint=direct:endpoint
+wireTapEndpoint=direct:wireTapEndpoint
\ No newline at end of file
diff --git a/eip-wire-tap/src/test/resources/application-test.properties b/eip-wire-tap/src/test/resources/application-test.properties
new file mode 100644
index 000000000000..1719c8ca4ab4
--- /dev/null
+++ b/eip-wire-tap/src/test/resources/application-test.properties
@@ -0,0 +1,3 @@
+entry=direct:entry
+endpoint=mock:endpoint
+wireTapEndpoint=mock:wireTapEndpoint
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index ec39a6914125..774b140190c1 100644
--- a/pom.xml
+++ b/pom.xml
@@ -145,8 +145,9 @@
<module>cqrs</module>
<module>event-sourcing</module>
<module>data-transfer-object</module>
- <module>throttling</module>
+ <module>throttling</module>
<module>partial-response</module>
+ <module>eip-wire-tap</module>
</modules>
<dependencyManagement>
| diff --git a/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java
new file mode 100644
index 000000000000..25b9d8550f4c
--- /dev/null
+++ b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java
@@ -0,0 +1,15 @@
+package com.iluwatar.eip.wiretap;
+
+import org.junit.Test;
+
+/**
+ * Test for App class
+ */
+public class AppTest {
+
+ @Test
+ public void testMain() throws Exception {
+ String[] args = {};
+ App.main(args);
+ }
+}
diff --git a/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java
new file mode 100644
index 000000000000..a7b15f45eb93
--- /dev/null
+++ b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java
@@ -0,0 +1,62 @@
+package com.iluwatar.eip.wiretap.routes;
+
+import org.apache.camel.EndpointInject;
+import org.apache.camel.Message;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.test.SpringApplicationConfiguration;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Test class for <i>WireTapRoute</i>.
+ * <p>
+ * In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute
+ * original endpoint names to mocks.
+ * </p>
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@SpringApplicationConfiguration(classes = WireTapRouteTest.class)
+@ActiveProfiles("test")
+@EnableAutoConfiguration
+@ComponentScan
+public class WireTapRouteTest {
+
+ @EndpointInject(uri = "{{entry}}")
+ private ProducerTemplate entry;
+
+ @EndpointInject(uri = "{{endpoint}}")
+ private MockEndpoint endpoint;
+
+ @EndpointInject(uri = "{{wireTapEndpoint}}")
+ private MockEndpoint wireTapEndpoint;
+
+ /**
+ * Test if both endpoints receive exactly one message containing the same, unchanged body.
+ * @throws Exception in case of en exception during the test
+ */
+ @Test
+ @DirtiesContext
+ public void testWireTap() throws Exception {
+ entry.sendBody("TEST");
+
+ endpoint.expectedMessageCount(1);
+ wireTapEndpoint.expectedMessageCount(1);
+
+ endpoint.assertIsSatisfied();
+ wireTapEndpoint.assertIsSatisfied();
+
+ Message endpointIn = endpoint.getExchanges().get(0).getIn();
+ Message wireTapEndpointIn = wireTapEndpoint.getExchanges().get(0).getIn();
+
+ assertEquals("TEST", endpointIn.getBody());
+ assertEquals("TEST", wireTapEndpointIn.getBody());
+ }
+}
| train | train | "2017-10-12T16:13:57" | "2015-07-27T17:26:37Z" | iluwatar | train |
|
iluwatar/java-design-patterns/173_655 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/173 | iluwatar/java-design-patterns/655 | [
"timestamp(timedelta=18.0, similarity=0.861311107588729)"
] | 41710cbe9e3cb1f83e5f8eb9fce8bf2d4323aba0 | 168c9cf3a9054663ca4e17574b6dcdfdd172f5ba | [
"I can work on this one. \r\nSources:\r\n- http://www.enterpriseintegrationpatterns.com/patterns/messaging/Sequencer.html\r\n- http://camel.apache.org/splitter.html",
"Ok @codinghog "
] | [] | "2017-10-17T10:49:34Z" | [
"epic: pattern"
] | Splitter (EIP) | [
"pom.xml"
] | [
"eip-splitter/README.md",
"eip-splitter/pom.xml",
"eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java",
"eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java",
"eip-splitter/src/main/resources/application.properties",
"eip-splitter/src/test/resources/application-test.properties",
"pom.xml"
] | [
"eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java",
"eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java"
] | diff --git a/eip-splitter/README.md b/eip-splitter/README.md
new file mode 100644
index 000000000000..b5914750499e
--- /dev/null
+++ b/eip-splitter/README.md
@@ -0,0 +1,32 @@
+---
+layout: pattern
+title: EIP Splitter
+folder: eip-splitter
+permalink: /patterns/eip-splitter/
+categories: Enterprise integration
+tags:
+ - Java
+ - Difficulty-Intermittent
+ - Enterprise integration
+---
+
+## Intent
+It is very common in integration systems that incoming messages consists of many items bundled together. For example
+an invoice document contains multiple invoice lines describing transaction (quantity, name of provided
+service/sold goods, price etc.). Such bundled messages may not be accepted by other systems. This is where splitter
+pattern comes in handy. It will take the whole document, split it based on given criteria and send individual
+items to the endpoint.
+
+![alt text](./etc/sequencer.gif "Splitter")
+
+## Applicability
+Use the Splitter pattern when
+
+* You need to split received data into smaller pieces to process them individually
+* You need to control the size of data batches you are able to process
+
+## Credits
+
+* [Gregor Hohpe, Bobby Woolf - Enterprise Integration Patterns](http://www.enterpriseintegrationpatterns.com/patterns/messaging/Sequencer.html)
+* [Apache Camel - Documentation](http://camel.apache.org/splitter.html)
+
diff --git a/eip-splitter/pom.xml b/eip-splitter/pom.xml
new file mode 100644
index 000000000000..fb7e4ca9b15e
--- /dev/null
+++ b/eip-splitter/pom.xml
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ The MIT License
+ Copyright (c) 2014-2016 Ilkka Seppälä
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>eip-splitter</artifactId>
+ <parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>java-design-patterns</artifactId>
+ <version>1.18.0-SNAPSHOT</version>
+ </parent>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter-web</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-core</artifactId>
+ <version>${camel.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-spring-boot</artifactId>
+ <version>${camel.version}</version>
+ </dependency>
+
+ <!-- Testing -->
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter-test</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-test-spring</artifactId>
+ <version>${camel.version}</version>
+ </dependency>
+
+ </dependencies>
+</project>
\ No newline at end of file
diff --git a/eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java
new file mode 100644
index 000000000000..1f52e9569ce8
--- /dev/null
+++ b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java
@@ -0,0 +1,53 @@
+package com.iluwatar.eip.splitter;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.builder.RouteBuilder;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.ConfigurableApplicationContext;
+
+/**
+ * It is very common in integration systems that incoming messages consists of many items bundled together. For example
+ * an invoice document contains multiple invoice lines describing transaction (quantity, name of provided
+ * service/sold goods, price etc.). Such bundled messages may not be accepted by other systems. This is where splitter
+ * pattern comes in handy. It will take the whole document, split it based on given criteria and send individual
+ * items to the endpoint.
+ *
+ * <p>
+ * Splitter allows you to split messages based on defined criteria. It takes original message, process it and send
+ * multiple parts to the output channel. It is not defined if it should keep the order of items though.
+ * </p>
+ *
+ */
+@SpringBootApplication
+public class App {
+
+ /**
+ * Program entry point. It starts Spring Boot application and using Apache Camel it auto-configures routes.
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) throws Exception {
+ // Run Spring Boot application and obtain ApplicationContext
+ ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
+
+ // Get CamelContext from ApplicationContext
+ CamelContext camelContext = (CamelContext) context.getBean("camelContext");
+
+ // Add a new routes that will handle endpoints form SplitterRoute class.
+ camelContext.addRoutes(new RouteBuilder() {
+
+ @Override
+ public void configure() throws Exception {
+ from("{{endpoint}}").log("ENDPOINT: ${body}");
+ }
+
+ });
+
+ // Add producer that will send test message to an entry point in WireTapRoute
+ String[] stringArray = {"Test item #1", "Test item #2", "Test item #3"};
+ camelContext.createProducerTemplate().sendBody("{{entry}}", stringArray);
+
+ SpringApplication.exit(context);
+ }
+}
diff --git a/eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java
new file mode 100644
index 000000000000..064ad1f688b0
--- /dev/null
+++ b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java
@@ -0,0 +1,29 @@
+package com.iluwatar.eip.splitter.routes;
+
+import org.apache.camel.builder.RouteBuilder;
+import org.springframework.stereotype.Component;
+
+/**
+ * Sample splitter route definition.
+ *
+ * <p>
+ * It consumes messages out of the <i>direct:entry</i> entry point and forwards them to <i>direct:endpoint</i>.
+ * Route accepts messages having body of array or collection of objects. Splitter component split message body and
+ * forwards single objects to the endpoint.
+ * </p>
+ *
+ * In this example input/output endpoints names are stored in <i>application.properties</i> file.
+ */
+@Component
+public class SplitterRoute extends RouteBuilder {
+
+ /**
+ * Configures the route
+ * @throws Exception in case of exception during configuration
+ */
+ @Override
+ public void configure() throws Exception {
+ // Main route
+ from("{{entry}}").split().body().to("{{endpoint}}");
+ }
+}
diff --git a/eip-splitter/src/main/resources/application.properties b/eip-splitter/src/main/resources/application.properties
new file mode 100644
index 000000000000..cb879e6e270e
--- /dev/null
+++ b/eip-splitter/src/main/resources/application.properties
@@ -0,0 +1,2 @@
+entry=direct:entry
+endpoint=direct:endpoint
diff --git a/eip-splitter/src/test/resources/application-test.properties b/eip-splitter/src/test/resources/application-test.properties
new file mode 100644
index 000000000000..f657ea5a102c
--- /dev/null
+++ b/eip-splitter/src/test/resources/application-test.properties
@@ -0,0 +1,2 @@
+entry=direct:entry
+endpoint=mock:endpoint
diff --git a/pom.xml b/pom.xml
index 774b140190c1..0c03909de269 100644
--- a/pom.xml
+++ b/pom.xml
@@ -148,6 +148,7 @@
<module>throttling</module>
<module>partial-response</module>
<module>eip-wire-tap</module>
+ <module>eip-splitter</module>
</modules>
<dependencyManagement>
| diff --git a/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java
new file mode 100644
index 000000000000..bff2cf0b1c62
--- /dev/null
+++ b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java
@@ -0,0 +1,15 @@
+package com.iluwatar.eip.splitter;
+
+import org.junit.Test;
+
+/**
+ * Test for App class
+ */
+public class AppTest {
+
+ @Test
+ public void testMain() throws Exception {
+ String[] args = {};
+ App.main(args);
+ }
+}
diff --git a/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java
new file mode 100644
index 000000000000..78fc37d91403
--- /dev/null
+++ b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java
@@ -0,0 +1,53 @@
+package com.iluwatar.eip.splitter.routes;
+
+import org.apache.camel.EndpointInject;
+import org.apache.camel.Message;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.test.SpringApplicationConfiguration;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Test class for <i>SplitterRoute</i>.
+ * <p>
+ * In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute
+ * original endpoint names to mocks.
+ * </p>
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@SpringApplicationConfiguration(classes = SplitterRouteTest.class)
+@ActiveProfiles("test")
+@EnableAutoConfiguration
+@ComponentScan
+public class SplitterRouteTest {
+
+ @EndpointInject(uri = "{{entry}}")
+ private ProducerTemplate entry;
+
+ @EndpointInject(uri = "{{endpoint}}")
+ private MockEndpoint endpoint;
+
+ /**
+ * Test if endpoint receives three separate messages.
+ * @throws Exception in case of en exception during the test
+ */
+ @Test
+ @DirtiesContext
+ public void testSplitter() throws Exception {
+
+ // Three items in one entry message
+ entry.sendBody(new String[] {"TEST1", "TEST2", "TEST3"});
+
+ // Endpoint should have three different messages in the end order of the messages is not important
+ endpoint.expectedMessageCount(3);
+ endpoint.assertIsSatisfied();
+ }
+}
| train | train | "2017-10-16T07:24:46" | "2015-07-27T17:25:50Z" | iluwatar | train |
|
iluwatar/java-design-patterns/114_663 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/114 | iluwatar/java-design-patterns/663 | [
"timestamp(timedelta=29.0, similarity=0.8599817368193922)"
] | 5ed46c2c6481c322673c6eacab918302ca1d5f13 | 6339e26838e60ba83cbc275446c6f542216a1272 | [
"Since I've completed Splitter recently I can work now on this one.",
"Ok @codinghog "
] | [] | "2017-11-04T21:45:39Z" | [
"epic: pattern"
] | Aggregator (EIP) | [
"pom.xml"
] | [
"eip-aggregator/README.md",
"eip-aggregator/pom.xml",
"eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java",
"eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java",
"eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java",
"eip-aggregator/src/main/resources/application.properties",
"eip-aggregator/src/test/resources/application-test.properties",
"pom.xml"
] | [
"eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java",
"eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java",
"eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java"
] | diff --git a/eip-aggregator/README.md b/eip-aggregator/README.md
new file mode 100644
index 000000000000..ec8454f63cef
--- /dev/null
+++ b/eip-aggregator/README.md
@@ -0,0 +1,33 @@
+---
+layout: pattern
+title: EIP Aggregator
+folder: eip-aggregator
+permalink: /patterns/eip-aggregator/
+categories: Enterprise integration
+tags:
+ - Java
+ - Difficulty-Intermittent
+ - Enterprise integration
+---
+
+## Intent
+Sometimes in enterprise systems there is a need to group incoming data in order to process it as a whole. For example
+you may need to gather offers and after defined number of offers has been received you would like to choose the one with
+the best parameters.
+
+Aggregator allows you to merge messages based on defined criteria and parameters. It gathers original messages,
+applies aggregation strategy and upon fulfilling given criteria, releasing merged messages.
+
+![alt text](./etc/aggregator.gif "Splitter")
+
+## Applicability
+Use the Aggregator pattern when
+
+* You need to combine multiple incoming messages
+* You want to process grouped data
+
+## Credits
+
+* [Gregor Hohpe, Bobby Woolf - Enterprise Integration Patterns](http://www.enterpriseintegrationpatterns.com/patterns/messaging/Aggregator.html)
+* [Apache Camel - Documentation](http://camel.apache.org/aggregator2.html)
+
diff --git a/eip-aggregator/pom.xml b/eip-aggregator/pom.xml
new file mode 100644
index 000000000000..7467cb3a8069
--- /dev/null
+++ b/eip-aggregator/pom.xml
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ The MIT License
+ Copyright (c) 2014-2016 Ilkka Seppälä
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>eip-aggregator</artifactId>
+ <parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>java-design-patterns</artifactId>
+ <version>1.18.0-SNAPSHOT</version>
+ </parent>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter-web</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-core</artifactId>
+ <version>${camel.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-spring-boot</artifactId>
+ <version>${camel.version}</version>
+ </dependency>
+
+ <!-- Testing -->
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter-test</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-test-spring</artifactId>
+ <version>${camel.version}</version>
+ </dependency>
+
+ </dependencies>
+</project>
\ No newline at end of file
diff --git a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java
new file mode 100644
index 000000000000..fbff1a28a123
--- /dev/null
+++ b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java
@@ -0,0 +1,51 @@
+package com.iluwatar.eip.aggregator;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.builder.RouteBuilder;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.ConfigurableApplicationContext;
+
+/**
+ * Sometimes in enterprise systems there is a need to group incoming data in order to process it as a whole. For example
+ * you may need to gather offers and after defined number of offers has been received you would like to choose the one
+ * with the best parameters.
+ *
+ * <p>
+ * Aggregator allows you to merge messages based on defined criteria and parameters. It gathers original messages,
+ * applies aggregation strategy and upon fulfilling given criteria, releasing merged messages.
+ * </p>
+ *
+ */
+@SpringBootApplication
+public class App {
+
+ /**
+ * Program entry point. It starts Spring Boot application and using Apache Camel it auto-configures routes.
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) throws Exception {
+ // Run Spring Boot application and obtain ApplicationContext
+ ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
+
+ // Get CamelContext from ApplicationContext
+ CamelContext camelContext = (CamelContext) context.getBean("camelContext");
+
+ // Add a new routes that will handle endpoints form SplitterRoute class.
+ camelContext.addRoutes(new RouteBuilder() {
+
+ @Override
+ public void configure() throws Exception {
+ from("{{endpoint}}").log("ENDPOINT: ${body}");
+ }
+
+ });
+
+ // Add producer that will send test message to an entry point in WireTapRoute
+ String[] stringArray = {"Test item #1", "Test item #2", "Test item #3"};
+ camelContext.createProducerTemplate().sendBody("{{entry}}", stringArray);
+
+ SpringApplication.exit(context);
+ }
+}
diff --git a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java
new file mode 100644
index 000000000000..5aba0ef27da7
--- /dev/null
+++ b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java
@@ -0,0 +1,38 @@
+package com.iluwatar.eip.aggregator.routes;
+
+import org.apache.camel.builder.RouteBuilder;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/**
+ * Sample aggregator route definition.
+ *
+ * <p>
+ * It consumes messages out of the <i>direct:entry</i> entry point and forwards them to <i>direct:endpoint</i>.
+ * Route accepts messages containing String as a body, it aggregates the messages based on the settings and forwards
+ * them as CSV to the output chanel.
+ *
+ * Settings for the aggregation are: aggregate until 3 messages are bundled or wait 2000ms before sending bundled
+ * messages further.
+ * </p>
+ *
+ * In this example input/output endpoints names are stored in <i>application.properties</i> file.
+ */
+@Component
+public class AggregatorRoute extends RouteBuilder {
+
+ @Autowired
+ private MessageAggregationStrategy aggregator;
+
+ /**
+ * Configures the route
+ * @throws Exception in case of exception during configuration
+ */
+ @Override
+ public void configure() throws Exception {
+ // Main route
+ from("{{entry}}").aggregate(constant(true), aggregator)
+ .completionSize(3).completionInterval(2000)
+ .to("{{endpoint}}");
+ }
+}
diff --git a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java
new file mode 100644
index 000000000000..a2c90c60921a
--- /dev/null
+++ b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java
@@ -0,0 +1,27 @@
+package com.iluwatar.eip.aggregator.routes;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.processor.aggregate.AggregationStrategy;
+import org.springframework.stereotype.Component;
+
+/**
+ * Aggregation strategy joining bodies of messages. If message is first one <i>oldMessage</i> is null. All changes are
+ * made on IN messages.
+ */
+@Component
+public class MessageAggregationStrategy implements AggregationStrategy {
+
+ @Override
+ public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
+ if (oldExchange == null) {
+ return newExchange;
+ }
+
+ String in1 = (String) oldExchange.getIn().getBody();
+ String in2 = (String) newExchange.getIn().getBody();
+
+ oldExchange.getIn().setBody(in1 + ";" + in2);
+
+ return oldExchange;
+ }
+}
diff --git a/eip-aggregator/src/main/resources/application.properties b/eip-aggregator/src/main/resources/application.properties
new file mode 100644
index 000000000000..cb879e6e270e
--- /dev/null
+++ b/eip-aggregator/src/main/resources/application.properties
@@ -0,0 +1,2 @@
+entry=direct:entry
+endpoint=direct:endpoint
diff --git a/eip-aggregator/src/test/resources/application-test.properties b/eip-aggregator/src/test/resources/application-test.properties
new file mode 100644
index 000000000000..f657ea5a102c
--- /dev/null
+++ b/eip-aggregator/src/test/resources/application-test.properties
@@ -0,0 +1,2 @@
+entry=direct:entry
+endpoint=mock:endpoint
diff --git a/pom.xml b/pom.xml
index 0c03909de269..2d84d50643bb 100644
--- a/pom.xml
+++ b/pom.xml
@@ -149,6 +149,7 @@
<module>partial-response</module>
<module>eip-wire-tap</module>
<module>eip-splitter</module>
+ <module>eip-aggregator</module>
</modules>
<dependencyManagement>
| diff --git a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java
new file mode 100644
index 000000000000..5eee0986f02f
--- /dev/null
+++ b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java
@@ -0,0 +1,15 @@
+package com.iluwatar.eip.aggregator;
+
+import org.junit.Test;
+
+/**
+ * Test for App class
+ */
+public class AppTest {
+
+ @Test
+ public void testMain() throws Exception {
+ String[] args = {};
+ App.main(args);
+ }
+}
diff --git a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java
new file mode 100644
index 000000000000..449c4aad0f01
--- /dev/null
+++ b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java
@@ -0,0 +1,62 @@
+package com.iluwatar.eip.aggregator.routes;
+
+import org.apache.camel.EndpointInject;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.test.SpringApplicationConfiguration;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Test class for <i>AggregatorRoute</i>.
+ * <p>
+ * In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute
+ * original endpoint names to mocks.
+ * </p>
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@SpringApplicationConfiguration(classes = AggregatorRouteTest.class)
+@ActiveProfiles("test")
+@EnableAutoConfiguration
+@ComponentScan
+public class AggregatorRouteTest {
+
+ @EndpointInject(uri = "{{entry}}")
+ private ProducerTemplate entry;
+
+ @EndpointInject(uri = "{{endpoint}}")
+ private MockEndpoint endpoint;
+
+ /**
+ * Test if endpoint receives three separate messages.
+ * @throws Exception in case of en exception during the test
+ */
+ @Test
+ @DirtiesContext
+ public void testSplitter() throws Exception {
+
+ // Three items in one entry message
+ entry.sendBody("TEST1");
+ entry.sendBody("TEST2");
+ entry.sendBody("TEST3");
+ entry.sendBody("TEST4");
+ entry.sendBody("TEST5");
+
+ // Endpoint should have three different messages in the end order of the messages is not important
+ endpoint.expectedMessageCount(2);
+ endpoint.assertIsSatisfied();
+
+ String body = (String) endpoint.getReceivedExchanges().get(0).getIn().getBody();
+ assertEquals(3, body.split(";").length);
+
+ String body2 = (String) endpoint.getReceivedExchanges().get(1).getIn().getBody();
+ assertEquals(2, body2.split(";").length);
+ }
+}
diff --git a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java
new file mode 100644
index 000000000000..f4685e334851
--- /dev/null
+++ b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java
@@ -0,0 +1,42 @@
+package com.iluwatar.eip.aggregator.routes;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.impl.DefaultExchange;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Tests MessageAggregationStrategy
+ */
+public class MessageAggregationStrategyTest {
+
+ @Test
+ public void testAggregate() {
+ MessageAggregationStrategy mas = new MessageAggregationStrategy();
+ Exchange oldExchange = new DefaultExchange((CamelContext) null);
+ oldExchange.getIn().setBody("TEST1");
+
+ Exchange newExchange = new DefaultExchange((CamelContext) null);
+ newExchange.getIn().setBody("TEST2");
+
+ Exchange output = mas.aggregate(oldExchange, newExchange);
+ String outputBody = (String) output.getIn().getBody();
+ assertEquals("TEST1;TEST2", outputBody);
+ }
+
+ @Test
+ public void testAggregateOldNull() {
+ MessageAggregationStrategy mas = new MessageAggregationStrategy();
+
+ Exchange newExchange = new DefaultExchange((CamelContext) null);
+ newExchange.getIn().setBody("TEST2");
+
+ Exchange output = mas.aggregate(null, newExchange);
+ String outputBody = (String) output.getIn().getBody();
+
+ assertEquals(newExchange, output);
+ assertEquals("TEST2", outputBody);
+ }
+}
| train | train | "2017-10-22T21:21:54" | "2015-07-27T17:03:24Z" | iluwatar | train |
|
iluwatar/java-design-patterns/666_668 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/666 | iluwatar/java-design-patterns/668 | [
"keyword_pr_to_issue"
] | 390c33e36e82b558e8cab6028d96e49c0a20da9f | d26f2620ec1714193243deb3ed1dbe843c7d9b46 | [
"@Krandelbord You are correct. It is not thread safe as field is being shared without synchronization. Can you raise a PR with the fix?",
"Perhaps change to atomicInteger?!",
"If I use AtomicInteger then I have to make reading, comparing, incrementing, and setting to zero as one atomic operation.\r\nIt will end up in something like that\r\n```\r\nprivate static AtomicInteger lastServedId = new AtomicInteger();\r\n public void serverRequest(Request request) {\r\n int serverIdToUse = lastServedId.getAndUpdate((lastServedId) -> lastServedId < servers.size() - 1 ? ++lastServedId : 0);\r\n Server server = servers.get(serverIdToUse);\r\n server.serve(request);\r\n }\r\n```\r\nDoesn't look good. So I decided to make method synchronized.",
"Is Volatile a Solution?!",
"No, ```volatile``` is not suitable for cases where you want to read-update-write as an atomic operation; access to a volatile variable never has the potential to block: you're only ever doing a simple read or write ([source](https://www.javamex.com/tutorials/synchronization_volatile.shtml)).\r\n\r\nSince we're doing changes in this class, could you also fix the misleading variable name ```serverIdToUse```: the value has nothing to do with the actual identifier of the server, it is just the index of the next server to use from ```List<Server> servers```"
] | [] | "2017-11-19T11:06:56Z" | [
"type: bug",
"info: help wanted"
] | Is it threadsafe ? | Seems like lastServedId field from LoadBlanacer.class is shared among all instances.
I think this is not threadsafe and will crash when mutiple threads will try to increment it.
https://github.com/iluwatar/java-design-patterns/blob/390c33e36e82b558e8cab6028d96e49c0a20da9f/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java#L39 | [
"monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java"
] | [
"monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java"
] | [] | diff --git a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
index e440dfba22d6..b280de76702d 100644
--- a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
+++ b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
@@ -35,10 +35,10 @@
public class LoadBalancer {
private static List<Server> servers = new ArrayList<>();
- private static int id;
private static int lastServedId;
static {
+ int id = 0;
servers.add(new Server("localhost", 8081, ++id));
servers.add(new Server("localhost", 8080, ++id));
servers.add(new Server("localhost", 8082, ++id));
@@ -67,14 +67,12 @@ public static int getLastServedId() {
/**
* Handle request
*/
- public void serverRequest(Request request) {
+ public synchronized void serverRequest(Request request) {
if (lastServedId >= servers.size()) {
lastServedId = 0;
}
Server server = servers.get(lastServedId++);
server.serve(request);
}
-
-
-
+
}
| null | train | train | "2017-11-05T08:59:14" | "2017-11-11T09:16:17Z" | Krandelbord | train |
iluwatar/java-design-patterns/672_682 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/672 | iluwatar/java-design-patterns/682 | [
"timestamp(timedelta=0.0, similarity=0.8457034043520804)"
] | 6c4de3bcef978bbdec4e7bbb07e6f67d412385c1 | 6b4ae0d0b1d88b344a59bd3098ddb4b79acd0786 | [
"I have no previous experience in the \"CII Best Practices Badge Program\". I see they have some [criteria](https://github.com/coreinfrastructure/best-practices-badge/blob/master/doc/criteria.md) that has to be met for a project to \"self-certify\". I briefly looked at it and it seems that we are already passing all their tests. So if you @zafarella or somebody else want to work on this and get us the badge I'm ok with it."
] | [] | "2017-12-25T13:53:59Z" | [
"info: help wanted",
"type: enhancement"
] | Consider adding another badge | @iluwatar as this project is open-source, I was thinking why not add https://bestpractices.coreinfrastructure.org
as a badge. It will be like cool both standardization + learning for readers.
You have to create the project there and add the badge.
Others probably also can contribute whenever you create it.
> Just thought, please ignore if not relevant | [
"README.md"
] | [
"README.md"
] | [] | diff --git a/README.md b/README.md
index 6eed9561b551..d7f2f154c781 100644
--- a/README.md
+++ b/README.md
@@ -8,6 +8,7 @@
[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md)
[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Quality Gate](https://sonarqube.com/api/badges/gate?key=com.iluwatar%3Ajava-design-patterns)](https://sonarqube.com/dashboard/index/com.iluwatar%3Ajava-design-patterns)
+[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/1503/badge)](https://bestpractices.coreinfrastructure.org/projects/1503)
# Introduction
| null | test | train | "2017-12-25T10:30:24" | "2017-11-25T05:10:21Z" | zafarella | train |
iluwatar/java-design-patterns/675_688 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/675 | iluwatar/java-design-patterns/688 | [
"timestamp(timedelta=79.0, similarity=0.9063894209171383)"
] | 082452947186a66d61fe1233264ace92d2722067 | e8496c5d48699e0fce579cc0b1c721240ab65fb8 | [
"Link to the diagram, please?",
"https://github.com/iluwatar/java-design-patterns/blob/master/event-asynchronous/etc/event-asynchronous.png",
"May I take this issue?",
"I am a bit confused. What should the .png look like?",
"I think the method name has changed. `ThreadCompleteListener#notifyOfThreadComplete` no longer exists. The current version of the class has a different method, see here https://github.com/iluwatar/java-design-patterns/blob/master/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java. So you should just update the class diagram. We have used http://www.objectaid.com/ to generate the class diagrams.",
"Go ahead @ThatGuyWithTheHat, just ask if you need more help."
] | [] | "2017-12-30T07:47:32Z" | [
"type: bug",
"info: good first issue"
] | event-asynchronous pattern class diagram is error | The ThreadCompleteListener can't find “notifyOfThreadComplete” method | [
"event-asynchronous/etc/event-asynchronous.ucls"
] | [
"event-asynchronous/etc/event-asynchronous.ucls"
] | [] | diff --git a/event-asynchronous/etc/event-asynchronous.ucls b/event-asynchronous/etc/event-asynchronous.ucls
index df09fc28d955..1327b7104459 100644
--- a/event-asynchronous/etc/event-asynchronous.ucls
+++ b/event-asynchronous/etc/event-asynchronous.ucls
@@ -1,63 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
-<class-diagram version="1.1.10" icons="true" automaticImage="PNG" always-add-relationships="false"
- generalizations="true" realizations="true" associations="true" dependencies="false" nesting-relationships="true"
- router="FAN">
- <class id="1" language="java" name="com.iluwatar.event.asynchronous.App" project="event-asynchronous"
- file="/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java" binary="false"
- corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="629" y="221"/>
+<class-diagram version="1.2.2" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
+ realizations="true" associations="true" dependencies="false" nesting-relationships="true" router="FAN">
+ <interface id="1" language="java" name="com.iluwatar.event.asynchronous.IEvent" project="java-design-patterns"
+ file="/java-design-patterns/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/IEvent.java"
+ binary="false" corner="BOTTOM_RIGHT">
+ <position height="117" width="151" x="42" y="15"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
- <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
- </class>
- <class id="2" language="java" name="com.iluwatar.event.asynchronous.Event" project="event-asynchronous"
- file="/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java" binary="false"
- corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="195" y="475"/>
+ </interface>
+ <interface id="2" language="java" name="com.iluwatar.event.asynchronous.ThreadCompleteListener"
+ project="java-design-patterns"
+ file="/java-design-patterns/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java"
+ binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="326" y="79"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
- <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
- </class>
- <class id="3" language="java" name="com.iluwatar.event.asynchronous.EventManager" project="event-asynchronous"
- file="/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java" binary="false"
- corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="575" y="475"/>
+ </interface>
+ <class id="3" language="java" name="com.iluwatar.event.asynchronous.App" project="java-design-patterns"
+ file="/java-design-patterns/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java"
+ binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="554" y="119"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
- <attributes public="false" package="false" protected="false" private="false" static="true"/>
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
- <interface id="4" language="java" name="com.iluwatar.event.asynchronous.IEvent" project="event-asynchronous"
- file="/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/IEvent.java" binary="false"
- corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="196" y="197"/>
+ <class id="4" language="java" name="com.iluwatar.event.asynchronous.EventAsynchronousTest"
+ project="java-design-patterns"
+ file="/java-design-patterns/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java"
+ binary="false" corner="BOTTOM_RIGHT">
+ <position height="207" width="234" x="669" y="16"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
- </interface>
- <interface id="5" language="java" name="com.iluwatar.event.asynchronous.ThreadCompleteListener"
- project="event-asynchronous"
- file="/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java" binary="false"
- corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="396" y="229"/>
+ </class>
+ <class id="5" language="java" name="com.iluwatar.event.asynchronous.Event" project="java-design-patterns"
+ file="/java-design-patterns/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java"
+ binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="141" y="441"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
- </interface>
- <class id="6" language="java" name="com.iluwatar.event.asynchronous.EventAsynchronousTest"
- project="event-asynchronous"
- file="/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java" binary="false"
- corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="924" y="220"/>
+ </class>
+ <class id="6" language="java" name="com.iluwatar.event.asynchronous.EventManager" project="java-design-patterns"
+ file="/java-design-patterns/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java"
+ binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="431" y="439"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
@@ -65,49 +64,36 @@
</display>
</class>
<association id="7">
- <end type="SOURCE" refId="6" navigable="false">
- <attribute id="8" name="app">
- <position height="0" width="0" x="0" y="0"/>
- </attribute>
- <multiplicity id="9" minimum="0" maximum="1">
- <position height="16" width="23" x="714" y="226"/>
- </multiplicity>
+ <end type="SOURCE" refId="5" navigable="false">
+ <attribute id="8" name="eventListener"/>
+ <multiplicity id="9" minimum="0" maximum="1"/>
</end>
- <end type="TARGET" refId="1" navigable="true"/>
+ <end type="TARGET" refId="2" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
- <association id="10">
- <end type="SOURCE" refId="2" navigable="false">
- <attribute id="11" name="eventListener">
- <position height="18" width="74" x="250" y="287"/>
- </attribute>
- <multiplicity id="12" minimum="0" maximum="1">
- <position height="0" width="0" x="0" y="0"/>
- </multiplicity>
+ <realization id="10">
+ <end type="SOURCE" refId="5"/>
+ <end type="TARGET" refId="1"/>
+ </realization>
+ <association id="11">
+ <end type="SOURCE" refId="4" navigable="false">
+ <attribute id="12" name="app"/>
+ <multiplicity id="13" minimum="0" maximum="1"/>
</end>
- <end type="TARGET" refId="5" navigable="true"/>
+ <end type="TARGET" refId="3" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
- <association id="13">
- <bendpoint x="433" y="475"/>
- <end type="SOURCE" refId="3" navigable="false">
- <attribute id="14" name="eventPool">
- <position height="0" width="0" x="0" y="0"/>
- </attribute>
- <multiplicity id="15" minimum="0" maximum="2147483647">
- <position height="0" width="0" x="0" y="0"/>
- </multiplicity>
+ <association id="14">
+ <end type="SOURCE" refId="6" navigable="false">
+ <attribute id="15" name="eventPool"/>
+ <multiplicity id="16" minimum="0" maximum="2147483647"/>
</end>
- <end type="TARGET" refId="2" navigable="true"/>
+ <end type="TARGET" refId="5" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
- <realization id="16">
- <end type="SOURCE" refId="2"/>
- <end type="TARGET" refId="4"/>
- </realization>
<realization id="17">
- <end type="SOURCE" refId="3"/>
- <end type="TARGET" refId="5"/>
+ <end type="SOURCE" refId="6"/>
+ <end type="TARGET" refId="2"/>
</realization>
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
| null | train | train | "2017-12-30T08:53:28" | "2017-11-27T06:45:44Z" | harley-byte | train |
iluwatar/java-design-patterns/681_693 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/681 | iluwatar/java-design-patterns/693 | [
"keyword_pr_to_issue"
] | dea2316f1fb535a7e1038158d54f58939fdd4040 | 09c0891948c221924a9280c19116c4c18611cb71 | [
"@iluwatar if no one help on this I would like to fix this one",
"Ok @jujis008 "
] | [] | "2018-01-02T10:31:52Z" | [
"type: bug",
"info: good first issue"
] | AbstractDocument: price or partner? | On the diagram of `AbstractDocument`, `HasPrice.getPartner()` should be `HasPrice.getPrice()`. | [
"abstract-document/README.md",
"abstract-document/etc/abstract-document-base.ucls",
"abstract-document/etc/abstract-document.ucls"
] | [
"abstract-document/README.md",
"abstract-document/etc/abstract-document.ucls"
] | [] | diff --git a/abstract-document/README.md b/abstract-document/README.md
index bf28ff999bf5..2adb3732b822 100644
--- a/abstract-document/README.md
+++ b/abstract-document/README.md
@@ -12,8 +12,6 @@ tags:
## Intent
Achieve flexibility of untyped languages and keep the type-safety
-![alt text](./etc/abstract-document-base.png "Abstract Document Base")
-
![alt text](./etc/abstract-document.png "Abstract Document Traits and Domain")
diff --git a/abstract-document/etc/abstract-document-base.ucls b/abstract-document/etc/abstract-document-base.ucls
deleted file mode 100644
index bfe927ed9357..000000000000
--- a/abstract-document/etc/abstract-document-base.ucls
+++ /dev/null
@@ -1,58 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<class-diagram version="1.1.9" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
- realizations="true" associations="true" dependencies="false" nesting-relationships="true" router="FAN">
- <interface id="1" language="java" name="com.iluwatar.abstractdocument.Document" project="design-patterns"
- file="/design-patterns/src/com/iluwatar/abstractdocument/Document.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="249" y="405"/>
- <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
- sort-features="false" accessors="true" visibility="true">
- <attributes public="true" package="true" protected="true" private="true" static="true"/>
- <operations public="true" package="true" protected="true" private="true" static="true"/>
- </display>
- </interface>
- <class id="2" language="java" name="com.iluwatar.abstractdocument.AbstractDocument" project="design-patterns"
- file="/design-patterns/src/com/iluwatar/abstractdocument/AbstractDocument.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="250" y="237"/>
- <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
- sort-features="false" accessors="true" visibility="true">
- <attributes public="true" package="true" protected="true" private="true" static="true"/>
- <operations public="true" package="true" protected="true" private="true" static="true"/>
- </display>
- </class>
- <class id="3" language="java" name="com.iluwatar.abstractdocument.domain.Car" project="design-patterns"
- file="/design-patterns/src/com/iluwatar/abstractdocument/domain/Car.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="108" y="75"/>
- <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
- sort-features="false" accessors="true" visibility="true">
- <attributes public="true" package="true" protected="true" private="true" static="true"/>
- <operations public="true" package="true" protected="true" private="true" static="true"/>
- </display>
- </class>
- <class id="4" language="java" name="com.iluwatar.abstractdocument.domain.Part" project="design-patterns"
- file="/design-patterns/src/com/iluwatar/abstractdocument/domain/Part.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="400" y="76"/>
- <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
- sort-features="false" accessors="true" visibility="true">
- <attributes public="true" package="true" protected="true" private="true" static="true"/>
- <operations public="true" package="true" protected="true" private="true" static="true"/>
- </display>
- </class>
- <generalization id="5">
- <end type="SOURCE" refId="4"/>
- <end type="TARGET" refId="2"/>
- </generalization>
- <realization id="6">
- <end type="SOURCE" refId="2"/>
- <end type="TARGET" refId="1"/>
- </realization>
- <generalization id="7">
- <end type="SOURCE" refId="3"/>
- <end type="TARGET" refId="2"/>
- </generalization>
- <classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
- sort-features="false" accessors="true" visibility="true">
- <attributes public="true" package="true" protected="true" private="true" static="true"/>
- <operations public="true" package="true" protected="true" private="true" static="true"/>
- </classifier-display>
- <association-display labels="true" multiplicity="true"/>
-</class-diagram>
\ No newline at end of file
diff --git a/abstract-document/etc/abstract-document.ucls b/abstract-document/etc/abstract-document.ucls
index ad97457fdfc2..f555394d04c2 100644
--- a/abstract-document/etc/abstract-document.ucls
+++ b/abstract-document/etc/abstract-document.ucls
@@ -1,91 +1,137 @@
<?xml version="1.0" encoding="UTF-8"?>
-<class-diagram version="1.1.9" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
- realizations="true" associations="true" dependencies="false" nesting-relationships="true" router="FAN">
- <interface id="1" language="java" name="com.iluwatar.abstractdocument.Document" project="design-patterns"
- file="/design-patterns/src/com/iluwatar/abstractdocument/Document.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="-1" width="-1" x="341" y="376"/>
+<class-diagram version="1.2.2" icons="true" always-add-relationships="false" generalizations="true" realizations="true"
+ associations="true" dependencies="false" nesting-relationships="true" router="FAN">
+ <class id="1" language="java" name="com.iluwatar.abstractdocument.AbstractDocument" project="abstract-document"
+ file="/abstract-document/src/main/java/com/iluwatar/abstractdocument/AbstractDocument.java" binary="false"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="659" y="286"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
- </interface>
- <interface id="2" language="java" name="com.iluwatar.abstractdocument.domain.HasModel" project="design-patterns"
- file="/design-patterns/src/com/iluwatar/abstractdocument/domain/HasModel.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="81" width="173" x="41" y="194"/>
+ </class>
+ <interface id="2" language="java" name="com.iluwatar.abstractdocument.Document" project="abstract-document"
+ file="/abstract-document/src/main/java/com/iluwatar/abstractdocument/Document.java" binary="false"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="562" y="27"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</interface>
- <interface id="3" language="java" name="com.iluwatar.abstractdocument.domain.HasPrice" project="design-patterns"
- file="/design-patterns/src/com/iluwatar/abstractdocument/domain/HasPrice.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="81" width="175" x="254" y="194"/>
+ <class id="3" language="java" name="com.iluwatar.abstractdocument.domain.Car" project="abstract-document"
+ file="/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Car.java" binary="false"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="348" y="737"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <class id="4" language="java" name="com.iluwatar.abstractdocument.domain.Part" project="abstract-document"
+ file="/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Part.java" binary="false"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="760" y="746"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <interface id="5" language="java" name="com.iluwatar.abstractdocument.domain.HasModel" project="abstract-document"
+ file="/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasModel.java" binary="false"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="355" y="297"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</interface>
- <interface id="4" language="java" name="com.iluwatar.abstractdocument.domain.HasParts" project="design-patterns"
- file="/design-patterns/src/com/iluwatar/abstractdocument/domain/HasParts.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="81" width="173" x="469" y="194"/>
+ <interface id="6" language="java" name="com.iluwatar.abstractdocument.domain.HasParts" project="abstract-document"
+ file="/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasParts.java" binary="false"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="109" y="297"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</interface>
- <class id="5" language="java" name="com.iluwatar.abstractdocument.domain.Car" project="design-patterns"
- file="/design-patterns/src/com/iluwatar/abstractdocument/domain/Car.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="99" width="173" x="254" y="37"/>
+ <interface id="7" language="java" name="com.iluwatar.abstractdocument.domain.HasPrice" project="abstract-document"
+ file="/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasPrice.java" binary="false"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="1008" y="283"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
- </class>
- <class id="6" language="java" name="com.iluwatar.abstractdocument.domain.Part" project="design-patterns"
- file="/design-patterns/src/com/iluwatar/abstractdocument/domain/Part.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="99" width="173" x="41" y="37"/>
+ </interface>
+ <interface id="8" language="java" name="com.iluwatar.abstractdocument.domain.HasType" project="abstract-document"
+ file="/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasType.java" binary="false"
+ corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="1257" y="277"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
- </class>
- <realization id="7">
- <end type="SOURCE" refId="5"/>
- <end type="TARGET" refId="2"/>
+ </interface>
+ <realization id="9">
+ <end type="SOURCE" refId="4"/>
+ <end type="TARGET" refId="8"/>
+ </realization>
+ <realization id="10">
+ <end type="SOURCE" refId="3"/>
+ <end type="TARGET" refId="7"/>
</realization>
- <realization id="8">
+ <generalization id="11">
<end type="SOURCE" refId="6"/>
<end type="TARGET" refId="2"/>
- </realization>
- <generalization id="9">
- <end type="SOURCE" refId="2"/>
- <end type="TARGET" refId="1"/>
</generalization>
- <realization id="10">
- <end type="SOURCE" refId="5"/>
- <end type="TARGET" refId="3"/>
+ <realization id="12">
+ <end type="SOURCE" refId="4"/>
+ <end type="TARGET" refId="5"/>
</realization>
- <realization id="11">
- <end type="SOURCE" refId="5"/>
- <end type="TARGET" refId="4"/>
+ <realization id="13">
+ <end type="SOURCE" refId="4"/>
+ <end type="TARGET" refId="7"/>
</realization>
- <generalization id="12">
+ <generalization id="14">
<end type="SOURCE" refId="3"/>
<end type="TARGET" refId="1"/>
</generalization>
- <generalization id="13">
+ <realization id="15">
+ <end type="SOURCE" refId="3"/>
+ <end type="TARGET" refId="6"/>
+ </realization>
+ <generalization id="16">
+ <end type="SOURCE" refId="8"/>
+ <end type="TARGET" refId="2"/>
+ </generalization>
+ <generalization id="17">
+ <end type="SOURCE" refId="7"/>
+ <end type="TARGET" refId="2"/>
+ </generalization>
+ <realization id="18">
+ <end type="SOURCE" refId="3"/>
+ <end type="TARGET" refId="5"/>
+ </realization>
+ <generalization id="19">
<end type="SOURCE" refId="4"/>
<end type="TARGET" refId="1"/>
</generalization>
- <realization id="14">
- <end type="SOURCE" refId="6"/>
- <end type="TARGET" refId="3"/>
+ <generalization id="20">
+ <end type="SOURCE" refId="5"/>
+ <end type="TARGET" refId="2"/>
+ </generalization>
+ <realization id="21">
+ <end type="SOURCE" refId="1"/>
+ <end type="TARGET" refId="2"/>
</realization>
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
| null | train | train | "2018-01-01T15:58:29" | "2017-12-16T14:38:45Z" | davidsusu | train |
iluwatar/java-design-patterns/694_695 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/694 | iluwatar/java-design-patterns/695 | [
"timestamp(timedelta=128.0, similarity=0.92367663716969)"
] | f87754917c5c5b8cf079c35de0aa98db039a7a28 | 288f1e8c7e02032dba10525e8f48ae9df1ec9a3e | [
"@iluwatar I'll take this if no one else has",
"@james-a-roland there is a pull request about this, see https://github.com/iluwatar/java-design-patterns/pull/695. But I have a feeling it does not solve all redundant calls to `super()`. Either work with @jonatasemidio by reviewing the PR or create your own PR that resolves all the cases. I will assign the issue to you.",
"Hi @james-a-roland and @iluwatar,\r\nDo you know what type of unit test can I include to check this other cases? ",
"I would probably just `grep` through all `super` occurrences",
"@iluwatar - Pull request can be found here https://github.com/iluwatar/java-design-patterns/pull/697",
"@iluwatar, another consideration... I know that grep can find all occurrences, but we might have some samples that super() calls some father's constructors.\r\n\r\nHi @james-a-roland, How did you checked all super() occurrences?",
"I used `grep 'super()'`",
"Same as @olcbean - any calls to super() called from a custom constructor were deleted. Since all objects are POJO's, I think this is a safe operation.",
"So... In this case, we can use #697 instead of #695 \r\n "
] | [] | "2018-01-05T10:40:46Z" | [
"type: enhancement",
"info: good first issue"
] | Remove redundant explicit super() constructor calls | The super() calls (taking no arguments) are inserted during compile time, so just make the code more verbose than required.
One example is found in the [HeroStat ](https://github.com/iluwatar/java-design-patterns/blob/master/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java#L40) class. | [
"value-object/src/main/java/com/iluwatar/value/object/HeroStat.java"
] | [
"value-object/src/main/java/com/iluwatar/value/object/HeroStat.java"
] | [] | diff --git a/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java b/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java
index ff85e0e934dc..0274bc47f394 100644
--- a/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java
+++ b/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java
@@ -37,7 +37,6 @@ public class HeroStat {
// All constructors must be private.
private HeroStat(int strength, int intelligence, int luck) {
- super();
this.strength = strength;
this.intelligence = intelligence;
this.luck = luck;
| null | train | train | "2018-01-02T18:29:14" | "2018-01-05T02:23:51Z" | dylanwatsonsoftware | train |
iluwatar/java-design-patterns/677_696 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/677 | iluwatar/java-design-patterns/696 | [
"timestamp(timedelta=82.0, similarity=0.8878464269645263)"
] | 09c0891948c221924a9280c19116c4c18611cb71 | 7fef5e4cd5862338557c1d90fdc6de445ebe631e | [
"Can you please provide links to the pattern?",
"Shure.\r\nWiki - https://en.wikipedia.org/wiki/Trampoline_(computing) (high-level programming)\r\ngood example - https://medium.com/@johnmcclean/trampolining-a-practical-guide-for-awesome-java-developers-4b657d9c3076\r\nstackoverflow - https://stackoverflow.com/questions/189725/what-is-a-trampoline-function\r\n\r\n2017-12-11 21:42 GMT+03:00 Ilkka Seppälä <notifications@github.com<mailto:notifications@github.com>>:\r\n\r\nCan you please provide links to the pattern?\r\n\r\n—\r\nYou are receiving this because you authored the thread.\r\nReply to this email directly, view it on GitHub<https://github.com/iluwatar/java-design-patterns/issues/677#issuecomment-350817317>, or mute the thread<https://github.com/notifications/unsubscribe-auth/Acc9YOi8BH4szX45S1GawlN7Dx8GIWBQks5s_XeqgaJpZM4Q9F1t>.\r\n\r\n",
"The links look good to me. Who would like to implement?",
"I can do it if you don't mind.\r\nI am going to do it in 1-2 weeks.",
"Ok @besok ",
"ok."
] | [
"Would it be possible to explain the pattern shortly in `Explanation` section? See https://github.com/iluwatar/java-design-patterns/wiki/02.-Pattern-template and some other patterns like http://java-design-patterns.com/patterns/decorator/ for examples.",
"Use `Tutorials` section for examples. Pattern descriptions can be in `Credits`.",
"Using Lombok should be project level decision. We haven't used it elsewhere so please do not take it into use in one pattern.",
"Please refer to methods properly in Javadoc e.g. {@link package.class#member label}. What is cyclops-react?",
"Please prefer \\<p\\> tag in Javadoc. See other patterns for examples. Please describe what the example does and how it implements the pattern.",
"Please use descriptive test method name? What does it test?",
"Done. Changed to testTrampolineWithFactorialFunction ",
"done",
"cyclops-react is a library for additions java8 streams.\r\ndone.",
"done",
"i added section,",
"changed it."
] | "2018-01-08T11:48:52Z" | [
"epic: pattern"
] | Pattern : trampoline. Is it needed? | Hi!
I have not found a pattern Trampoline in the list.
I want to discuss adding this pattern to list.
Will be it right?
I can do it if it is possible. | [
"pom.xml"
] | [
"pom.xml",
"trampoline/.gitignore",
"trampoline/README.md",
"trampoline/pom.xml",
"trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java",
"trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java"
] | [
"trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java"
] | diff --git a/pom.xml b/pom.xml
index 66c5fa850c83..7e669d39669c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -147,13 +147,13 @@
<module>event-sourcing</module>
<module>data-transfer-object</module>
<module>throttling</module>
-
<module>unit-of-work</module>
<module>partial-response</module>
<module>eip-wire-tap</module>
<module>eip-splitter</module>
<module>eip-aggregator</module>
<module>retry</module>
+ <module>trampoline</module>
</modules>
<repositories>
diff --git a/trampoline/.gitignore b/trampoline/.gitignore
new file mode 100644
index 000000000000..431845ed0592
--- /dev/null
+++ b/trampoline/.gitignore
@@ -0,0 +1,2 @@
+/target/
+.idea/
diff --git a/trampoline/README.md b/trampoline/README.md
new file mode 100644
index 000000000000..cae343a61df9
--- /dev/null
+++ b/trampoline/README.md
@@ -0,0 +1,45 @@
+---
+layout: pattern
+title: Trampoline
+folder: trampoline
+permalink: /patterns/trampoline/
+categories: Behavior
+tags:
+ - Java
+ - Difficulty-Intermediate
+ - Performance
+ - Recursion
+---
+
+## Intent
+Trampoline pattern is used for implementing algorithms recursively in Java without blowing the stack
+and to interleave the execution of functions without hard coding them together
+It is possible by representing a computation in one of 2 states : done | more
+(completed with result, or a reference to the reminder of the computation,
+something like the way a java.util.Supplier does).
+
+
+## Explanation
+Trampoline pattern allows to define recursive algorithms by iterative loop.
+
+
+## Applicability
+Use the Trampoline pattern when
+
+* For implementing tail recursive function. This pattern allows to switch on a stackless operation.
+* For interleaving the execution of two or more functions on the same thread.
+
+## Known uses(real world examples)
+* Trampoline refers to using reflection to avoid using inner classes, for example in event listeners.
+The time overhead of a reflection call is traded for the space overhead of an inner class.
+Trampolines in Java usually involve the creation of a GenericListener to pass events to an outer class.
+
+
+## Tutorials
+* [Trampolining: a practical guide for awesome Java Developers](https://medium.com/@johnmcclean/trampolining-a-practical-guide-for-awesome-java-developers-4b657d9c3076)
+* [Trampoline in java ](http://mindprod.com/jgloss/trampoline.html)
+
+## Credits
+* [library 'cyclops-react' uses the pattern](https://github.com/aol/cyclops-react)
+
+
diff --git a/trampoline/pom.xml b/trampoline/pom.xml
new file mode 100644
index 000000000000..71de3f8f2684
--- /dev/null
+++ b/trampoline/pom.xml
@@ -0,0 +1,77 @@
+<?xml version="1.0"?>
+<!--
+
+ The MIT License
+ Copyright (c) 2014-2016 Ilkka Seppälä
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+
+-->
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
+ xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>java-design-patterns</artifactId>
+ <version>1.19.0-SNAPSHOT</version>
+
+ </parent>
+ <artifactId>trampoline</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.12</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.projectlombok</groupId>
+ <artifactId>lombok</artifactId>
+ <version>1.16.18</version>
+ </dependency>
+
+
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <version>2.19</version>
+ <configuration>
+ <skipTests>false</skipTests>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
diff --git a/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java b/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java
new file mode 100644
index 000000000000..277ae9ffbad1
--- /dev/null
+++ b/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java
@@ -0,0 +1,85 @@
+package com.iluwatar.trampoline;
+
+import java.util.stream.Stream;
+
+/**
+ * <p>Trampoline pattern allows to define recursive algorithms by iterative loop </p>
+ * <p>When get is called on the returned Trampoline, internally it will iterate calling ‘jump’
+ * on the returned Trampoline as long as the concrete instance returned is {@link #more(Trampoline)},
+ * stopping once the returned instance is {@link #done(Object)}.</p>
+ * <p>Essential we convert looping via recursion into iteration,
+ * the key enabling mechanism is the fact that {@link #more(Trampoline)} is a lazy operation.</p>
+ *
+ * @param <T> is type for returning result.
+ */
+public interface Trampoline<T> {
+ T get();
+
+
+ /**
+ * @return next stage
+ */
+ default Trampoline<T> jump() {
+ return this;
+ }
+
+
+ default T result() {
+ return get();
+ }
+
+ /**
+ * @return true if complete
+ */
+ default boolean complete() {
+ return true;
+ }
+
+ /**
+ * Created a completed Trampoline
+ *
+ * @param result Completed result
+ * @return Completed Trampoline
+ */
+ static <T> Trampoline<T> done(final T result) {
+ return () -> result;
+ }
+
+
+ /**
+ * Create a Trampoline that has more work to do
+ *
+ * @param trampoline Next stage in Trampoline
+ * @return Trampoline with more work
+ */
+ static <T> Trampoline<T> more(final Trampoline<Trampoline<T>> trampoline) {
+ return new Trampoline<T>() {
+ @Override
+ public boolean complete() {
+ return false;
+ }
+
+ @Override
+ public Trampoline<T> jump() {
+ return trampoline.result();
+ }
+
+ @Override
+ public T get() {
+ return trampoline(this);
+ }
+
+ T trampoline(final Trampoline<T> trampoline) {
+
+ return Stream.iterate(trampoline, Trampoline::jump)
+ .filter(Trampoline::complete)
+ .findFirst()
+ .get()
+ .result();
+
+ }
+ };
+ }
+
+
+}
diff --git a/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java b/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java
new file mode 100644
index 000000000000..76e3ed3da080
--- /dev/null
+++ b/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java
@@ -0,0 +1,58 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ * <p>
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ * <p>
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ * <p>
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.trampoline;
+
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * <p>Trampoline pattern allows to define recursive algorithms by iterative loop </p>
+ * <p>it is possible to implement algorithms recursively in Java without blowing the stack
+ * and to interleave the execution of functions without hard coding them together or even using threads.</p>
+ */
+@Slf4j
+public class TrampolineApp {
+
+ /**
+ * Main program for showing pattern. It does loop with factorial function.
+ * */
+ public static void main(String[] args) {
+ log.info("start pattern");
+ Integer result = loop(10, 1).result();
+ log.info("result {}", result);
+
+ }
+
+ /**
+ * Manager for pattern. Define it with a factorial function.
+ */
+ public static Trampoline<Integer> loop(int times, int prod) {
+ if (times == 0) {
+ return Trampoline.done(prod);
+ } else {
+ return Trampoline.more(() -> loop(times - 1, prod * times));
+ }
+ }
+
+}
| diff --git a/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java b/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java
new file mode 100644
index 000000000000..553e583e12e9
--- /dev/null
+++ b/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java
@@ -0,0 +1,22 @@
+package com.iluwatar.trampoline;
+
+import org.junit.Test;
+
+import java.io.IOException;
+
+import static org.junit.Assert.*;
+
+
+/**
+ * Test for trampoline pattern.
+ * */
+public class TrampolineAppTest {
+
+
+ @Test
+ public void testTrampolineWithFactorialFunction() throws IOException {
+ int result = TrampolineApp.loop(10, 1).result();
+ assertEquals("Be equal", 3628800, result);
+ }
+
+}
\ No newline at end of file
| train | train | "2018-01-08T06:55:39" | "2017-12-11T09:29:04Z" | besok | train |
iluwatar/java-design-patterns/560_717 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/560 | iluwatar/java-design-patterns/717 | [
"timestamp(timedelta=974.0, similarity=0.934879032923891)"
] | 4ac6f90c96b6d34778c564fae501b4038f106979 | eddfe76a8487d687f7f74d8f7b50a6c005b7f112 | [
"I am working on this.",
"Ok @abhi-agr ",
"@abhi-agr I implemented something similar in my scene graph code without knowing this pattern. If you need collaborator in this pattern please let me know. ",
"@abhi-agr are you still implementing this?",
"Sorry I am not working on this, I got busy with my work. ",
"This issue is free for taking again",
"@iluwatar \r\n\r\nHello. I would like to work on this particular pattern. I'll be drawing up inspiration from https://www.takeupcode.com/podcast/89-design-patterns-dirty-flag/ . \r\n\r\nIs that alright?",
"@waisuan ok",
"Kindly take a look at my pull request and lemme know if I've missed out on something. Thanks! @iluwatar ",
"Closing this issue. PR successfully merged."
] | [
"I am not sure if DataFetcher should be returning `null` to indicate no change in data. Any other options for this?",
"Suggestion: Just document a warning that this is not a thread safe way to implement Singleton. Refer to Singleton for more information.",
"Question: I don't understand the intent to keep `World` and `DataFetcher` singleton here. Any particular reason you chose this way?",
"This singleton reset thing won't be needed if we avoid `getInstance`. Hence my question about Singletonness.",
"The class diagram should be made with ObjectAid eclipse plugin. More about it in wiki ",
"Done.",
"Use `assertFalse()` in place of `assertTrue(!condition)`"
] | "2018-02-19T16:10:42Z" | [
"epic: pattern"
] | Dirty Flag pattern | http://gameprogrammingpatterns.com/dirty-flag.html | [
"pom.xml"
] | [
"dirty-flag/README.md",
"dirty-flag/etc/dirty-flag.ucls",
"dirty-flag/pom.xml",
"dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java",
"dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java",
"dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java",
"dirty-flag/src/main/resources/world.txt",
"pom.xml"
] | [
"dirty-flag/src/test/java/org/dirty/flag/AppTest.java",
"dirty-flag/src/test/java/org/dirty/flag/DirtyFlagTest.java"
] | diff --git a/dirty-flag/README.md b/dirty-flag/README.md
new file mode 100644
index 000000000000..36c92f0e28b8
--- /dev/null
+++ b/dirty-flag/README.md
@@ -0,0 +1,26 @@
+---
+layout: pattern
+title: Dirty Flag
+folder: dirty-flag
+permalink: /patterns/dirty-flag/
+categories: Other
+tags:
+ - Java
+ - Difficulty-Easy
+ - Performance
+---
+
+## Intent
+To avoid expensive re-acquisition of resources. The resources retain their identity, are kept in some
+fast-access storage, and are re-used to avoid having to acquire them again.
+
+![alt text](./etc/dirty-flag.png "Dirty Flag")
+
+## Applicability
+Use the Dirty Flag pattern when
+
+* Repetitious acquisition, initialization, and release of the same resource causes unnecessary performance overhead.
+
+## Credits
+
+* [Design Patterns: Dirty Flag](https://www.takeupcode.com/podcast/89-design-patterns-dirty-flag/)
diff --git a/dirty-flag/etc/dirty-flag.ucls b/dirty-flag/etc/dirty-flag.ucls
new file mode 100644
index 000000000000..760d456f731d
--- /dev/null
+++ b/dirty-flag/etc/dirty-flag.ucls
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<class-diagram version="1.2.2" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
+ realizations="true" associations="true" dependencies="false" nesting-relationships="true" router="FAN">
+ <class id="1" language="java" name="com.iluwatar.dirtyflag.App" project="dirty-flag"
+ file="/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="266" y="188"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <class id="2" language="java" name="com.iluwatar.dirtyflag.DataFetcher" project="dirty-flag"
+ file="/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="153" width="125" x="66" y="291"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <class id="3" language="java" name="com.iluwatar.dirtyflag.World" project="dirty-flag"
+ file="/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="379" y="366"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <association id="4">
+ <end type="SOURCE" refId="3" navigable="false">
+ <attribute id="5" name="df"/>
+ <multiplicity id="6" minimum="0" maximum="1"/>
+ </end>
+ <end type="TARGET" refId="2" navigable="true"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </classifier-display>
+ <association-display labels="true" multiplicity="true"/>
+</class-diagram>
\ No newline at end of file
diff --git a/dirty-flag/pom.xml b/dirty-flag/pom.xml
new file mode 100644
index 000000000000..a50381a56d72
--- /dev/null
+++ b/dirty-flag/pom.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0"?>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>java-design-patterns</artifactId>
+ <version>1.20.0-SNAPSHOT</version>
+ </parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>dirty-flag</artifactId>
+ <version>1.20.0-SNAPSHOT</version>
+ <name>dirty-flag</name>
+ <url>http://maven.apache.org</url>
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ </properties>
+ <dependencies>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
diff --git a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java
new file mode 100644
index 000000000000..4d72b34da249
--- /dev/null
+++ b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java
@@ -0,0 +1,82 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ * <p>
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ * <p>
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ * <p>
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.dirtyflag;
+
+import java.util.List;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+/**
+ *
+ * This application demonstrates the <b>Dirty Flag</b> pattern. The dirty flag behavioral pattern allows you to avoid
+ * expensive operations that would just need to be done again anyway. This is a simple pattern that really just explains
+ * how to add a bool value to your class that you can set anytime a property changes. This will let your class know that
+ * any results it may have previously calculated will need to be calculated again when they’re requested. Once the
+ * results are re-calculated, then the bool value can be cleared.
+ *
+ * There are some points that need to be considered before diving into using this pattern:- there are some things you’ll
+ * need to consider:- (1) Do you need it? This design pattern works well when the results to be calculated are difficult
+ * or resource intensive to compute. You want to save them. You also don’t want to be calculating them several times in
+ * a row when only the last one counts. (2) When do you set the dirty flag? Make sure that you set the dirty flag within
+ * the class itself whenever an important property changes. This property should affect the result of the calculated
+ * result and by changing the property, that makes the last result invalid. (3) When do you clear the dirty flag? It
+ * might seem obvious that the dirty flag should be cleared whenever the result is calculated with up-to-date
+ * information but there are other times when you might want to clear the flag.
+ *
+ * In this example, the {@link DataFetcher} holds the <i>dirty flag</i>. It fetches and re-fetches from <i>world.txt</i>
+ * when needed. {@link World} mainly serves the data to the front-end.
+ */
+public class App {
+ /**
+ * Program execution point
+ */
+ public void run() {
+
+ final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
+ executorService.scheduleAtFixedRate(new Runnable() {
+ @Override
+ public void run() {
+ World world = new World();
+ List<String> countries = world.fetch();
+ System.out.println("Our world currently has the following countries:-");
+ for (String country : countries) {
+ System.out.println("\t" + country);
+ }
+ }
+ }, 0, 15, TimeUnit.SECONDS); // Run at every 15 seconds.
+ }
+
+ /**
+ * Program entry point
+ *
+ * @param args
+ * command line args
+ */
+ public static void main(String[] args) {
+ App app = new App();
+
+ app.run();
+ }
+
+}
diff --git a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java
new file mode 100644
index 000000000000..9123bf32db3f
--- /dev/null
+++ b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java
@@ -0,0 +1,59 @@
+package com.iluwatar.dirtyflag;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A mock database manager -- Fetches data from a raw file.
+ *
+ * @author swaisuan
+ *
+ */
+public class DataFetcher {
+
+ private final String filename = "world.txt";
+ private long lastFetched;
+
+ public DataFetcher() {
+ this.lastFetched = -1;
+ }
+
+ private boolean isDirty(long fileLastModified) {
+ if (lastFetched != fileLastModified) {
+ lastFetched = fileLastModified;
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Fetches data/content from raw file.
+ *
+ * @return List of strings
+ */
+ public List<String> fetch() {
+ ClassLoader classLoader = getClass().getClassLoader();
+ File file = new File(classLoader.getResource(filename).getFile());
+
+ if (isDirty(file.lastModified())) {
+ System.out.println(filename + " is dirty! Re-fetching file content...");
+
+ List<String> data = new ArrayList<String>();
+ try (BufferedReader br = new BufferedReader(new FileReader(file))) {
+ String line;
+ while ((line = br.readLine()) != null) {
+ data.add(line);
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return data;
+ }
+
+ return new ArrayList<String>();
+ }
+}
diff --git a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java
new file mode 100644
index 000000000000..d356e6581798
--- /dev/null
+++ b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java
@@ -0,0 +1,36 @@
+package com.iluwatar.dirtyflag;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ *
+ * A middle-layer app that calls/passes along data from the back-end.
+ *
+ * @author swaisuan
+ *
+ */
+public class World {
+
+ private List<String> countries;
+ private DataFetcher df;
+
+ public World() {
+ this.countries = new ArrayList<String>();
+ this.df = new DataFetcher();
+ }
+
+ /**
+ *
+ * Calls {@link DataFetcher} to fetch data from back-end.
+ *
+ * @return List of strings
+ */
+ public List<String> fetch() {
+ List<String> data = df.fetch();
+
+ countries = data.isEmpty() ? countries : data;
+
+ return countries;
+ }
+}
diff --git a/dirty-flag/src/main/resources/world.txt b/dirty-flag/src/main/resources/world.txt
new file mode 100644
index 000000000000..280ea370239c
--- /dev/null
+++ b/dirty-flag/src/main/resources/world.txt
@@ -0,0 +1,3 @@
+UNITED_KINGDOM
+MALAYSIA
+UNITED_STATES
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index 965c8f37c483..e1d025c13bc1 100644
--- a/pom.xml
+++ b/pom.xml
@@ -158,7 +158,8 @@
<module>eip-splitter</module>
<module>eip-aggregator</module>
<module>retry</module>
- <module>trampoline</module>
+ <module>dirty-flag</module>
+ <module>trampoline</module>
<module>serverless</module>
</modules>
| diff --git a/dirty-flag/src/test/java/org/dirty/flag/AppTest.java b/dirty-flag/src/test/java/org/dirty/flag/AppTest.java
new file mode 100644
index 000000000000..50f107cd58c0
--- /dev/null
+++ b/dirty-flag/src/test/java/org/dirty/flag/AppTest.java
@@ -0,0 +1,40 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package org.dirty.flag;
+
+import java.io.IOException;
+
+import org.junit.jupiter.api.Test;
+
+import com.iluwatar.dirtyflag.App;
+
+/**
+ * Tests that Dirty-Flag example runs without errors.
+ */
+public class AppTest {
+ @Test
+ public void test() throws IOException {
+ String[] args = {};
+ App.main(args);
+ }
+}
diff --git a/dirty-flag/src/test/java/org/dirty/flag/DirtyFlagTest.java b/dirty-flag/src/test/java/org/dirty/flag/DirtyFlagTest.java
new file mode 100644
index 000000000000..8f651b2678bb
--- /dev/null
+++ b/dirty-flag/src/test/java/org/dirty/flag/DirtyFlagTest.java
@@ -0,0 +1,54 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package org.dirty.flag;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+
+import com.iluwatar.dirtyflag.DataFetcher;
+
+/**
+ *
+ * Application test
+ *
+ */
+public class DirtyFlagTest {
+
+ @Test
+ public void testIsDirty() {
+ DataFetcher df = new DataFetcher();
+ List<String> countries = df.fetch();
+ assertTrue(!countries.isEmpty());
+ }
+
+ @Test
+ public void testIsNotDirty() {
+ DataFetcher df = new DataFetcher();
+ df.fetch();
+ List<String> countries = df.fetch();
+ assertTrue(countries.isEmpty());
+ }
+}
| val | train | "2018-04-29T09:39:51" | "2017-04-01T08:57:10Z" | iluwatar | train |
iluwatar/java-design-patterns/725_726 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/725 | iluwatar/java-design-patterns/726 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.9169838390585222)"
] | c723289bbb7ea841fa15b73006fedbe413691035 | 68799908578ec471239d45460d4aa0af4684ec67 | [
"Hi,\r\n Did they provide you with the new URL pattern? It looks like that even in the SonarSource repo they are still using the old URL (search for quality gate):\r\n\r\n https://raw.githubusercontent.com/SonarSource/sonar-java/master/README.md",
"The new URL's are provided on the sonarcloud.io project page. The options\r\n\r\nhttps://sonarcloud.io/api/project_badges/measure?project=com.iluwatar%3Ajava-design-patterns&metric=alert_status\r\nhttps://sonarcloud.io/api/project_badges/quality_gate?project=com.iluwatar%3Ajava-design-patterns\r\nhttps://sonarcloud.io/images/project_badges/sonarcloud-white.svg"
] | [] | "2018-03-14T17:22:45Z" | [
"info: help wanted",
"epic: web site",
"info: good first issue"
] | SonarCloud badge URL changing | Hi,
About a month ago, we deployed new built-in badges on SonarCloud:
News: https://about.sonarcloud.io/news/2018/02/05/new-project-badges.html
Tweet: https://twitter.com/sonarcloud/status/960790516936867840
As explained in the news, the URL for those new badges is different from the old one - which we will remove on Monday April, 2nd (so in a month from now).
I'm contacting you because we noticed that some of the projects you are admin of might still be referencing the deprecated badge URL ("/api/badges/..."). If this is not the case, please ignore this email - what we see in our logs might come from forks of your repositories. However, if some of your projects do still use those deprecated URL, you might want to update them in the upcoming month to keep on enjoying SonarCloud badges on your projects.
Hope you enjoy the service!
Best regards,
Fabrice Bellingard | SonarSource
SonarCloud Product Manager
https://sonarsource.com | [
"README.md"
] | [
"README.md"
] | [] | diff --git a/README.md b/README.md
index 03aea2bf64e0..4ec0f33bd350 100644
--- a/README.md
+++ b/README.md
@@ -7,7 +7,7 @@
[![Build status](https://travis-ci.org/iluwatar/java-design-patterns.svg?branch=master)](https://travis-ci.org/iluwatar/java-design-patterns)
[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md)
[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
-[![Quality Gate](https://sonarcloud.io/api/badges/gate?key=com.iluwatar%3Ajava-design-patterns)](https://sonarcloud.io/dashboard/index/com.iluwatar%3Ajava-design-patterns)
+[![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=com.iluwatar%3Ajava-design-patterns&metric=alert_status)](https://sonarcloud.io/dashboard/index/com.iluwatar%3Ajava-design-patterns)
[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/1503/badge)](https://bestpractices.coreinfrastructure.org/projects/1503)
# Introduction
| null | train | train | "2018-03-11T20:59:13" | "2018-03-10T11:38:43Z" | iluwatar | train |
iluwatar/java-design-patterns/722_755 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/722 | iluwatar/java-design-patterns/755 | [
"timestamp(timedelta=31.0, similarity=0.9386446228913135)"
] | c7f9266768e566a532280d51b67dc070394233d6 | d915b66e70bf8ba7ad07daf8fcc3d9972b8cf435 | [
"@npathai According to me this pattern is just extended use of proxy pattern. Here at edge service, we are putting our logic for the proxy which hides actual Application and also provides us extendibility to put our circuit breaking and other logic in that.\r\nEg. Hibernate Transaction management uses proxy pattern in which it provide extendibility to provide support for commits/roll-back \r\nLet me know if it makes any sense ",
"@harshitrathod despite this seeming like an extension of proxy as you stated, is it still viable to create an example? If so I would be interested in doing so.",
"Yes, go ahead @okinskas ",
"@harshitrathod Yeah it does make sense. It is almost (if not exactly) same as Remote Proxy pattern."
] | [
"Isn't networking just one example of Ambassador usages? Could the description be more general?",
"This can be written on one line `private RemoteService() {}`. Please check whitespace usage elsewhere too.",
"Use logger for output. Check this elsewhere too.",
"Could be `private final ServiceAmbassador serviceAmbassador = new ServiceAmbassador();`",
"Use logger",
"Could be written on one line `RemoteService.getRemoteService().doRemoteFunction(value)`",
"Not sure where this assertion comes from",
"Not sure where this assertion comes from",
"Could be written on one line",
"Thank you for the review. I will implement the changes.\r\n\r\nThis assertion is because ServiceAmbassador will either return input * 10 (100) using the remote service or -1 if the connection fails after 3 attempts so either of those assertions is valid. \r\n\r\nWould you suggest a better way of testing this?"
] | "2018-06-04T21:52:31Z" | [
"info: help wanted"
] | Ambassador Pattern | https://docs.microsoft.com/en-us/azure/architecture/patterns/ambassador | [
"pom.xml"
] | [
"ambassador/README.md",
"ambassador/pom.xml",
"ambassador/src/main/java/com/iluwatar/ambassador/App.java",
"ambassador/src/main/java/com/iluwatar/ambassador/Client.java",
"ambassador/src/main/java/com/iluwatar/ambassador/RemoteService.java",
"ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceInterface.java",
"ambassador/src/main/java/com/iluwatar/ambassador/ServiceAmbassador.java",
"pom.xml"
] | [
"ambassador/src/test/java/com/iluwatar/ambassador/AppTest.java",
"ambassador/src/test/java/com/iluwatar/ambassador/ClientTest.java",
"ambassador/src/test/java/com/iluwatar/ambassador/RemoteServiceTest.java",
"ambassador/src/test/java/com/iluwatar/ambassador/ServiceAmbassadorTest.java"
] | diff --git a/ambassador/README.md b/ambassador/README.md
new file mode 100644
index 000000000000..f23d1e13cedb
--- /dev/null
+++ b/ambassador/README.md
@@ -0,0 +1,178 @@
+---
+layout: pattern
+title: Ambassador
+folder: ambassador
+permalink: /patterns/ambassador/
+categories: Structural
+tags:
+ - Java
+ - Difficulty-Intermediate
+---
+
+## Intent
+Provide a helper service instance on a client and offload common functionality away from a shared resource.
+
+## Explanation
+Real world example
+
+> A remote service has many clients accessing a function it provides. The service is a legacy application and is impossible to update. Large numbers of requests from users are causing connectivity issues. New rules for request frequency should be implemented along with latency checks and client-side logging.
+
+In plain words
+
+> Using the ambassador pattern, we can implement less-frequent polling from clients along with latency checks and logging.
+
+Microsoft documentation states
+
+> An ambassador service can be thought of as an out-of-process proxy that is co-located with the client.
+ This pattern can be useful for offloading common client connectivity tasks such as monitoring, logging, routing, security (such as TLS), and resiliency patterns in a language agnostic way. It is often used with legacy applications, or other applications that are difficult to modify, in order to extend their networking capabilities. It can also enable a specialized team to implement those features.
+
+**Programmatic Example**
+
+With the above example in mind we will imitate the functionality in a simple manner. We have an interface implemented by the remote service as well as the ambassador service:
+
+```java
+interface RemoteServiceInterface {
+
+ long doRemoteFunction(int value) throws Exception;
+}
+```
+
+A remote services represented as a singleton.
+
+```java
+public class RemoteService implements RemoteServiceInterface {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(RemoteService.class);
+ private static RemoteService service = null;2
+
+ static synchronized RemoteService getRemoteService() {
+ if (service == null) {
+ service = new RemoteService();
+ }
+ return service;
+ }
+
+ private RemoteService() {}
+
+ @Override
+ public long doRemoteFunction(int value) {
+
+ long waitTime = (long) Math.floor(Math.random() * 1000);
+
+ try {
+ sleep(waitTime);
+ } catch (InterruptedException e) {
+ LOGGER.error("Thread sleep interrupted", e)
+ }
+ return waitTime >= 200 ? value * 10 : -1;
+ }
+}
+```
+
+A service ambassador adding additional features such as logging, latency checks
+
+```java
+public class ServiceAmbassador implements RemoteServiceInterface {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(ServiceAmbassador.class);
+ private static final int RETRIES = 3;
+ private static final int DELAY_MS = 3000;
+
+ ServiceAmbassador() {}
+
+ @Override
+ public long doRemoteFunction(int value) {
+
+ return safeCall(value);
+ }
+
+ private long checkLatency(int value) {
+ RemoteService service = RemoteService.getRemoteService();
+ long startTime = System.currentTimeMillis();
+ long result = service.doRemoteFunction(value);
+ long timeTaken = System.currentTimeMillis() - startTime;
+
+ LOGGER.info("Time taken (ms): " + timeTaken);
+ return result;
+ }
+
+ private long safeCall(int value) {
+
+ int retries = 0;
+ long result = -1;
+
+ for (int i = 0; i < RETRIES; i++) {
+
+ if (retries >= RETRIES) {
+ return -1;
+ }
+
+ if ((result = checkLatency(value)) == -1) {
+ LOGGER.info("Failed to reach remote: (" + (i + 1) + ")");
+ retries++;
+ try {
+ sleep(DELAY_MS);
+ } catch (InterruptedException e) {
+ LOGGER.error("Thread sleep state interrupted", e);
+ }
+ } else {
+ break;
+ }
+ }
+ return result;
+ }
+}
+```
+
+A client has a local service ambassador used to interact with the remote service:
+
+```java
+public class Client {
+
+ private ServiceAmbassador serviceAmbassador;
+
+ Client() {
+ serviceAmbassador = new ServiceAmbassador();
+ }
+
+ long useService(int value) {
+ long result = serviceAmbassador.doRemoteFunction(value);
+ LOGGER.info("Service result: " + result)
+ return result;
+ }
+}
+```
+
+And here are two clients using the service.
+
+```java
+Client host1 = new Client();
+Client host2 = new Client();
+host1.useService(12);
+host2.useService(73);
+```
+
+## Applicability
+Ambassador is applicable when working with a legacy remote service that cannot
+be modified or would be extremely difficult to modify. Connectivity features can
+be implemented on the client avoiding the need for changes on the remote service.
+
+* Ambassador provides a local interface for a remote service.
+* Ambassador provides logging, circuit breaking, retries and security on the client.
+
+## Typical Use Case
+
+* Control access to another object
+* Implement logging
+* Implement circuit breaking
+* Offload remote service tasks
+* Facilitate network connection
+
+## Real world examples
+
+* [Kubernetes-native API gateway for microservices](https://github.com/datawire/ambassador)
+
+## Credits
+
+* [Ambassador pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/ambassador)
+* [Designing Distributed Systems: Patterns and Paradigms for Scalable, Reliable Services](https://books.google.co.uk/books?id=6BJNDwAAQBAJ&pg=PT35&lpg=PT35&dq=ambassador+pattern+in+real+world&source=bl&ots=d2e7GhYdHi&sig=Lfl_MDnCgn6lUcjzOg4GXrN13bQ&hl=en&sa=X&ved=0ahUKEwjk9L_18rrbAhVpKcAKHX_KA7EQ6AEIWTAI#v=onepage&q=ambassador%20pattern%20in%20real%20world&f=false)
diff --git a/ambassador/pom.xml b/ambassador/pom.xml
new file mode 100644
index 000000000000..f47b76f9a643
--- /dev/null
+++ b/ambassador/pom.xml
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+ The MIT License
+ Copyright (c) 2014-2016 Ilkka Seppälä
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <parent>
+ <artifactId>java-design-patterns</artifactId>
+ <groupId>com.iluwatar</groupId>
+ <version>1.20.0-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>ambassador</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
\ No newline at end of file
diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/App.java b/ambassador/src/main/java/com/iluwatar/ambassador/App.java
new file mode 100644
index 000000000000..e4b4d392ab3c
--- /dev/null
+++ b/ambassador/src/main/java/com/iluwatar/ambassador/App.java
@@ -0,0 +1,53 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.ambassador;
+
+/**
+ *
+ * The ambassador pattern creates a helper service that sends network requests on behalf of a
+ * client. It is often used in cloud-based applications to offload features of a remote service.
+ *
+ * An ambassador service can be thought of as an out-of-process proxy that is co-located with
+ * the client. Similar to the proxy design pattern, the ambassador service provides an interface
+ * for another remote service. In addition to the interface, the ambassador provides extra
+ * functionality and features, specifically offloaded common connectivity tasks. This usually
+ * consists of monitoring, logging, routing, security etc. This is extremely useful in
+ * legacy applications where the codebase is difficult to modify and allows for improvements
+ * in the application's networking capabilities.
+ *
+ * In this example, we will the ({@link ServiceAmbassador}) class represents the ambassador while the
+ * ({@link RemoteService}) class represents a remote application.
+ *
+ */
+public class App {
+
+ /**
+ * Entry point
+ */
+ public static void main(String[] args) {
+ Client host1 = new Client();
+ Client host2 = new Client();
+ host1.useService(12);
+ host2.useService(73);
+ }
+}
diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/Client.java b/ambassador/src/main/java/com/iluwatar/ambassador/Client.java
new file mode 100644
index 000000000000..9832265303ec
--- /dev/null
+++ b/ambassador/src/main/java/com/iluwatar/ambassador/Client.java
@@ -0,0 +1,42 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.ambassador;
+
+import org.slf4j.LoggerFactory;
+
+import org.slf4j.Logger;
+
+/**
+ * A simple Client
+ */
+public class Client {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(Client.class);
+ private final ServiceAmbassador serviceAmbassador = new ServiceAmbassador();
+
+ long useService(int value) {
+ long result = serviceAmbassador.doRemoteFunction(value);
+ LOGGER.info("Service result: " + result);
+ return result;
+ }
+}
diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/RemoteService.java b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteService.java
new file mode 100644
index 000000000000..225e033d8e78
--- /dev/null
+++ b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteService.java
@@ -0,0 +1,65 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.ambassador;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static java.lang.Thread.sleep;
+
+/**
+ * A remote legacy application represented by a Singleton implementation.
+ */
+public class RemoteService implements RemoteServiceInterface {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(RemoteService.class);
+ private static RemoteService service = null;
+
+ static synchronized RemoteService getRemoteService() {
+ if (service == null) {
+ service = new RemoteService();
+ }
+ return service;
+ }
+
+ private RemoteService() {}
+
+ /**
+ * Remote function takes a value and multiplies it by 10 taking a random amount of time.
+ * Will sometimes return -1. This imitates connectivity issues a client might have to account for.
+ * @param value integer value to be multiplied.
+ * @return if waitTime is more than 200ms, it returns value * 10, otherwise -1.
+ */
+ @Override
+ public long doRemoteFunction(int value) {
+
+ long waitTime = (long) Math.floor(Math.random() * 1000);
+
+ try {
+ sleep(waitTime);
+ } catch (InterruptedException e) {
+ LOGGER.error("Thread sleep state interrupted", e);
+ }
+ return waitTime >= 200 ? value * 10 : -1;
+ }
+}
diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceInterface.java b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceInterface.java
new file mode 100644
index 000000000000..940313de36a0
--- /dev/null
+++ b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceInterface.java
@@ -0,0 +1,31 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.ambassador;
+
+/**
+ * Interface shared by ({@link RemoteService}) and ({@link ServiceAmbassador}).
+ */
+interface RemoteServiceInterface {
+
+ long doRemoteFunction(int value) throws Exception;
+}
diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/ServiceAmbassador.java b/ambassador/src/main/java/com/iluwatar/ambassador/ServiceAmbassador.java
new file mode 100644
index 000000000000..4be1dfcbf2db
--- /dev/null
+++ b/ambassador/src/main/java/com/iluwatar/ambassador/ServiceAmbassador.java
@@ -0,0 +1,84 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.ambassador;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static java.lang.Thread.sleep;
+
+/**
+ *
+ * ServiceAmbassador provides an interface for a ({@link Client}) to access ({@link RemoteService}).
+ * The interface adds logging, latency testing and usage of the service in a safe way that will not
+ * add stress to the remote service when connectivity issues occur.
+ *
+ */
+public class ServiceAmbassador implements RemoteServiceInterface {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(ServiceAmbassador.class);
+ private static final int RETRIES = 3;
+ private static final int DELAY_MS = 3000;
+
+ ServiceAmbassador() {}
+
+ @Override
+ public long doRemoteFunction(int value) {
+ return safeCall(value);
+ }
+
+ private long checkLatency(int value) {
+ long startTime = System.currentTimeMillis();
+ long result = RemoteService.getRemoteService().doRemoteFunction(value);
+ long timeTaken = System.currentTimeMillis() - startTime;
+
+ LOGGER.info("Time taken (ms): " + timeTaken);
+ return result;
+ }
+
+ private long safeCall(int value) {
+
+ int retries = 0;
+ long result = -1;
+
+ for (int i = 0; i < RETRIES; i++) {
+
+ if (retries >= RETRIES) {
+ return -1;
+ }
+
+ if ((result = checkLatency(value)) == -1) {
+ LOGGER.info("Failed to reach remote: (" + (i + 1) + ")");
+ retries++;
+ try {
+ sleep(DELAY_MS);
+ } catch (InterruptedException e) {
+ LOGGER.error("Thread sleep state interrupted", e);
+ }
+ } else {
+ break;
+ }
+ }
+ return result;
+ }
+}
diff --git a/pom.xml b/pom.xml
index 00b0de4f1fe2..81763b6c1100 100644
--- a/pom.xml
+++ b/pom.xml
@@ -161,7 +161,8 @@
<module>dirty-flag</module>
<module>trampoline</module>
<module>serverless</module>
- <module>acyclic-visitor</module>
+ <module>ambassador</module>
+ <module>acyclic-visitor</module>
</modules>
<repositories>
| diff --git a/ambassador/src/test/java/com/iluwatar/ambassador/AppTest.java b/ambassador/src/test/java/com/iluwatar/ambassador/AppTest.java
new file mode 100644
index 000000000000..cb072c1eb406
--- /dev/null
+++ b/ambassador/src/test/java/com/iluwatar/ambassador/AppTest.java
@@ -0,0 +1,36 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.ambassador;
+
+import org.junit.jupiter.api.Test;
+
+/**
+ * Application test
+ */
+public class AppTest {
+
+ @Test
+ public void test() {
+ App.main(new String[]{});
+ }
+}
diff --git a/ambassador/src/test/java/com/iluwatar/ambassador/ClientTest.java b/ambassador/src/test/java/com/iluwatar/ambassador/ClientTest.java
new file mode 100644
index 000000000000..9354c4f868d4
--- /dev/null
+++ b/ambassador/src/test/java/com/iluwatar/ambassador/ClientTest.java
@@ -0,0 +1,40 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.ambassador;
+
+import org.junit.jupiter.api.Test;
+
+/**
+ * Test for {@link Client}
+ */
+public class ClientTest {
+
+ @Test
+ public void test() {
+
+ Client client = new Client();
+ long result = client.useService(10);
+
+ assert result == 100 || result == -1;
+ }
+}
diff --git a/ambassador/src/test/java/com/iluwatar/ambassador/RemoteServiceTest.java b/ambassador/src/test/java/com/iluwatar/ambassador/RemoteServiceTest.java
new file mode 100644
index 000000000000..e0b297af4841
--- /dev/null
+++ b/ambassador/src/test/java/com/iluwatar/ambassador/RemoteServiceTest.java
@@ -0,0 +1,37 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.ambassador;
+
+import org.junit.jupiter.api.Test;
+
+/**
+ * Test for {@link RemoteService}
+ */
+public class RemoteServiceTest {
+
+ @Test
+ public void test() {
+ long result = RemoteService.getRemoteService().doRemoteFunction(10);
+ assert result == 100 || result == -1;
+ }
+}
diff --git a/ambassador/src/test/java/com/iluwatar/ambassador/ServiceAmbassadorTest.java b/ambassador/src/test/java/com/iluwatar/ambassador/ServiceAmbassadorTest.java
new file mode 100644
index 000000000000..432df9fd13e4
--- /dev/null
+++ b/ambassador/src/test/java/com/iluwatar/ambassador/ServiceAmbassadorTest.java
@@ -0,0 +1,37 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.ambassador;
+
+import org.junit.jupiter.api.Test;
+
+/**
+ * Test for {@link ServiceAmbassador}
+ */
+public class ServiceAmbassadorTest {
+
+ @Test
+ public void test() {
+ long result = new ServiceAmbassador().doRemoteFunction(10);
+ assert result == 100 || result == -1;
+ }
+}
| train | train | "2018-06-28T10:25:32" | "2018-02-26T11:52:14Z" | npathai | train |
iluwatar/java-design-patterns/784_787 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/784 | iluwatar/java-design-patterns/787 | [
"timestamp(timedelta=53.0, similarity=0.9241091745913026)",
"keyword_issue_to_pr"
] | 16df157181990e8d384f7dfcdc1bac424928d273 | b64262303aa1980ac64ead4bc2e8b7fd7bf1a834 | [
"PR #787 has been merged. Closing this issue now."
] | [] | "2018-08-21T02:38:22Z" | [] | Minor Checkstyle issues | com.iluwatar.acyclicvisitor.ZoomVisitor.java and com.iluwatar.retry.Retry.java have Checkstyle warnings. | [
"acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ZoomVisitor.java",
"retry/src/main/java/com/iluwatar/retry/Retry.java"
] | [
"acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ZoomVisitor.java",
"retry/src/main/java/com/iluwatar/retry/Retry.java"
] | [] | diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ZoomVisitor.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ZoomVisitor.java
index b4c949ed7b71..6a47867fc81b 100644
--- a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ZoomVisitor.java
+++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ZoomVisitor.java
@@ -25,6 +25,6 @@
/**
* ZoomVisitor interface
*/
-public interface ZoomVisitor extends ModemVisitor{
+public interface ZoomVisitor extends ModemVisitor {
void visit(Zoom zoom);
}
diff --git a/retry/src/main/java/com/iluwatar/retry/Retry.java b/retry/src/main/java/com/iluwatar/retry/Retry.java
index 5ed60f98b537..da5c76d5d3ac 100644
--- a/retry/src/main/java/com/iluwatar/retry/Retry.java
+++ b/retry/src/main/java/com/iluwatar/retry/Retry.java
@@ -105,6 +105,7 @@ public T perform() throws BusinessException {
//ignore
}
}
- } while (true);
+ }
+ while (true);
}
}
| null | val | train | "2018-08-13T07:13:06" | "2018-08-20T03:54:17Z" | bordoisila1 | train |
iluwatar/java-design-patterns/781_794 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/781 | iluwatar/java-design-patterns/794 | [
"keyword_pr_to_issue"
] | 9e56e5cbc1c86980fe61d04bd1e247461611dc99 | b079aec1fdf6e72ffccb4373083b90ce16f562ff | [
"@iluwatar That is not a bug, it is expected to happen. I will change the log level and use `instanceof` instead to resolve the confusion.",
"Well done @npathai Thank you!"
] | [] | "2018-09-11T10:32:38Z" | [
"type: bug"
] | ClassCastException was throwed in App.java#52 | The row that has an exception was:
hayes.accept(conUnix); // Hayes modem with Unix configurator
Because of ConfigureForUnixVisitor didn't implements HayesVisitor.
#java-design-patterns/acyclic-visitor | [
"acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/AllModemVisitor.java",
"acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitor.java",
"acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Hayes.java",
"acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Zoom.java"
] | [
"acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/AllModemVisitor.java",
"acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitor.java",
"acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Hayes.java",
"acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Zoom.java"
] | [] | diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/AllModemVisitor.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/AllModemVisitor.java
index e6f5834462d1..749ea00a25fb 100644
--- a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/AllModemVisitor.java
+++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/AllModemVisitor.java
@@ -23,8 +23,9 @@
package com.iluwatar.acyclicvisitor;
/**
- * All ModemVisitor interface extends all visitor interfaces
+ * All ModemVisitor interface extends all visitor interfaces. This interface
+ * provides ease of use when a visitor needs to visit all modem types.
*/
-public interface AllModemVisitor extends ModemVisitor, ZoomVisitor, HayesVisitor{
+public interface AllModemVisitor extends ZoomVisitor, HayesVisitor{
}
diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitor.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitor.java
index d3ef3bf6c018..c3546012166d 100644
--- a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitor.java
+++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitor.java
@@ -27,9 +27,10 @@
/**
* ConfigureForUnixVisitor class implements zoom's visit method for Unix
- * manufacturer
+ * manufacturer, unlike traditional visitor pattern, this class may selectively implement
+ * visit for other modems.
*/
-public class ConfigureForUnixVisitor implements ModemVisitor, ZoomVisitor {
+public class ConfigureForUnixVisitor implements ZoomVisitor {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigureForUnixVisitor.class);
diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Hayes.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Hayes.java
index 1128057bfd76..3ee76a812b49 100644
--- a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Hayes.java
+++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Hayes.java
@@ -37,10 +37,10 @@ public class Hayes extends Modem {
*/
@Override
public void accept(ModemVisitor modemVisitor) {
- try {
+ if (modemVisitor instanceof HayesVisitor) {
((HayesVisitor) modemVisitor).visit(this);
- } catch (ClassCastException e) {
- LOGGER.error("Unable to cast to HayesVisitor");
+ } else {
+ LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem");
}
}
diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Zoom.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Zoom.java
index 7091d79dfff8..ee054851e514 100644
--- a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Zoom.java
+++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Zoom.java
@@ -37,10 +37,10 @@ public class Zoom extends Modem {
*/
@Override
public void accept(ModemVisitor modemVisitor) {
- try {
+ if (modemVisitor instanceof ZoomVisitor) {
((ZoomVisitor) modemVisitor).visit(this);
- } catch (ClassCastException e) {
- LOGGER.error("Unable to cast to ZoomVisitor");
+ } else {
+ LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem");
}
}
| null | val | train | "2018-09-08T20:54:42" | "2018-08-10T02:55:01Z" | yushouling | train |
iluwatar/java-design-patterns/795_796 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/795 | iluwatar/java-design-patterns/796 | [
"keyword_pr_to_issue"
] | 9e56e5cbc1c86980fe61d04bd1e247461611dc99 | 3cec7a9ec1c5c196969153d802d264f891a5761b | [
"@LyndonArmitage thanks for the improvement suggestion. I think those files could be removed from git and added to `.gitignore`. I would be glad to accept pull request for this.",
"See PR: #796"
] | [] | "2018-09-24T09:14:38Z" | [
"info: help wanted",
"info: good first issue"
] | module/output.txt & module/error.txt change on build | First off great project here, thanks for spending time collating all this information! :+1:
Something very minor I noticed when building the project locally with `mvn clean package` is that the files:
`module/output.txt` and `module/error.txt` end up being change to not include the MIT licence.
Perhaps they should be removed with `git rm` and then added to the ignore file as they are generated by tests? Or the [test](https://github.com/iluwatar/java-design-patterns/blob/master/module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.java) should use a [temporary file](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createTempFile(java.nio.file.Path,%20java.lang.String,%20java.lang.String,%20java.nio.file.attribute.FileAttribute...))?
I've attached a diff for what it is worth: [diff.txt](https://github.com/iluwatar/java-design-patterns/files/2396099/diff.txt) | [
"module/error.txt",
"module/output.txt"
] | [
"module/.gitignore"
] | [] | diff --git a/module/.gitignore b/module/.gitignore
new file mode 100644
index 000000000000..ecfa5dd4617e
--- /dev/null
+++ b/module/.gitignore
@@ -0,0 +1,2 @@
+error.txt
+output.txt
diff --git a/module/error.txt b/module/error.txt
deleted file mode 100644
index ee28c3c1cf7e..000000000000
--- a/module/error.txt
+++ /dev/null
@@ -1,23 +0,0 @@
-====
- The MIT License
- Copyright (c) 2014 Ilkka Seppälä
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
-====
-
diff --git a/module/output.txt b/module/output.txt
deleted file mode 100644
index ee28c3c1cf7e..000000000000
--- a/module/output.txt
+++ /dev/null
@@ -1,23 +0,0 @@
-====
- The MIT License
- Copyright (c) 2014 Ilkka Seppälä
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
-====
-
| null | train | train | "2018-09-08T20:54:42" | "2018-09-19T08:24:24Z" | LyndonArmitage | train |
iluwatar/java-design-patterns/699_802 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/699 | iluwatar/java-design-patterns/802 | [
"keyword_pr_to_issue"
] | db33cc533bc1032cb36280653f53a18eb558e48b | f5eaf06c1c6b5f6e33a4315c1421def54c1dcae6 | [
"Ping @Rzeposlaw, care to investigate?",
"Why this is messy when I open the Travis log?",
"@iluwatar I would like to work on it :)",
"Ok @sharmin03 ",
"Flaky test disabled in https://github.com/iluwatar/java-design-patterns/commit/17ea0b17f68e6d20917dfd2937db28de83d9bf27. Still needs to be fixed."
] | [] | "2018-10-15T11:09:17Z" | [
"type: bug",
"epic: build issue"
] | Intermittent failure in Balking pattern | See Travis log https://api.travis-ci.org/v3/job/329176022/log.txt | [
"balking/src/main/java/com/iluwatar/balking/WashingMachine.java"
] | [
"balking/src/main/java/com/iluwatar/balking/DelayProvider.java",
"balking/src/main/java/com/iluwatar/balking/WashingMachine.java"
] | [
"balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java"
] | diff --git a/balking/src/main/java/com/iluwatar/balking/DelayProvider.java b/balking/src/main/java/com/iluwatar/balking/DelayProvider.java
new file mode 100644
index 000000000000..26b4f8936127
--- /dev/null
+++ b/balking/src/main/java/com/iluwatar/balking/DelayProvider.java
@@ -0,0 +1,10 @@
+package com.iluwatar.balking;
+
+import java.util.concurrent.TimeUnit;
+
+/**
+ * An interface to simulate delay while executing some work.
+ */
+public interface DelayProvider {
+ void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task);
+}
diff --git a/balking/src/main/java/com/iluwatar/balking/WashingMachine.java b/balking/src/main/java/com/iluwatar/balking/WashingMachine.java
index e4f1259add25..5aa39c66ca89 100644
--- a/balking/src/main/java/com/iluwatar/balking/WashingMachine.java
+++ b/balking/src/main/java/com/iluwatar/balking/WashingMachine.java
@@ -25,17 +25,38 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.util.concurrent.TimeUnit;
+
/**
* Washing machine class
*/
public class WashingMachine {
private static final Logger LOGGER = LoggerFactory.getLogger(WashingMachine.class);
-
+ private final DelayProvider delayProvider;
private WashingMachineState washingMachineState;
+ /**
+ * Creates a new instance of WashingMachine
+ */
public WashingMachine() {
- washingMachineState = WashingMachineState.ENABLED;
+ this((interval, timeUnit, task) -> {
+ try {
+ Thread.sleep(timeUnit.toMillis(interval));
+ } catch (InterruptedException ie) {
+ ie.printStackTrace();
+ }
+ task.run();
+ });
+ }
+
+ /**
+ * Creates a new instance of WashingMachine using provided delayProvider. This constructor is used only for
+ * unit testing purposes.
+ */
+ public WashingMachine(DelayProvider delayProvider) {
+ this.delayProvider = delayProvider;
+ this.washingMachineState = WashingMachineState.ENABLED;
}
public WashingMachineState getWashingMachineState() {
@@ -56,12 +77,8 @@ public void wash() {
washingMachineState = WashingMachineState.WASHING;
}
LOGGER.info("{}: Doing the washing", Thread.currentThread().getName());
- try {
- Thread.sleep(50);
- } catch (InterruptedException ie) {
- ie.printStackTrace();
- }
- endOfWashing();
+
+ this.delayProvider.executeAfterDelay(50, TimeUnit.MILLISECONDS, this::endOfWashing);
}
/**
| diff --git a/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java b/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java
index 9a13b8b2dcf4..100bf61a6341 100644
--- a/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java
+++ b/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java
@@ -22,11 +22,8 @@
*/
package com.iluwatar.balking;
-import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -36,32 +33,39 @@
*/
public class WashingMachineTest {
- private volatile WashingMachineState machineStateGlobal;
+ private FakeDelayProvider fakeDelayProvider = new FakeDelayProvider();
- @Disabled
@Test
- public void wash() throws Exception {
- WashingMachine washingMachine = new WashingMachine();
- ExecutorService executorService = Executors.newFixedThreadPool(2);
- executorService.execute(washingMachine::wash);
- executorService.execute(() -> {
- washingMachine.wash();
- machineStateGlobal = washingMachine.getWashingMachineState();
- });
- executorService.shutdown();
- try {
- executorService.awaitTermination(10, TimeUnit.SECONDS);
- } catch (InterruptedException ie) {
- ie.printStackTrace();
- }
+ public void wash() {
+ WashingMachine washingMachine = new WashingMachine(fakeDelayProvider);
+
+ washingMachine.wash();
+ washingMachine.wash();
+
+ WashingMachineState machineStateGlobal = washingMachine.getWashingMachineState();
+
+ fakeDelayProvider.task.run();
+
+ // washing machine remains in washing state
assertEquals(WashingMachineState.WASHING, machineStateGlobal);
+
+ // washing machine goes back to enabled state
+ assertEquals(WashingMachineState.ENABLED, washingMachine.getWashingMachineState());
}
@Test
- public void endOfWashing() throws Exception {
+ public void endOfWashing() {
WashingMachine washingMachine = new WashingMachine();
washingMachine.wash();
assertEquals(WashingMachineState.ENABLED, washingMachine.getWashingMachineState());
}
+ private class FakeDelayProvider implements DelayProvider {
+ private Runnable task;
+
+ @Override
+ public void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task) {
+ this.task = task;
+ }
+ }
}
\ No newline at end of file
| train | train | "2018-10-13T17:40:10" | "2018-01-16T19:21:59Z" | iluwatar | train |
iluwatar/java-design-patterns/562_828 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/562 | iluwatar/java-design-patterns/828 | [
"timestamp(timedelta=75.0, similarity=0.9301966998609539)"
] | 53b673d5b00192fd339e2db7e2fb55a554311a57 | a6749cb63e97cab38f7751ce2d164dfa9b4beb3b | [
"hi @iluwatar \r\nI'm willing to implement this pattern.",
"Ok @szoeke ",
"@szoeke This is pretty interesting pattern, please let me know if you need help in implementing/discussing this pattern.",
"This issue is free for taking again",
"@iluwatar I'll take a stab at this",
"Ok @danielsiwiec ",
"@danielsiwiec are you still implementing this?",
"@iluwatar sorry, no - I got side tracked into other things. Please take me off of it for the time being.",
"This issue is free for taking again",
"I'd like to try to implement this. This looks interesting. @iluwatar ",
"Ok @karmagamer ",
"@iluwatar I am on it. I will update you once I am finished,",
"@karmagamer please let me know if you need help with implementing or something with this pattern. I would love to help",
"@tliecau Sure buddy, so far it's coming along fine. I will update you in a week if I am stuck or need help.",
"Hi, is this done? \r\nI have been working on something for the last few days and it is working...if it's not done can I submit a PR?",
"@AnaghaSasikumar go ahead. My implementation is working but I haven't had time to follow the PR guidelines and re-write my implementation. ",
"Ok sure @karmagamer i'll give it a shot then 👍😀",
"PR #797\r\nUpdated: #828 "
] | [] | "2018-11-27T01:39:25Z" | [
"epic: pattern"
] | Spatial Partition pattern | http://gameprogrammingpatterns.com/spatial-partition.html | [
"pom.xml"
] | [
"pom.xml",
"spatial-partition/README.md",
"spatial-partition/pom.xml",
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java",
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java",
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java",
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java",
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/Rect.java",
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java",
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionGeneric.java"
] | [
"spatial-partition/src/test/java/com/iluwatar/spatialpartition/BubbleTest.java",
"spatial-partition/src/test/java/com/iluwatar/spatialpartition/QuadTreeTest.java",
"spatial-partition/src/test/java/com/iluwatar/spatialpartition/RectTest.java",
"spatial-partition/src/test/java/com/iluwatar/spatialpartition/SpatialPartitionBubblesTest.java"
] | diff --git a/pom.xml b/pom.xml
index 84cf41535a7a..d5aba817058c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -164,6 +164,7 @@
<module>ambassador</module>
<module>acyclic-visitor</module>
<module>collection-pipeline</module>
+ <module>spatial-partition</module>
</modules>
<repositories>
diff --git a/spatial-partition/README.md b/spatial-partition/README.md
new file mode 100644
index 000000000000..e4270e50b1e0
--- /dev/null
+++ b/spatial-partition/README.md
@@ -0,0 +1,54 @@
+---
+layout: pattern
+title: Spatial Partition
+folder: spatial-partition
+permalink: /patterns/spatial-partition/
+categories: Game Programming pattern/Optimisation pattern
+tags:
+ - Java
+ - Difficulty-Intermediate
+---
+
+## Intent
+As explained in the book [Game Programming Patterns](http://gameprogrammingpatterns.com/spatial-partition.html) by Bob Nystrom, spatial partition pattern helps to
+
+> efficiently locate objects by storing them in a data structure organized by their positions.
+
+## Applicability
+This pattern can be used:
+* When you need to keep track of a large number of objects' positions, which are getting updated every frame.
+* When it is acceptable to trade memory for speed, since creating and updating data structure will use up extra memory.
+
+## Explanation
+Say, you are building a war game with hundreds, or maybe even thousands of players, who are clashing on the battle field. Each player's position is getting updated every frame. The simple way to handle all interactions taking place on the field is to check each player's position against every other player's position:
+
+```java
+public void handleMeLee(Unit units[], int numUnits) {
+ for (int a = 0; a < numUnits - 1; a++)
+ {
+ for (int b = a + 1; b < numUnits; b++)
+ {
+ if (units[a].position() == units[b].position())
+ {
+ handleAttack(units[a], units[b]);
+ }
+ }
+ }
+}
+```
+
+This will include a lot of unnecessary checks between players which are too far apart to have any influence on each other. The nested loops gives this operation an O(n^2) complexity, which has to be performed every frame since many of the objects on the field may be moving each frame.
+The idea behind the Spatial Partition design pattern is to enable quick location of objects using a data structure that is organised by their positions, so when performing an operation like the one above, every object's position need not be checked against all other objects' positions. The data structure can be used to store moving and static objects, though in order to keep track of the moving objects, their positions will have to be reset each time they move. This would mean having to create a new instance of the data structure each time an object moves, which would use up additional memory. The common data structures used for this design pattern are:
+
+* Grid
+* Quad tree
+* k-d tree
+* BSP
+* Boundary volume hierarchy
+
+In our implementation, we use the Quadtree data structure which will reduce the time complexity of finding the objects within a certain range from O(n^2) to O(nlogn), decreasing the computations required significantly in case of large number of objects.
+
+## Credits
+* [Game Programming Patterns/Spatial Partition](http://gameprogrammingpatterns.com/spatial-partition.html) by Bob Nystrom
+* [Quadtree tutorial](https://www.youtube.com/watch?v=OJxEcs0w_kE) by Daniel Schiffman
+
diff --git a/spatial-partition/pom.xml b/spatial-partition/pom.xml
new file mode 100644
index 000000000000..4b42ea6c3220
--- /dev/null
+++ b/spatial-partition/pom.xml
@@ -0,0 +1,40 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <!--
+ The MIT License
+ Copyright (c) 2014-2016 Ilkka Seppälä
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+-->
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>java-design-patterns</artifactId>
+ <version>1.21.0-SNAPSHOT</version>
+ </parent>
+ <artifactId>spatial-partition</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java
new file mode 100644
index 000000000000..2928b41fe654
--- /dev/null
+++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java
@@ -0,0 +1,136 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.spatialpartition;
+
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.Random;
+
+/**
+ * <p>The idea behind the <b>Spatial Partition</b> design pattern is to enable efficient location of objects
+ * by storing them in a data structure that is organised by their positions. This is especially useful in the
+ * gaming world, where one may need to look up all the objects within a certain boundary, or near a certain
+ * other object, repeatedly. The data structure can be used to store moving and static objects, though in order
+ * to keep track of the moving objects, their positions will have to be reset each time they move. This would
+ * mean having to create a new instance of the data structure each frame, which would use up additional memory,
+ * and so this pattern should only be used if one does not mind trading memory for speed and the number of
+ * objects to keep track of is large to justify the use of the extra space.</p>
+ * <p>In our example, we use <b>{@link QuadTree} data structure</b> which divides into 4 (quad) sub-sections when
+ * the number of objects added to it exceeds a certain number (int field capacity). There is also a
+ * <b>{@link Rect}</b> class to define the boundary of the quadtree. We use an abstract class <b>{@link Point}</b>
+ * with x and y coordinate fields and also an id field so that it can easily be put and looked up in the hashtable.
+ * This class has abstract methods to define how the object moves (move()), when to check for collision with any
+ * object (touches(obj)) and how to handle collision (handleCollision(obj)), and will be extended by any object
+ * whose position has to be kept track of in the quadtree. The <b>{@link SpatialPartitionGeneric}</b> abstract class
+ * has 2 fields - a hashtable containing all objects (we use hashtable for faster lookups, insertion and deletion)
+ * and a quadtree, and contains an abstract method which defines how to handle interactions between objects using
+ * the quadtree.</p>
+ * <p>Using the quadtree data structure will reduce the time complexity of finding the objects within a
+ * certain range from <b>O(n^2) to O(nlogn)</b>, increasing the speed of computations immensely in case of
+ * large number of objects, which will have a positive effect on the rendering speed of the game.</p>
+ */
+
+public class App {
+
+ static void noSpatialPartition(int height, int width,
+ int numOfMovements, Hashtable<Integer, Bubble> bubbles) {
+ ArrayList<Point> bubblesToCheck = new ArrayList<Point>();
+ for (Enumeration<Integer> e = bubbles.keys(); e.hasMoreElements();) {
+ bubblesToCheck.add(bubbles.get(e.nextElement())); //all bubbles have to be checked for collision for all bubbles
+ }
+
+ //will run numOfMovement times or till all bubbles have popped
+ while (numOfMovements > 0 && !bubbles.isEmpty()) {
+ for (Enumeration<Integer> e = bubbles.keys(); e.hasMoreElements();) {
+ Integer i = e.nextElement();
+ //bubble moves, new position gets updated, collisions checked with all bubbles in bubblesToCheck
+ bubbles.get(i).move();
+ bubbles.replace(i, bubbles.get(i));
+ bubbles.get(i).handleCollision(bubblesToCheck, bubbles);
+ }
+ numOfMovements--;
+ }
+ for (Integer key : bubbles.keySet()) {
+ //bubbles not popped
+ System.out.println("Bubble " + key + " not popped");
+ }
+ }
+
+ static void withSpatialPartition(int height, int width,
+ int numOfMovements, Hashtable<Integer, Bubble> bubbles) {
+ //creating quadtree
+ Rect rect = new Rect(width / 2,height / 2,width,height);
+ QuadTree qTree = new QuadTree(rect, 4);
+
+ //will run numOfMovement times or till all bubbles have popped
+ while (numOfMovements > 0 && !bubbles.isEmpty()) {
+ //quadtree updated each time
+ for (Enumeration<Integer> e = bubbles.keys(); e.hasMoreElements();) {
+ qTree.insert(bubbles.get(e.nextElement()));
+ }
+ for (Enumeration<Integer> e = bubbles.keys(); e.hasMoreElements();) {
+ Integer i = e.nextElement();
+ //bubble moves, new position gets updated, quadtree used to reduce computations
+ bubbles.get(i).move();
+ bubbles.replace(i, bubbles.get(i));
+ SpatialPartitionBubbles sp = new SpatialPartitionBubbles(bubbles, qTree);
+ sp.handleCollisionsUsingQt(bubbles.get(i));
+ }
+ numOfMovements--;
+ }
+ for (Integer key : bubbles.keySet()) {
+ //bubbles not popped
+ System.out.println("Bubble " + key + " not popped");
+ }
+ }
+
+ /**
+ * Program entry point.
+ *
+ * @param args command line args
+ */
+
+ public static void main(String[] args) {
+ Hashtable<Integer, Bubble> bubbles1 = new Hashtable<Integer, Bubble>();
+ Hashtable<Integer, Bubble> bubbles2 = new Hashtable<Integer, Bubble>();
+ Random rand = new Random();
+ for (int i = 0; i < 10000; i++) {
+ Bubble b = new Bubble(rand.nextInt(300), rand.nextInt(300), i, rand.nextInt(2) + 1);
+ bubbles1.put(i, b);
+ bubbles2.put(i, b);
+ System.out.println("Bubble " + i + " with radius " + b.radius + " added at (" + b.x + "," + b.y + ")");
+ }
+
+ long start1 = System.currentTimeMillis();
+ App.noSpatialPartition(300,300,20,bubbles1);
+ long end1 = System.currentTimeMillis();
+ long start2 = System.currentTimeMillis();
+ App.withSpatialPartition(300,300,20,bubbles2);
+ long end2 = System.currentTimeMillis();
+ System.out.println("Without spatial partition takes " + (end1 - start1) + "ms");
+ System.out.println("With spatial partition takes " + (end2 - start2) + "ms");
+ }
+}
+
diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java
new file mode 100644
index 000000000000..ade1829adc19
--- /dev/null
+++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java
@@ -0,0 +1,77 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.spatialpartition;
+
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.Random;
+
+/**
+ * Bubble class extends Point. In this example, we create several bubbles in the field,
+ * let them move and keep track of which ones have popped and which ones remain.
+ */
+
+public class Bubble extends Point<Bubble> {
+
+ final int radius;
+
+ Bubble(int x, int y, int id, int radius) {
+ super(x,y,id);
+ this.radius = radius;
+ }
+
+ void move() {
+ Random rand = new Random();
+ //moves by 1 unit in either direction
+ this.x += rand.nextInt(3) - 1;
+ this.y += rand.nextInt(3) - 1;
+ }
+
+ boolean touches(Bubble b) {
+ //distance between them is greater than sum of radii (both sides of equation squared)
+ return (this.x - b.x) * (this.x - b.x) + (this.y - b.y) * (this.y - b.y)
+ <= (this.radius + b.radius) * (this.radius + b.radius);
+ }
+
+ void pop(Hashtable<Integer, Bubble> allBubbles) {
+ System.out.println("Bubble " + this.id + " popped at (" + this.x + "," + this.y + ")!");
+ allBubbles.remove(this.id);
+ }
+
+ void handleCollision(ArrayList<Point> bubblesToCheck, Hashtable<Integer, Bubble> allBubbles) {
+ boolean toBePopped = false; //if any other bubble collides with it, made true
+ for (int i = 0; i < bubblesToCheck.size(); i++) {
+ Integer otherId = bubblesToCheck.get(i).id;
+ if (allBubbles.get(otherId) != null && //the bubble hasn't been popped yet
+ this.id != otherId && //the two bubbles are not the same
+ this.touches(allBubbles.get(otherId))) { //the bubbles touch
+ allBubbles.get(otherId).pop(allBubbles);
+ toBePopped = true;
+ }
+ }
+ if (toBePopped) {
+ this.pop(allBubbles);
+ }
+ }
+}
diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java
new file mode 100644
index 000000000000..24553a6dd6a0
--- /dev/null
+++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java
@@ -0,0 +1,66 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.spatialpartition;
+
+import java.util.ArrayList;
+import java.util.Hashtable;
+
+/**
+ * The abstract Point class which will be extended by any object in the field
+ * whose location has to be kept track of. Defined by x,y coordinates and an id
+ * for easy hashing into hashtable.
+ * @param <T> T will be type subclass
+ */
+
+public abstract class Point<T> {
+
+ public int x;
+ public int y;
+ public final int id;
+
+ Point(int x, int y, int id) {
+ this.x = x;
+ this.y = y;
+ this.id = id;
+ }
+
+ /**
+ * defines how the object moves
+ */
+ abstract void move();
+
+ /**
+ * defines conditions for interacting with an object obj
+ * @param obj is another object on field which also extends Point
+ * @return whether the object can interact with the other or not
+ */
+ abstract boolean touches(T obj);
+
+ /**
+ * handling interactions/collisions with other objects
+ * @param pointsToCheck contains the objects which need to be checked
+ * @param allPoints contains hashtable of all points on field at this time
+ */
+ abstract void handleCollision(ArrayList<Point> pointsToCheck, Hashtable<Integer, T> allPoints);
+}
diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java
new file mode 100644
index 000000000000..072468ce80d4
--- /dev/null
+++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java
@@ -0,0 +1,115 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.spatialpartition;
+
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.Hashtable;
+
+/**
+ * The quadtree data structure is being used to keep track of the objects' locations.
+ * It has the insert(Point) and query(range) methods to insert a new object and find
+ * the objects within a certain (rectangular) range respectively.
+ */
+
+public class QuadTree {
+ Rect boundary;
+ int capacity;
+ boolean divided;
+ Hashtable<Integer, Point> points;
+ QuadTree northwest;
+ QuadTree northeast;
+ QuadTree southwest;
+ QuadTree southeast;
+
+ QuadTree(Rect boundary, int capacity) {
+ this.boundary = boundary;
+ this.capacity = capacity;
+ this.divided = false;
+ this.points = new Hashtable<Integer, Point>();
+ this.northwest = null;
+ this.northeast = null;
+ this.southwest = null;
+ this.southeast = null;
+ }
+
+ void insert(Point p) {
+ if (!this.boundary.contains(p)) {
+ return;
+ } else {
+ if (this.points.size() < this.capacity) {
+ points.put(p.id, p);
+ } else {
+ if (!this.divided) {
+ this.divide();
+ }
+
+ if (this.northwest.boundary.contains(p)) {
+ this.northwest.insert(p);
+ } else if (this.northeast.boundary.contains(p)) {
+ this.northeast.insert(p);
+ } else if (this.southwest.boundary.contains(p)) {
+ this.southwest.insert(p);
+ } else if (this.southeast.boundary.contains(p)) {
+ this.southeast.insert(p);
+ }
+ }
+ }
+ }
+
+ void divide() {
+ Rect nw = new Rect(this.boundary.x - this.boundary.width / 4, this.boundary.y + this.boundary.height / 4,
+ this.boundary.width / 2, this.boundary.height / 2);
+ this.northwest = new QuadTree(nw , this.capacity);
+ Rect ne = new Rect(this.boundary.x + this.boundary.width / 4, this.boundary.y + this.boundary.height / 4,
+ this.boundary.width / 2, this.boundary.height / 2);
+ this.northeast = new QuadTree(ne , this.capacity);
+ Rect sw = new Rect(this.boundary.x - this.boundary.width / 4, this.boundary.y - this.boundary.height / 4,
+ this.boundary.width / 2, this.boundary.height / 2);
+ this.southwest = new QuadTree(sw , this.capacity);
+ Rect se = new Rect(this.boundary.x + this.boundary.width / 4, this.boundary.y - this.boundary.height / 4,
+ this.boundary.width / 2, this.boundary.height / 2);
+ this.southeast = new QuadTree(se , this.capacity);
+ this.divided = true;
+ }
+
+ ArrayList<Point> query(Rect r, ArrayList<Point> relevantPoints) {
+ //could also be a circle instead of a rectangle
+ if (this.boundary.intersects(r)) {
+ for (Enumeration<Integer> e = this.points.keys(); e.hasMoreElements();) {
+ Integer i = e.nextElement();
+ if (r.contains(this.points.get(i))) {
+ relevantPoints.add(this.points.get(i));
+ }
+ }
+ if (this.divided) {
+ this.northwest.query(r, relevantPoints);
+ this.northeast.query(r, relevantPoints);
+ this.southwest.query(r, relevantPoints);
+ this.southeast.query(r, relevantPoints);
+ }
+ }
+ return relevantPoints;
+ }
+}
diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Rect.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Rect.java
new file mode 100644
index 000000000000..309d88ba183a
--- /dev/null
+++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Rect.java
@@ -0,0 +1,58 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.spatialpartition;
+
+/**
+ * The Rect class helps in defining the boundary of the quadtree and is also used to
+ * define the range within which objects need to be found in our example.
+ */
+
+public class Rect {
+ int x;
+ int y;
+ int width;
+ int height;
+
+ //(x,y) - centre of rectangle
+
+ Rect(int x, int y, int width, int height) {
+ this.x = x;
+ this.y = y;
+ this.width = width;
+ this.height = height;
+ }
+
+ boolean contains(Point p) {
+ return p.x >= this.x - this.width / 2 && p.x <= this.x + this.width / 2
+ && p.y >= this.y - this.height / 2 && p.y <= this.y + this.height / 2;
+ }
+
+ boolean intersects(Rect other) {
+ return !(this.x + this.width / 2 <= other.x - other.width / 2
+ || this.x - this.width / 2 >= other.x + other.width / 2
+ || this.y + this.height / 2 <= other.y - other.height / 2
+ || this.y - this.height / 2 >= other.y + other.height / 2);
+ }
+}
+
diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java
new file mode 100644
index 000000000000..ec10df78d283
--- /dev/null
+++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java
@@ -0,0 +1,52 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.spatialpartition;
+
+import java.util.ArrayList;
+import java.util.Hashtable;
+
+/**
+ * This class extends the generic SpatialPartition abstract class and is used in
+ * our example to keep track of all the bubbles that collide, pop and stay un-popped.
+ */
+
+public class SpatialPartitionBubbles extends SpatialPartitionGeneric<Bubble> {
+
+ Hashtable<Integer, Bubble> bubbles;
+ QuadTree qTree;
+
+ SpatialPartitionBubbles(Hashtable<Integer, Bubble> bubbles, QuadTree qTree) {
+ this.bubbles = bubbles;
+ this.qTree = qTree;
+ }
+
+ void handleCollisionsUsingQt(Bubble b) {
+ //finding points within area of a square drawn with centre same as centre of bubble and length = radius of bubble
+ Rect rect = new Rect(b.x, b.y, 2 * b.radius, 2 * b.radius);
+ ArrayList<Point> quadTreeQueryResult = new ArrayList<Point>();
+ this.qTree.query(rect, quadTreeQueryResult);
+ //handling these collisions
+ b.handleCollision(quadTreeQueryResult, this.bubbles);
+ }
+}
diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionGeneric.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionGeneric.java
new file mode 100644
index 000000000000..c09753553d41
--- /dev/null
+++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionGeneric.java
@@ -0,0 +1,44 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.spatialpartition;
+
+import java.util.Hashtable;
+
+/**
+ * This abstract class has 2 fields, one of which is a hashtable containing all objects
+ * that currently exist on the field and a quadtree which keeps track of locations.
+ * @param <T> T will be type of object (that extends Point)
+ */
+
+public abstract class SpatialPartitionGeneric<T> {
+
+ Hashtable<Integer, T> playerPositions;
+ QuadTree qTree;
+
+ /**
+ * handles collisions for object obj using quadtree
+ * @param obj is the object for which collisions need to be checked
+ */
+ abstract void handleCollisionsUsingQt(T obj);
+}
| diff --git a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/BubbleTest.java b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/BubbleTest.java
new file mode 100644
index 000000000000..ab6b6078fbf0
--- /dev/null
+++ b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/BubbleTest.java
@@ -0,0 +1,84 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Sepp�l�
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.spatialpartition;
+
+import static org.junit.jupiter.api.Assertions.*;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import org.junit.jupiter.api.Test;
+
+/**
+* Testing methods in Bubble class.
+*/
+
+class BubbleTest {
+
+ @Test
+ void moveTest() {
+ Bubble b = new Bubble(10,10,1,2);
+ int initialX = b.x;
+ int initialY = b.y;
+ b.move();
+ //change in x and y < |2|
+ assertTrue((b.x - initialX < 2 && b.x - initialX > -2) && (b.y - initialY < 2 && b.y - initialY > -2));
+ }
+
+ @Test
+ void touchesTest() {
+ Bubble b1 = new Bubble(0,0,1,2);
+ Bubble b2 = new Bubble(1,1,2,1);
+ Bubble b3 = new Bubble(10,10,3,1);
+ //b1 touches b2 but not b3
+ assertTrue(b1.touches(b2) && !b1.touches(b3));
+ }
+
+ @Test
+ void popTest() {
+ Bubble b1 = new Bubble(10,10,1,2);
+ Bubble b2 = new Bubble(0,0,2,2);
+ Hashtable<Integer, Bubble> bubbles = new Hashtable<Integer, Bubble>();
+ bubbles.put(1, b1);
+ bubbles.put(2, b2);
+ b1.pop(bubbles);
+ //after popping, bubble no longer in hashtable containing all bubbles
+ assertTrue(bubbles.get(1) == null && bubbles.get(2) != null);
+ }
+
+ @Test
+ void handleCollisionTest() {
+ Bubble b1 = new Bubble(0,0,1,2);
+ Bubble b2 = new Bubble(1,1,2,1);
+ Bubble b3 = new Bubble(10,10,3,1);
+ Hashtable<Integer, Bubble> bubbles = new Hashtable<Integer, Bubble>();
+ bubbles.put(1, b1);
+ bubbles.put(2, b2);
+ bubbles.put(3, b3);
+ ArrayList<Point> bubblesToCheck = new ArrayList<Point>();
+ bubblesToCheck.add(b2);
+ bubblesToCheck.add(b3);
+ b1.handleCollision(bubblesToCheck, bubbles);
+ //b1 touches b2 and not b3, so b1, b2 will be popped
+ assertTrue(bubbles.get(1) == null && bubbles.get(2) == null && bubbles.get(3) != null);
+ }
+}
diff --git a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/QuadTreeTest.java b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/QuadTreeTest.java
new file mode 100644
index 000000000000..3191af83b3fc
--- /dev/null
+++ b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/QuadTreeTest.java
@@ -0,0 +1,77 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Sepp�l�
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.spatialpartition;
+
+import static org.junit.jupiter.api.Assertions.*;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.Random;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Testing QuadTree class.
+ */
+
+class QuadTreeTest {
+
+ @Test
+ void queryTest() {
+ ArrayList<Point> points = new ArrayList<Point>();
+ Random rand = new Random();
+ for (int i = 0; i < 20; i++) {
+ Bubble p = new Bubble(rand.nextInt(300), rand.nextInt(300), i, rand.nextInt(2) + 1);
+ points.add(p);
+ }
+ Rect field = new Rect(150,150,300,300); //size of field
+ Rect queryRange = new Rect(70,130,100,100); //result = all points lying in this rectangle
+ //points found in the query range using quadtree and normal method is same
+ assertTrue(QuadTreeTest.quadTreeTest(points, field, queryRange).equals(QuadTreeTest.verify(points, queryRange)));
+ }
+
+ static Hashtable<Integer, Point> quadTreeTest(ArrayList<Point> points, Rect field, Rect queryRange) {
+ //creating quadtree and inserting all points
+ QuadTree qTree = new QuadTree(field, 4);
+ for (int i = 0; i < points.size(); i++) {
+ qTree.insert(points.get(i));
+ }
+
+ ArrayList<Point> queryResult = qTree.query(queryRange, new ArrayList<Point>());
+ Hashtable<Integer, Point> result = new Hashtable<Integer, Point>();
+ for (int i = 0; i < queryResult.size(); i++) {
+ Point p = queryResult.get(i);
+ result.put(p.id, p);
+ }
+ return result;
+ }
+
+ static Hashtable<Integer, Point> verify(ArrayList<Point> points, Rect queryRange) {
+ Hashtable<Integer, Point> result = new Hashtable<Integer, Point>();
+ for (int i = 0; i < points.size(); i++) {
+ if (queryRange.contains(points.get(i))) {
+ result.put(points.get(i).id, points.get(i));
+ }
+ }
+ return result;
+ }
+}
diff --git a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/RectTest.java b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/RectTest.java
new file mode 100644
index 000000000000..c85254b5c383
--- /dev/null
+++ b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/RectTest.java
@@ -0,0 +1,52 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Sepp�l�
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.spatialpartition;
+
+import static org.junit.jupiter.api.Assertions.*;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Testing Rect class.
+ */
+
+class RectTest {
+
+ @Test
+ void containsTest() {
+ Rect r = new Rect(10,10,20,20);
+ Bubble b1 = new Bubble(2,2,1,1);
+ Bubble b2 = new Bubble(30,30,2,1);
+ //r contains b1 and not b2
+ assertTrue(r.contains(b1) && !r.contains(b2));
+ }
+
+ @Test
+ void intersectsTest() {
+ Rect r1 = new Rect(10,10,20,20);
+ Rect r2 = new Rect(15,15,20,20);
+ Rect r3 = new Rect(50,50,20,20);
+ //r1 intersects r2 and not r3
+ assertTrue(r1.intersects(r2) && !r1.intersects(r3));
+ }
+}
diff --git a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/SpatialPartitionBubblesTest.java b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/SpatialPartitionBubblesTest.java
new file mode 100644
index 000000000000..4f37e2f86fc9
--- /dev/null
+++ b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/SpatialPartitionBubblesTest.java
@@ -0,0 +1,58 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Sepp�l�
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.spatialpartition;
+
+import static org.junit.jupiter.api.Assertions.*;
+import java.util.Hashtable;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Testing SpatialPartition_Bubbles class.
+ */
+
+class SpatialPartitionBubblesTest {
+
+ @Test
+ void handleCollisionsUsingQtTest() {
+ Bubble b1 = new Bubble(10,10,1,3);
+ Bubble b2 = new Bubble(5,5,2,1);
+ Bubble b3 = new Bubble(9,9,3,1);
+ Bubble b4 = new Bubble(8,8,4,2);
+ Hashtable<Integer, Bubble> bubbles = new Hashtable<Integer, Bubble>();
+ bubbles.put(1, b1);
+ bubbles.put(2, b2);
+ bubbles.put(3, b3);
+ bubbles.put(4, b4);
+ Rect r = new Rect(10,10,20,20);
+ QuadTree qt = new QuadTree(r,4);
+ qt.insert(b1);
+ qt.insert(b2);
+ qt.insert(b3);
+ qt.insert(b4);
+ SpatialPartitionBubbles sp = new SpatialPartitionBubbles(bubbles, qt);
+ sp.handleCollisionsUsingQt(b1);
+ //b1 touches b3 and b4 but not b2 - so b1,b3,b4 get popped
+ assertTrue(bubbles.get(1) == null && bubbles.get(2) != null && bubbles.get(3) == null && bubbles.get(4) == null);
+ }
+}
| val | train | "2018-11-25T18:35:22" | "2017-04-01T08:58:10Z" | iluwatar | train |
iluwatar/java-design-patterns/775_829 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/775 | iluwatar/java-design-patterns/829 | [
"timestamp(timedelta=64.0, similarity=0.8490796066626536)"
] | 53b673d5b00192fd339e2db7e2fb55a554311a57 | 10cb191533e4b1c48f8827f481cde4b563ae00d2 | [
"Yes, I agree. Go ahead @awesomefei ",
"Hi, is this done?",
"Created pull request #797 in case it's still needed. I am new to open source, would really appreciate any feedback. I used this source to do it: https://cloud.google.com/storage/docs/exponential-backoff\r\nUpdated: #829 "
] | [] | "2018-12-01T12:24:36Z" | [
"type: enhancement"
] | Implement Retry pattern with exponential backoff | In practice, we often retry with exponential backoff to avoid making traffic congestion/server load worse, would be nice to implement this option.
Also, I would like to implement this. | [
"retry/src/main/java/com/iluwatar/retry/App.java"
] | [
"retry/src/main/java/com/iluwatar/retry/App.java",
"retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java"
] | [
"retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java"
] | diff --git a/retry/src/main/java/com/iluwatar/retry/App.java b/retry/src/main/java/com/iluwatar/retry/App.java
index 376a64fbff97..20205bdf3973 100644
--- a/retry/src/main/java/com/iluwatar/retry/App.java
+++ b/retry/src/main/java/com/iluwatar/retry/App.java
@@ -71,6 +71,7 @@ public static void main(String[] args) throws Exception {
noErrors();
errorNoRetry();
errorWithRetry();
+ errorWithRetryExponentialBackoff();
}
private static void noErrors() throws Exception {
@@ -102,4 +103,19 @@ private static void errorWithRetry() throws Exception {
+ "the result %s after a number of attempts %s", customerId, retry.attempts()
));
}
+
+ private static void errorWithRetryExponentialBackoff() throws Exception {
+ final RetryExponentialBackoff<String> retry = new RetryExponentialBackoff<>(
+ new FindCustomer("123", new CustomerNotFoundException("not found")),
+ 6, //6 attempts
+ 30000, //30 s max delay between attempts
+ e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass())
+ );
+ op = retry;
+ final String customerId = op.perform();
+ LOG.info(String.format(
+ "However, retrying the operation while ignoring a recoverable error will eventually yield "
+ + "the result %s after a number of attempts %s", customerId, retry.attempts()
+ ));
+ }
}
diff --git a/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java b/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java
new file mode 100644
index 000000000000..b24bebbce192
--- /dev/null
+++ b/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java
@@ -0,0 +1,115 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package com.iluwatar.retry;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Predicate;
+
+/**
+ * Decorates {@link BusinessOperation business operation} with "retry" capabilities.
+ *
+ * @author George Aristy (george.aristy@gmail.com)
+ * @param <T> the remote op's return type
+ */
+public final class RetryExponentialBackoff<T> implements BusinessOperation<T> {
+ private final BusinessOperation<T> op;
+ private final int maxAttempts;
+ private final long maxDelay;
+ private final AtomicInteger attempts;
+ private final Predicate<Exception> test;
+ private final List<Exception> errors;
+
+ /**
+ * Ctor.
+ *
+ * @param op the {@link BusinessOperation} to retry
+ * @param maxAttempts number of times to retry
+ * @param ignoreTests tests to check whether the remote exception can be ignored. No exceptions
+ * will be ignored if no tests are given
+ */
+ @SafeVarargs
+ public RetryExponentialBackoff(
+ BusinessOperation<T> op,
+ int maxAttempts,
+ long maxDelay,
+ Predicate<Exception>... ignoreTests
+ ) {
+ this.op = op;
+ this.maxAttempts = maxAttempts;
+ this.maxDelay = maxDelay;
+ this.attempts = new AtomicInteger();
+ this.test = Arrays.stream(ignoreTests).reduce(Predicate::or).orElse(e -> false);
+ this.errors = new ArrayList<>();
+ }
+
+ /**
+ * The errors encountered while retrying, in the encounter order.
+ *
+ * @return the errors encountered while retrying
+ */
+ public List<Exception> errors() {
+ return Collections.unmodifiableList(this.errors);
+ }
+
+ /**
+ * The number of retries performed.
+ *
+ * @return the number of retries performed
+ */
+ public int attempts() {
+ return this.attempts.intValue();
+ }
+
+ @Override
+ public T perform() throws BusinessException {
+ do {
+ try {
+ return this.op.perform();
+ } catch (BusinessException e) {
+ this.errors.add(e);
+
+ if (this.attempts.incrementAndGet() >= this.maxAttempts || !this.test.test(e)) {
+ throw e;
+ }
+
+ try {
+ Random rand = new Random();
+ long testDelay = (long) Math.pow(2, this.attempts()) * 1000 + rand.nextInt(1000);
+ long delay = testDelay < this.maxDelay ? testDelay : maxDelay;
+ Thread.sleep(delay);
+ } catch (InterruptedException f) {
+ //ignore
+ }
+ }
+ }
+ while (true);
+ }
+}
+
| diff --git a/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java b/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java
new file mode 100644
index 000000000000..d14b1eef68a6
--- /dev/null
+++ b/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java
@@ -0,0 +1,115 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package com.iluwatar.retry;
+
+import org.junit.jupiter.api.Test;
+import static org.hamcrest.CoreMatchers.hasItem;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+/**
+ * Unit tests for {@link Retry}.
+ *
+ * @author George Aristy (george.aristy@gmail.com)
+ */
+public class RetryExponentialBackoffTest {
+ /**
+ * Should contain all errors thrown.
+ */
+ @Test
+ public void errors() throws Exception {
+ final BusinessException e = new BusinessException("unhandled");
+ final RetryExponentialBackoff<String> retry = new RetryExponentialBackoff<>(
+ () -> {
+ throw e;
+ },
+ 2,
+ 0
+ );
+ try {
+ retry.perform();
+ } catch (BusinessException ex) {
+ //ignore
+ }
+
+ assertThat(
+ retry.errors(),
+ hasItem(e)
+ );
+ }
+
+ /**
+ * No exceptions will be ignored, hence final number of attempts should be 1 even if we're asking
+ * it to attempt twice.
+ */
+ @Test
+ public void attempts() {
+ final BusinessException e = new BusinessException("unhandled");
+ final RetryExponentialBackoff<String> retry = new RetryExponentialBackoff<>(
+ () -> {
+ throw e;
+ },
+ 2,
+ 0
+ );
+ try {
+ retry.perform();
+ } catch (BusinessException ex) {
+ //ignore
+ }
+
+ assertThat(
+ retry.attempts(),
+ is(1)
+ );
+ }
+
+ /**
+ * Final number of attempts should be equal to the number of attempts asked because we are
+ * asking it to ignore the exception that will be thrown.
+ */
+ @Test
+ public void ignore() throws Exception {
+ final BusinessException e = new CustomerNotFoundException("customer not found");
+ final RetryExponentialBackoff<String> retry = new RetryExponentialBackoff<>(
+ () -> {
+ throw e;
+ },
+ 2,
+ 0,
+ ex -> CustomerNotFoundException.class.isAssignableFrom(ex.getClass())
+ );
+ try {
+ retry.perform();
+ } catch (BusinessException ex) {
+ //ignore
+ }
+
+ assertThat(
+ retry.attempts(),
+ is(2)
+ );
+ }
+}
| train | train | "2018-11-25T18:35:22" | "2018-07-18T18:40:23Z" | awesomefei | train |
iluwatar/java-design-patterns/555_848 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/555 | iluwatar/java-design-patterns/848 | [
"timestamp(timedelta=80.0, similarity=0.8931129968109979)"
] | 55c75799831716b6248ceefa1315881e7f90806b | 0c6237c225584a3a28bdd81cb19a40de698ed7f7 | [
"Hello @iluwatar I would like to take this pattern. Thanks!",
"Ok @Imp92 ",
"This issue is free for taking again",
"Hey, @iluwatar I would like to take this pattern. Thanks.",
"@laubera ok",
"@laubera are you still implementing this?",
"PR #848 "
] | [
"does `start` and `end` both needs to current milliseconds?",
"same here. `start` and `end` are essentially the same.",
"It's needed so that we can enter into while loop"
] | "2019-02-09T07:20:53Z" | [
"epic: pattern"
] | Type Object pattern | http://gameprogrammingpatterns.com/type-object.html | [
"pom.xml"
] | [
"pom.xml",
"typeobjectpattern/README.md",
"typeobjectpattern/pom.xml",
"typeobjectpattern/src/main/java/com/iluwatar/typeobject/App.java",
"typeobjectpattern/src/main/java/com/iluwatar/typeobject/Candy.java",
"typeobjectpattern/src/main/java/com/iluwatar/typeobject/CandyGame.java",
"typeobjectpattern/src/main/java/com/iluwatar/typeobject/Cell.java",
"typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java",
"typeobjectpattern/src/main/java/com/iluwatar/typeobject/JsonParser.java",
"typeobjectpattern/src/main/java/com/iluwatar/typeobject/candy.json"
] | [
"typeobjectpattern/src/test/java/com/iluwatar/typeobject/CandyGameTest.java",
"typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellPoolTest.java",
"typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellTest.java"
] | diff --git a/pom.xml b/pom.xml
index d5aba817058c..990a5a325cff 100644
--- a/pom.xml
+++ b/pom.xml
@@ -165,6 +165,7 @@
<module>acyclic-visitor</module>
<module>collection-pipeline</module>
<module>spatial-partition</module>
+ <module>typeobjectpattern</module>
</modules>
<repositories>
diff --git a/typeobjectpattern/README.md b/typeobjectpattern/README.md
new file mode 100644
index 000000000000..97aa64e0b603
--- /dev/null
+++ b/typeobjectpattern/README.md
@@ -0,0 +1,29 @@
+---
+layout: pattern
+title: Type-object
+folder: typeobjectpattern
+permalink: /patterns/typeobjectpattern/
+categories: Game Programming Patterns/Behavioral Patterns
+tags:
+ - Java
+ - Difficulty-Beginner
+---
+
+## Intent
+As explained in the book Game Programming Patterns by Robert Nystrom, type object pattern helps in
+
+> Allowing flexible creation of new “classes” by creating a single class, each instance of which represents a different type of object
+
+## Applicability
+This pattern can be used when:
+* We don’t know what types we will need up front.
+* We want to be able to modify or add new types without having to recompile or change code.
+* Only difference between the different 'types' of objects is the data, not the behaviour.
+
+## Explanation
+Say, we are working on a game which has a hero and many monsters which are going to attack the hero. These monsters have certain attributes like attack, points etc. and come in different 'breeds' like zombie or ogres. The obvious answer is to have a base Monster class which has some fields and methods, which may be overriden by subclasses like the Zombie or Ogre class. But as we continue to build the game, there may be more and more breeds of monsters added and certain attributes may need to be changed in the existing monsters too. The OOP solution of inheriting from the base class would not be an efficient method in this case.
+Using the type-object pattern, instead of creating many classes inheriting from a base class, we have 1 class with a field which represents the 'type' of object. This makes the code cleaner and object instantiation also becomes as easy as parsing a json file with the object properties.
+
+## Credits
+* [Game Programming Patterns/Type Object](http://gameprogrammingpatterns.com/type-object.html) by Robert Nystrom
+* [http://www.cs.sjsu.edu/~pearce/modules/patterns/analysis/top.htm]
diff --git a/typeobjectpattern/pom.xml b/typeobjectpattern/pom.xml
new file mode 100644
index 000000000000..3377245f30ba
--- /dev/null
+++ b/typeobjectpattern/pom.xml
@@ -0,0 +1,31 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>java-design-patterns</artifactId>
+ <version>1.21.0-SNAPSHOT</version>
+ </parent>
+ <artifactId>typeobjectpattern</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>com.googlecode.json-simple</groupId>
+ <artifactId>json-simple</artifactId>
+ <version>1.1.1</version>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
\ No newline at end of file
diff --git a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/App.java b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/App.java
new file mode 100644
index 000000000000..f16777c686a3
--- /dev/null
+++ b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/App.java
@@ -0,0 +1,85 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.typeobject;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import org.json.simple.parser.ParseException;
+
+/**<p>Type object pattern is the pattern we use when the OOP concept of creating a base class and
+ * inheriting from it just doesn't work for the case in hand. This happens when we either don't know
+ * what types we will need upfront, or want to be able to modify or add new types conveniently w/o
+ * recompiling repeatedly. The pattern provides a solution by allowing flexible creation of required
+ * objects by creating one class, which has a field which represents the 'type' of the object.</p>
+ * <p>In this example, we have a mini candy-crush game in action. There are many different candies
+ * in the game, which may change over time, as we may want to upgrade the game. To make the object
+ * creation convenient, we have a class {@link Candy} which has a field name, parent, points and
+ * Type. We have a json file {@link candy} which contains the details about the candies, and this is
+ * parsed to get all the different candies in {@link JsonParser}. The {@link Cell} class is what the
+ * game matrix is made of, which has the candies that are to be crushed, and contains information on
+ * how crushing can be done, how the matrix is to be reconfigured and how points are to be gained.
+ * The {@link CellPool} class is a pool which reuses the candy cells that have been crushed instead
+ * of making new ones repeatedly. The {@link CandyGame} class has the rules for the continuation of
+ * the game and the {@link App} class has the game itself.</p>
+ */
+
+public class App {
+
+ /**
+ * Program entry point.
+ * @param args command line args
+ */
+ public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {
+ int givenTime = 50; //50ms
+ int toWin = 500; //points
+ int pointsWon = 0;
+ int numOfRows = 3;
+ long start = System.currentTimeMillis();
+ long end = System.currentTimeMillis();
+ int round = 0;
+ while (pointsWon < toWin && end - start < givenTime) {
+ round++;
+ CellPool pool = new CellPool(numOfRows * numOfRows + 5);
+ CandyGame cg = new CandyGame(numOfRows, pool);
+ if (round > 1) {
+ System.out.println("Refreshing..");
+ } else {
+ System.out.println("Starting game..");
+ }
+ cg.printGameStatus();
+ end = System.currentTimeMillis();
+ cg.round((int)(end - start), givenTime);
+ pointsWon += cg.totalPoints;
+ end = System.currentTimeMillis();
+ }
+ System.out.println("Game Over");
+ if (pointsWon >= toWin) {
+ System.out.println(pointsWon);
+ System.out.println("You win!!");
+ } else {
+ System.out.println(pointsWon);
+ System.out.println("Sorry, you lose!");
+ }
+ }
+}
diff --git a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/Candy.java b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/Candy.java
new file mode 100644
index 000000000000..40b276e5bbc5
--- /dev/null
+++ b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/Candy.java
@@ -0,0 +1,60 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.typeobject;
+
+/**
+ * The Candy class has a field type, which represents the 'type' of candy. The objects
+ * are created by parsing the candy.json file.
+ */
+
+public class Candy {
+
+ enum Type { crushableCandy, rewardFruit };
+
+ String name;
+ Candy parent;
+ String parentName;
+ private int points;
+ private Type type;
+
+ Candy(String name, String parentName, Type type, int points) {
+ this.name = name;
+ this.parent = null;
+ this.type = type;
+ this.points = points;
+ this.parentName = parentName;
+ }
+
+ int getPoints() {
+ return this.points;
+ }
+
+ void setPoints(int a) {
+ this.points = a;
+ }
+
+ Type getType() {
+ return this.type;
+ }
+}
diff --git a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CandyGame.java b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CandyGame.java
new file mode 100644
index 000000000000..a2ba452ec03a
--- /dev/null
+++ b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CandyGame.java
@@ -0,0 +1,171 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.typeobject;
+
+import java.util.ArrayList;
+import com.iluwatar.typeobject.Candy.Type;
+
+/**
+ * The CandyGame class contains the rules for the continuation of the game and has
+ * the game matrix (field 'cells') and totalPoints gained during the game.
+ */
+
+public class CandyGame {
+ Cell[][] cells;
+ CellPool pool;
+ int totalPoints;
+
+ CandyGame(int num, CellPool pool) {
+ this.cells = new Cell[num][num];
+ this.pool = pool;
+ this.totalPoints = 0;
+ for (int i = 0; i < num; i++) {
+ for (int j = 0; j < num; j++) {
+ this.cells[i][j] = this.pool.getNewCell();
+ this.cells[i][j].xIndex = j;
+ this.cells[i][j].yIndex = i;
+ }
+ }
+ }
+
+ static String numOfSpaces(int num) {
+ String result = "";
+ for (int i = 0; i < num; i++) {
+ result += " ";
+ }
+ return result;
+ }
+
+ void printGameStatus() {
+ System.out.println("");
+ for (int i = 0; i < cells.length; i++) {
+ for (int j = 0; j < cells.length; j++) {
+ String candyName = cells[i][j].candy.name;
+ if (candyName.length() < 20) {
+ int totalSpaces = 20 - candyName.length();
+ System.out.print(numOfSpaces(totalSpaces / 2) + cells[i][j].candy.name
+ + numOfSpaces(totalSpaces - totalSpaces / 2) + "|");
+ } else {
+ System.out.print(candyName + "|");
+ }
+ }
+ System.out.println("");
+ }
+ System.out.println("");
+ }
+
+ ArrayList<Cell> adjacentCells(int yIndex, int xIndex) {
+ ArrayList<Cell> adjacent = new ArrayList<Cell>();
+ if (yIndex == 0) {
+ adjacent.add(this.cells[1][xIndex]);
+ }
+ if (xIndex == 0) {
+ adjacent.add(this.cells[yIndex][1]);
+ }
+ if (yIndex == cells.length - 1) {
+ adjacent.add(this.cells[cells.length - 2][xIndex]);
+ }
+ if (xIndex == cells.length - 1) {
+ adjacent.add(this.cells[yIndex][cells.length - 2]);
+ }
+ if (yIndex > 0 && yIndex < cells.length - 1) {
+ adjacent.add(this.cells[yIndex - 1][xIndex]);
+ adjacent.add(this.cells[yIndex + 1][xIndex]);
+ }
+ if (xIndex > 0 && xIndex < cells.length - 1) {
+ adjacent.add(this.cells[yIndex][xIndex - 1]);
+ adjacent.add(this.cells[yIndex][xIndex + 1]);
+ }
+ return adjacent;
+ }
+
+ boolean continueRound() {
+ for (int i = 0; i < this.cells.length; i++) {
+ if (this.cells[cells.length - 1][i].candy.getType().equals(Type.rewardFruit)) {
+ return true;
+ }
+ }
+ for (int i = 0; i < this.cells.length; i++) {
+ for (int j = 0; j < this.cells.length; j++) {
+ if (!this.cells[i][j].candy.getType().equals(Type.rewardFruit)) {
+ ArrayList<Cell> adj = adjacentCells(i,j);
+ for (int a = 0; a < adj.size(); a++) {
+ if (this.cells[i][j].candy.name.equals(adj.get(a).candy.name)) {
+ return true;
+ }
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ void handleChange(int points) {
+ System.out.println("+" + points + " points!");
+ this.totalPoints += points;
+ printGameStatus();
+ }
+
+ void round(int timeSoFar, int totalTime) {
+ long start = System.currentTimeMillis();
+ long end = System.currentTimeMillis();
+ while (end - start + timeSoFar < totalTime && continueRound()) {
+ for (int i = 0; i < this.cells.length; i++) {
+ int points = 0;
+ int j = this.cells.length - 1;
+ while (this.cells[j][i].candy.getType().equals(Type.rewardFruit)) {
+ points = this.cells[j][i].candy.getPoints();
+ this.cells[j][i].crush(pool, this.cells);
+ handleChange(points);
+ }
+ }
+ for (int i = 0; i < this.cells.length; i++) {
+ int j = cells.length - 1;
+ int points = 0;
+ while (j > 0) {
+ points = this.cells[j][i].interact(this.cells[j - 1][i], this.pool, this.cells);
+ if (points != 0) {
+ handleChange(points);
+ } else {
+ j = j - 1;
+ }
+ }
+ }
+ for (int i = 0; i < this.cells.length; i++) {
+ int j = 0;
+ int points = 0;
+ while (j < cells.length - 1) {
+ points = this.cells[i][j].interact(this.cells[i][j + 1], this.pool, this.cells);
+ if (points != 0) {
+ handleChange(points);
+ } else {
+ j = j + 1;
+ }
+ }
+ }
+ end = System.currentTimeMillis();
+ }
+ }
+
+}
diff --git a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/Cell.java b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/Cell.java
new file mode 100644
index 000000000000..7d0d696430fd
--- /dev/null
+++ b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/Cell.java
@@ -0,0 +1,90 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.typeobject;
+
+import com.iluwatar.typeobject.Candy.Type;
+
+/**
+ * The Cell object is what the game matrix is made of and contains the candy which is
+ * to be crushed or collected as reward.
+ */
+
+public class Cell {
+ Candy candy;
+ int xIndex;
+ int yIndex;
+
+ Cell(Candy candy, int xIndex, int yIndex) {
+ this.candy = candy;
+ this.xIndex = xIndex;
+ this.yIndex = yIndex;
+ }
+
+ Cell() {
+ this.candy = null;
+ this.xIndex = 0;
+ this.yIndex = 0;
+ }
+
+ void crush(CellPool pool, Cell[][] cellMatrix) {
+ //take out from this position and put back in pool
+ pool.addNewCell(this);
+ this.fillThisSpace(pool, cellMatrix);
+ }
+
+ void fillThisSpace(CellPool pool, Cell[][] cellMatrix) {
+ for (int y = this.yIndex; y > 0; y--) {
+ cellMatrix[y][this.xIndex] = cellMatrix[y - 1][this.xIndex];
+ cellMatrix[y][this.xIndex].yIndex = y;
+ }
+ Cell newC = pool.getNewCell();
+ cellMatrix[0][this.xIndex] = newC;
+ cellMatrix[0][this.xIndex].xIndex = this.xIndex;
+ cellMatrix[0][this.xIndex].yIndex = 0;
+ }
+
+ void handleCrush(Cell c, CellPool pool, Cell[][] cellMatrix) {
+ if (this.yIndex >= c.yIndex) {
+ this.crush(pool, cellMatrix);
+ c.crush(pool, cellMatrix);
+ } else {
+ c.crush(pool, cellMatrix);
+ this.crush(pool, cellMatrix);
+ }
+ }
+
+ int interact(Cell c, CellPool pool, Cell[][] cellMatrix) {
+ if (this.candy.getType().equals(Type.rewardFruit) || c.candy.getType().equals(Type.rewardFruit)) {
+ return 0;
+ } else {
+ if (this.candy.name.equals(c.candy.name)) {
+ int pointsWon = this.candy.getPoints() + c.candy.getPoints();
+ handleCrush(c,pool,cellMatrix);
+ return pointsWon;
+ } else {
+ return 0;
+ }
+ }
+ }
+}
diff --git a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java
new file mode 100644
index 000000000000..88263ceab57d
--- /dev/null
+++ b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java
@@ -0,0 +1,96 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.typeobject;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.Random;
+import org.json.simple.parser.ParseException;
+import com.iluwatar.typeobject.Candy.Type;
+
+/**
+ * The CellPool class allows the reuse of crushed cells instead of creation of new
+ * cells each time. The reused cell is given a new candy to hold using the randomCode
+ * field which holds all the candies available.
+ */
+
+public class CellPool {
+ ArrayList<Cell> pool;
+ int pointer;
+ Candy[] randomCode;
+
+ CellPool(int num) {
+ this.pool = new ArrayList<Cell>(num);
+ try {
+ this.randomCode = assignRandomCandytypes();
+ } catch (Exception e) {
+ e.printStackTrace();
+ //manually initialising this.randomCode
+ this.randomCode = new Candy[5];
+ randomCode[0] = new Candy("cherry", "fruit", Type.rewardFruit, 20);
+ randomCode[1] = new Candy("mango", "fruit", Type.rewardFruit, 20);
+ randomCode[2] = new Candy("purple popsicle", "candy", Type.crushableCandy, 10);
+ randomCode[3] = new Candy("green jellybean", "candy", Type.crushableCandy, 10);
+ randomCode[4] = new Candy("orange gum", "candy", Type.crushableCandy, 10);
+ }
+ for (int i = 0; i < num; i++) {
+ Cell c = new Cell();
+ Random rand = new Random();
+ c.candy = randomCode[rand.nextInt(randomCode.length)];
+ this.pool.add(c);
+ }
+ this.pointer = num - 1;
+ }
+
+ Cell getNewCell() {
+ Cell newCell = this.pool.remove(pointer);
+ pointer--;
+ return newCell;
+ }
+
+ void addNewCell(Cell c) {
+ Random rand = new Random();
+ c.candy = randomCode[rand.nextInt(randomCode.length)]; //changing candytype to new
+ this.pool.add(c);
+ pointer++;
+ }
+
+ Candy[] assignRandomCandytypes() throws FileNotFoundException, IOException, ParseException {
+ JsonParser jp = new JsonParser();
+ jp.parse();
+ Candy[] randomCode = new Candy[jp.candies.size() - 2]; //exclude generic types 'fruit' and 'candy'
+ int i = 0;
+ for (Enumeration<String> e = jp.candies.keys(); e.hasMoreElements();) {
+ String s = e.nextElement();
+ if (!s.equals("fruit") && !s.equals("candy")) {
+ //not generic
+ randomCode[i] = jp.candies.get(s);
+ i++;
+ }
+ }
+ return randomCode;
+ }
+}
diff --git a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/JsonParser.java b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/JsonParser.java
new file mode 100644
index 000000000000..6c6bfa616a34
--- /dev/null
+++ b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/JsonParser.java
@@ -0,0 +1,87 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.typeobject;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.json.simple.parser.JSONParser;
+import org.json.simple.parser.ParseException;
+import com.iluwatar.typeobject.Candy.Type;
+
+/**
+ * The JsonParser class helps parse the json file candy.json to get all the
+ * different candies.
+ */
+
+public class JsonParser {
+ Hashtable<String, Candy> candies;
+
+ JsonParser() {
+ this.candies = new Hashtable<String, Candy>();
+ }
+
+ void parse() throws FileNotFoundException, IOException, ParseException {
+ JSONParser parser = new JSONParser();
+ JSONObject jo = (JSONObject) parser.parse(new FileReader(new File("").getAbsolutePath()
+ + "\\src\\main\\java\\com\\iluwatar\\typeobject\\candy.json"));
+ JSONArray a = (JSONArray) jo.get("candies");
+ for (Object o : a) {
+ JSONObject candy = (JSONObject) o;
+ String name = (String) candy.get("name");
+ String parentName = (String) candy.get("parent");
+ String t = (String) candy.get("type");
+ Type type = null;
+ if (t.equals("rewardFruit")) {
+ type = Type.rewardFruit;
+ } else {
+ type = Type.crushableCandy;
+ }
+ int points = Integer.parseInt((String) candy.get("points"));
+ Candy c = new Candy(name, parentName, type, points);
+ this.candies.put(name, c);
+ }
+ setParentAndPoints();
+ }
+
+ void setParentAndPoints() {
+ for (Enumeration<String> e = this.candies.keys(); e.hasMoreElements();) {
+ Candy c = this.candies.get(e.nextElement());
+ if (c.parentName == null) {
+ c.parent = null;
+ } else {
+ c.parent = this.candies.get(c.parentName);
+ }
+ if (c.getPoints() == 0 && c.parent != null) {
+ c.setPoints(c.parent.getPoints());
+ }
+ }
+ }
+
+}
diff --git a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/candy.json b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/candy.json
new file mode 100644
index 000000000000..74430c318d72
--- /dev/null
+++ b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/candy.json
@@ -0,0 +1,45 @@
+{"candies" : [
+ {
+ "name" : "fruit",
+ "parent" : "null",
+ "type" : "rewardFruit",
+ "points" : "20"
+ },
+ {
+ "name" : "candy",
+ "parent" : "null",
+ "type" : "crushableCandy",
+ "points" : "10"
+ },
+ {
+ "name" : "cherry",
+ "parent" : "fruit",
+ "type" : "rewardFruit",
+ "points" : "0"
+ },
+ {
+ "name" : "mango",
+ "parent" : "fruit",
+ "type" : "rewardFruit",
+ "points" : "0"
+ },
+ {
+ "name" : "purple popsicle",
+ "parent" : "candy",
+ "type" : "crushableCandy",
+ "points" : "0"
+ },
+ {
+ "name" : "green jellybean",
+ "parent" : "candy",
+ "type" : "crushableCandy",
+ "points" : "0"
+ },
+ {
+ "name" : "orange gum",
+ "parent" : "candy",
+ "type" : "crushableCandy",
+ "points" : "0"
+ }
+ ]
+}
| diff --git a/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CandyGameTest.java b/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CandyGameTest.java
new file mode 100644
index 000000000000..d1b2fd359385
--- /dev/null
+++ b/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CandyGameTest.java
@@ -0,0 +1,69 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.typeobject;
+
+import static org.junit.jupiter.api.Assertions.*;
+import org.junit.jupiter.api.Test;
+import java.util.ArrayList;
+import com.iluwatar.typeobject.Candy.Type;
+
+/**
+ * The CandyGameTest class tests the methods in the {@link CandyGame} class.
+ */
+
+class CandyGameTest {
+
+ @Test
+ void adjacentCellsTest() {
+ CandyGame cg = new CandyGame(3,new CellPool(9));
+ ArrayList<Cell> arr1 = cg.adjacentCells(0, 0);
+ ArrayList<Cell> arr2 = cg.adjacentCells(1, 2);
+ ArrayList<Cell> arr3 = cg.adjacentCells(1, 1);
+ assertTrue(arr1.size() == 2 && arr2.size() == 3 && arr3.size() == 4);
+ }
+
+ @Test
+ void continueRoundTest() {
+ Cell[][] matrix = new Cell[2][2];
+ Candy c1 = new Candy("green jelly", "jelly", Type.crushableCandy, 5);
+ Candy c2 = new Candy("purple jelly", "jelly", Type.crushableCandy, 5);
+ Candy c3 = new Candy("green apple", "apple", Type.rewardFruit, 10);
+ matrix[0][0] = new Cell(c1,0,0);;
+ matrix[0][1] = new Cell(c2,1,0);
+ matrix[1][0] = new Cell(c3,0,1);
+ matrix[1][1] = new Cell(c2,1,1);
+ CellPool p = new CellPool(4);
+ CandyGame cg = new CandyGame(2,p);
+ cg.cells = matrix;
+ boolean fruitInLastRow = cg.continueRound();
+ matrix[1][0].crush(p, matrix);
+ matrix[0][0] = new Cell(c3,0,0);
+ boolean matchingCandy = cg.continueRound();
+ matrix[0][1].crush(p,matrix);
+ matrix[0][1] = new Cell(c3,1,0);
+ boolean noneLeft = cg.continueRound();
+ assertTrue(fruitInLastRow && matchingCandy && !noneLeft);
+ }
+
+}
diff --git a/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellPoolTest.java b/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellPoolTest.java
new file mode 100644
index 000000000000..437e39d1abd3
--- /dev/null
+++ b/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellPoolTest.java
@@ -0,0 +1,52 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.typeobject;
+
+import static org.junit.jupiter.api.Assertions.*;
+import org.junit.jupiter.api.Test;
+import java.util.Hashtable;
+
+/**
+ * The CellPoolTest class tests the methods in the {@link CellPool} class.
+ */
+
+class CellPoolTest {
+
+ @Test
+ void assignRandomCandyTypesTest() {
+ CellPool cp = new CellPool(10);
+ Hashtable<String, Boolean> ht = new Hashtable<String, Boolean>();
+ int parentTypes = 0;
+ for (int i = 0; i < cp.randomCode.length; i++) {
+ if (ht.get(cp.randomCode[i].name) == null) {
+ ht.put(cp.randomCode[i].name, true);
+ }
+ if (cp.randomCode[i].name.equals("fruit") || cp.randomCode[i].name.equals("candy")) {
+ parentTypes++;
+ }
+ }
+ assertTrue(ht.size() == 5 && parentTypes == 0);
+ }
+
+}
diff --git a/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellTest.java b/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellTest.java
new file mode 100644
index 000000000000..b4118cb48651
--- /dev/null
+++ b/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellTest.java
@@ -0,0 +1,61 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.typeobject;
+
+import static org.junit.jupiter.api.Assertions.*;
+import org.junit.jupiter.api.Test;
+import com.iluwatar.typeobject.Candy.Type;
+
+/**
+ * The CellTest class tests the methods in the {@link Cell} class.
+ */
+
+class CellTest {
+
+ @Test
+ void interactTest() {
+ Candy c1 = new Candy("green jelly", "jelly", Type.crushableCandy, 5);
+ Candy c2 = new Candy("green apple", "apple", Type.rewardFruit, 10);
+ Cell[][] matrix = new Cell[4][4];
+ matrix[0][0] = new Cell(c1,0,0);
+ matrix[0][1] = new Cell(c1,1,0);
+ matrix[0][2] = new Cell(c2,2,0);
+ matrix[0][3] = new Cell(c1,3,0);
+ CellPool cp = new CellPool(5);
+ int points1 = matrix[0][0].interact(matrix[0][1], cp, matrix);
+ int points2 = matrix[0][2].interact(matrix[0][3], cp, matrix);
+ assertTrue(points1 > 0 && points2 == 0);
+ }
+
+ @Test
+ void crushTest() {
+ Candy c1 = new Candy("green jelly", "jelly", Type.crushableCandy, 5);
+ Candy c2 = new Candy("purple candy", "candy", Type.crushableCandy, 5);
+ Cell[][] matrix = new Cell[4][4];
+ matrix[0][0] = new Cell(c1,0,0);
+ matrix[1][0] = new Cell(c2,0,1);
+ matrix[1][0].crush(new CellPool(5), matrix);
+ assertTrue(matrix[1][0].candy.name.equals("green jelly"));
+ }
+}
| train | train | "2019-02-04T07:35:06" | "2017-04-01T08:54:36Z" | iluwatar | train |
iluwatar/java-design-patterns/846_853 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/846 | iluwatar/java-design-patterns/853 | [
"keyword_pr_to_issue"
] | 26f1a608ab76178694468c7ce05037e5a1837e6c | 5251ec4a932d8739f201fe19efed2899c429033d | [
"It might be best just to put a comment saying so if needed. It doesn't really matter if it's there or not. It actually might be clearer to have it.\r\n[Java Reference on Enums](https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9)",
"Well spotted @lprone. I will gladly accept a pull request that removes the unnecessary `static`."
] | [] | "2019-02-13T21:47:58Z" | [
"info: help wanted",
"info: good first issue"
] | static enum | https://github.com/iluwatar/java-design-patterns/blob/55c75799831716b6248ceefa1315881e7f90806b/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java#L89
Enums don't need to be defined as a static. Can change it to :
`
enum Action {
` | [
"facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java"
] | [
"facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java"
] | [] | diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java b/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java
index bb80ae87409d..b313dd9890d9 100644
--- a/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java
+++ b/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java
@@ -86,7 +86,7 @@ public void action(Action... actions) {
public abstract String name();
- static enum Action {
+ enum Action {
GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK
}
}
| null | test | train | "2019-02-13T22:14:53" | "2019-02-07T01:22:23Z" | lprone | train |
iluwatar/java-design-patterns/508_854 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/508 | iluwatar/java-design-patterns/854 | [
"timestamp(timedelta=107.0, similarity=0.8485832572968025)"
] | 26f1a608ab76178694468c7ce05037e5a1837e6c | f7e22a1cf6f7664e8790cc5c76285adbcc6ab19d | [
"I will take care of this.\n",
"Thank you @sangupta you're good to go!\n",
"@sangupta are you still working on this?",
"@iluwatar Am sorry - have been pressed for time lately. Will have sometime in March - when I should be able to lend a helping hand.\r\n",
"@iluwatar I can pick this if no one else is looking at it, to start with I could begin with dao. Is it okay?",
"@Praveer-grover this is ok, please go ahead.",
"Updated sonarqube url\r\nhttps://sonarcloud.io/project/issues?id=com.iluwatar%3Ajava-design-patterns&resolved=false&severities=BLOCKER&types=CODE_SMELL\r\n\r\n@Praveer-grover Are you still working on these issues? Let me know if you want me to share some modules?\r\n",
"Ping @Praveer-grover ",
"@mookkiah Are you planning to completely work on this ticket or you need a helping hand? ;)",
"Either way is fine for me. As @Praveer-grover is not responding, I will look at sonarqube reported issues in prototype module (maybe this weekend). @dosdebug, you are welcome to help another module. Please just comment so we don't step on each other.",
"@mookkiah I will be working on `dao` and `naked-objects-dom` then.",
"Hey @mookkiah and @dosdebug are you guys still working on this?",
"I will work on prototype module. ",
"@iluwatar No Sir, not working on this.",
"Ok @mookkiah I will keep the issue `under construction`",
"Note : \r\nThe problem with the `dao` seems to be cause by the fact that SonarQube does not support `@Nested` : SQ currently ignores any `@Nested` classes, in other words it does not verify if there is a test within or not. ",
"There are still 4 blockers and 37 criticals. See https://sonarcloud.io/project/issues?id=com.iluwatar%3Ajava-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL. This issue is free for taking, if someone would like to help.",
"Hm.... there is something strange here. I just opened one of the `Blockers` : https://sonarcloud.io/project/issues?id=com.iluwatar%3Ajava-design-patterns&open=AVfejjZoPl_GJI-SB0qL&resolved=false&severities=BLOCKER and although the analysis is run on `October 24, 2018, 10:43 PM Version 1.21.0-SNAPSHOT` SonarCloud is displaying outdated source code : from 2 years ago instead of the one fixed in #810....\r\n\r\nOh, actually #810 has been merged on `October 25` : a day later. I guess the analysis does not contain the changes done in #810 ( if I am to trust the timestamps of GitHub and SonarCloud ). I would guess the blockers will be fixed in the next analysis.\r\n\r\nJust my 2c ;)\r\n\r\nPS : This may explain the 4 blockers but the criticals still need to be fixed.",
"@iluwatar I will start working on this and raise a PR shortly.",
"Ok @IAmPramod ",
"@iluwatar Is this available ?",
"@IAmPramod Are you still working on this ?",
"Hi @iluwatar : Pull request raised for this "
] | [] | "2019-02-15T08:17:59Z" | [
"type: bug",
"info: good first issue"
] | SonarQube reports code smells | Java Design Patterns is analyzed with SonarQube.com static analysis. The analysis shows some blocker level code smells that should be fixed:
https://sonarqube.com/component_issues/index?id=com.iluwatar%3Ajava-design-patterns#resolved=false|severities=BLOCKER|types=CODE_SMELL
| [
"event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java",
"event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java",
"event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java"
] | [
"event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java",
"event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java",
"event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java"
] | [] | diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java
index 6e9138d3c518..820279bc058a 100644
--- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java
+++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java
@@ -60,7 +60,8 @@ public class App {
/**
* Program entry point.
*
- * @param args command line args
+ * @param args
+ * command line args
*/
public static void main(String[] args) {
App app = new App();
@@ -150,56 +151,11 @@ public void runInteractiveMode() {
option = s.nextInt();
if (option == 1) {
- s.nextLine();
- LOGGER.info("Boil multiple eggs at once (A) or boil them one-by-one (S)?: ");
- String eventType = s.nextLine();
- LOGGER.info("How long should this egg be boiled for (in seconds)?: ");
- int eventTime = s.nextInt();
- if (eventType.equalsIgnoreCase("A")) {
- try {
- int eventId = eventManager.createAsync(eventTime);
- eventManager.start(eventId);
- LOGGER.info("Egg [{}] is being boiled.", eventId);
- } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) {
- LOGGER.error(e.getMessage());
- }
- } else if (eventType.equalsIgnoreCase("S")) {
- try {
- int eventId = eventManager.create(eventTime);
- eventManager.start(eventId);
- LOGGER.info("Egg [{}] is being boiled.", eventId);
- } catch (MaxNumOfEventsAllowedException | InvalidOperationException | LongRunningEventException
- | EventDoesNotExistException e) {
- LOGGER.error(e.getMessage());
- }
- } else {
- LOGGER.info("Unknown event type.");
- }
+ processOption1(eventManager, s);
} else if (option == 2) {
- LOGGER.info("Which egg?: ");
- int eventId = s.nextInt();
- try {
- eventManager.cancel(eventId);
- LOGGER.info("Egg [{}] is removed from boiler.", eventId);
- } catch (EventDoesNotExistException e) {
- LOGGER.error(e.getMessage());
- }
+ processOption2(eventManager, s);
} else if (option == 3) {
- s.nextLine();
- LOGGER.info("Just one egg (O) OR all of them (A) ?: ");
- String eggChoice = s.nextLine();
-
- if (eggChoice.equalsIgnoreCase("O")) {
- LOGGER.info("Which egg?: ");
- int eventId = s.nextInt();
- try {
- eventManager.status(eventId);
- } catch (EventDoesNotExistException e) {
- LOGGER.error(e.getMessage());
- }
- } else if (eggChoice.equalsIgnoreCase("A")) {
- eventManager.statusOfAllEvents();
- }
+ processOption3(eventManager, s);
} else if (option == 4) {
eventManager.shutdown();
}
@@ -208,4 +164,61 @@ public void runInteractiveMode() {
s.close();
}
+ private void processOption3(EventManager eventManager, Scanner s) {
+ s.nextLine();
+ LOGGER.info("Just one egg (O) OR all of them (A) ?: ");
+ String eggChoice = s.nextLine();
+
+ if (eggChoice.equalsIgnoreCase("O")) {
+ LOGGER.info("Which egg?: ");
+ int eventId = s.nextInt();
+ try {
+ eventManager.status(eventId);
+ } catch (EventDoesNotExistException e) {
+ LOGGER.error(e.getMessage());
+ }
+ } else if (eggChoice.equalsIgnoreCase("A")) {
+ eventManager.statusOfAllEvents();
+ }
+ }
+
+ private void processOption2(EventManager eventManager, Scanner s) {
+ LOGGER.info("Which egg?: ");
+ int eventId = s.nextInt();
+ try {
+ eventManager.cancel(eventId);
+ LOGGER.info("Egg [{}] is removed from boiler.", eventId);
+ } catch (EventDoesNotExistException e) {
+ LOGGER.error(e.getMessage());
+ }
+ }
+
+ private void processOption1(EventManager eventManager, Scanner s) {
+ s.nextLine();
+ LOGGER.info("Boil multiple eggs at once (A) or boil them one-by-one (S)?: ");
+ String eventType = s.nextLine();
+ LOGGER.info("How long should this egg be boiled for (in seconds)?: ");
+ int eventTime = s.nextInt();
+ if (eventType.equalsIgnoreCase("A")) {
+ try {
+ int eventId = eventManager.createAsync(eventTime);
+ eventManager.start(eventId);
+ LOGGER.info("Egg [{}] is being boiled.", eventId);
+ } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) {
+ LOGGER.error(e.getMessage());
+ }
+ } else if (eventType.equalsIgnoreCase("S")) {
+ try {
+ int eventId = eventManager.create(eventTime);
+ eventManager.start(eventId);
+ LOGGER.info("Egg [{}] is being boiled.", eventId);
+ } catch (MaxNumOfEventsAllowedException | InvalidOperationException | LongRunningEventException
+ | EventDoesNotExistException e) {
+ LOGGER.error(e.getMessage());
+ }
+ } else {
+ LOGGER.info("Unknown event type.");
+ }
+ }
+
}
diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java
index 729900620aa0..d54665bb21f5 100644
--- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java
+++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java
@@ -39,6 +39,8 @@ public class EventManager implements ThreadCompleteListener {
private int currentlyRunningSyncEvent = -1;
private Random rand;
private Map<Integer, Event> eventPool;
+
+ private static final String DOES_NOT_EXIST = " does not exist.";
/**
* EventManager constructor.
@@ -112,7 +114,7 @@ private int createEvent(int eventTime, boolean isSynchronous)
*/
public void start(int eventId) throws EventDoesNotExistException {
if (!eventPool.containsKey(eventId)) {
- throw new EventDoesNotExistException(eventId + " does not exist.");
+ throw new EventDoesNotExistException(eventId + DOES_NOT_EXIST);
}
eventPool.get(eventId).start();
@@ -126,7 +128,7 @@ public void start(int eventId) throws EventDoesNotExistException {
*/
public void cancel(int eventId) throws EventDoesNotExistException {
if (!eventPool.containsKey(eventId)) {
- throw new EventDoesNotExistException(eventId + " does not exist.");
+ throw new EventDoesNotExistException(eventId + DOES_NOT_EXIST);
}
if (eventId == currentlyRunningSyncEvent) {
@@ -145,7 +147,7 @@ public void cancel(int eventId) throws EventDoesNotExistException {
*/
public void status(int eventId) throws EventDoesNotExistException {
if (!eventPool.containsKey(eventId)) {
- throw new EventDoesNotExistException(eventId + " does not exist.");
+ throw new EventDoesNotExistException(eventId + DOES_NOT_EXIST);
}
eventPool.get(eventId).status();
diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java
index d2e5f429b5d4..a8ba649eb602 100644
--- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java
+++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java
@@ -44,6 +44,8 @@ public class Account {
private final int accountNo;
private final String owner;
private BigDecimal money;
+
+ private static final String MSG = "Some external api for only realtime execution could be called here.";
/**
* Instantiates a new Account.
@@ -126,7 +128,7 @@ private void handleDeposit(BigDecimal money, boolean realTime) {
depositMoney(money);
AccountAggregate.putAccount(this);
if (realTime) {
- LOGGER.info("Some external api for only realtime execution could be called here.");
+ LOGGER.info(MSG);
}
}
@@ -138,7 +140,7 @@ private void handleWithdrawal(BigDecimal money, boolean realTime) {
withdrawMoney(money);
AccountAggregate.putAccount(this);
if (realTime) {
- LOGGER.info("Some external api for only realtime execution could be called here.");
+ LOGGER.info(MSG);
}
}
@@ -160,7 +162,7 @@ public void handleEvent(MoneyDepositEvent moneyDepositEvent) {
public void handleEvent(AccountCreateEvent accountCreateEvent) {
AccountAggregate.putAccount(this);
if (accountCreateEvent.isRealTime()) {
- LOGGER.info("Some external api for only realtime execution could be called here.");
+ LOGGER.info(MSG);
}
}
| null | val | train | "2019-02-13T22:14:53" | "2016-10-20T14:17:59Z" | iluwatar | train |
iluwatar/java-design-patterns/845_856 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/845 | iluwatar/java-design-patterns/856 | [
"timestamp(timedelta=33.0, similarity=0.8746586039099573)"
] | eafe52e17a2e985f269477a633608a64851abcc0 | b6b4602baf5a12d8b76b3f8dd0284bae44230aa9 | [
"I don't really think this is an issue at all. This is a code style suggestion, and in my opinion, both are equally clear.",
"Yes, just create a pull request and we can improve the style.",
"Hi @iluwatar \r\nI can take this up",
"Ok @kanwarpreet25 "
] | [] | "2019-02-15T18:46:41Z" | [
"info: good first issue"
] | Unnecesary return | https://github.com/iluwatar/java-design-patterns/blob/55c75799831716b6248ceefa1315881e7f90806b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java#L58
you can change this block
`
if (!this.boundary.contains(p)) {
return;
} else {
`
to this other most clear:
`
if (this.boundary.contains(p)) {
`
| [
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java"
] | [
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java"
] | [] | diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java
index 072468ce80d4..815bf8acc74c 100644
--- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java
+++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java
@@ -55,16 +55,13 @@ public class QuadTree {
}
void insert(Point p) {
- if (!this.boundary.contains(p)) {
- return;
- } else {
+ if (this.boundary.contains(p)) {
if (this.points.size() < this.capacity) {
points.put(p.id, p);
} else {
if (!this.divided) {
this.divide();
}
-
if (this.northwest.boundary.contains(p)) {
this.northwest.insert(p);
} else if (this.northeast.boundary.contains(p)) {
| null | train | train | "2019-02-15T19:00:21" | "2019-02-07T01:14:46Z" | lprone | train |
iluwatar/java-design-patterns/868_872 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/868 | iluwatar/java-design-patterns/872 | [
"keyword_pr_to_issue"
] | fedc2d9e47cb2b44aa4ea23aed9d117bbd4ed069 | aaabc8f517461593d206a009858cefd163e43daa | [
"Code snippet of **_<org.apache.commons.logging.LogFactory: org.apache.commons.logging.LogFactory getFactory()>_** in _**org.slf4j:jcl-over-slf4j:jar:1.7.16:compile**_ (loaded version):\r\n![01](https://user-images.githubusercontent.com/46306510/55683799-534bcb80-5976-11e9-800a-a3b00a00cafa.png)\r\n\r\nCode snippet of **_<org.apache.commons.logging.LogFactory: org.apache.commons.logging.LogFactory getFactory()>_** in _**commons-logging:commons-logging:jar:1.2:compile**_ \r\n (shadowed but expected to invoke method):\r\n![02](https://user-images.githubusercontent.com/46306510/55683800-5777e900-5976-11e9-82f0-3e7a8e44bff2.png)\r\n**.......**\r\n\r\n\r\nAs a result, these conflicting method included in **commons-logging:commons-logging:jar:1.2:compile** deals with different cases, which changes the control flows and data flows. So being forced to use these methods in **org.slf4j:jcl-over-slf4j:jar:1.7.16:compile** may lead to inconsisitent semantic behaviors.",
"Thanks @HelloCoCooo for the finding. I'll be glad to accept your pull request."
] | [] | "2019-04-15T10:13:10Z" | [
"epic: build issue"
] | Dependency Conflict: duplicate classes "org.apache.commons.logging.LogFactory" in different JARs, have different implementations | Hi, in **java-design-patterns-1.20.0** (**api-gateway\api-gateway-service** module), duplicate classes with the same fully-qualified name _**org.apache.commons.logging.LogFactory**_ are included in two different libraries, i.e., **org.slf4j:jcl-over-slf4j:1.7.16** and **commons-logging:commons-logging:1.2**.
According to _"first declaration wins"_ class loading strategy, only this class in **_org.slf4j:jcl-over-slf4j:1.7.16_** can be loaded, and that in _**commons-logging:commons-logging:1.2**_ will be shadowed.
By further analyzing, your project expects to invoke method **_<org.apache.commons.logging.LogFactory: org.apache.commons.logging.LogFactory getFactory()>_** in _**commons-logging:commons-logging:1.2**_. As it has been shadowed, so that this method defined in **_org.slf4j:jcl-over-slf4j:1.7.16_** are actually forced to be referenced via the following invocation path:
```
<com.iluwatar.api.gateway.PriceClientImpl: java.lang.String getPrice()> D:\testcase\TestProject\java-design-patterns-1.20.0\api-gateway\api-gateway-service\target\classes
<org.apache.http.impl.client.HttpClients: org.apache.http.impl.client.CloseableHttpClient createDefault()> D:\cEnvironment\repository\org\apache\httpcomponents\httpclient\4.5.2\httpclient-4.5.2.jar
<org.apache.http.impl.client.HttpClientBuilder: org.apache.http.impl.client.CloseableHttpClient build()> D:\cEnvironment\repository\org\apache\httpcomponents\httpclient\4.5.2\httpclient-4.5.2.jar
<org.apache.http.impl.client.InternalHttpClient: void <init>(org.apache.http.impl.execchain.ClientExecChain,org.apache.http.conn.HttpClientConnectionManager,org.apache.http.conn.routing.HttpRoutePlanner,org.apache.http.config.Lookup,org.apache.http.config.Lookup,org.apache.http.client.CookieStore,org.apache.http.client.CredentialsProvider,org.apache.http.client.config.RequestConfig,java.util.List)> D:\cEnvironment\repository\org\apache\httpcomponents\httpclient\4.5.2\httpclient-4.5.2.jar
<org.apache.commons.logging.LogFactory: org.apache.commons.logging.Log getLog(java.lang.Class)>
<org.apache.commons.logging.LogFactory: org.apache.commons.logging.LogFactory getFactory()>
```
Although both of these two conflicting classes contain the referenced methods (with the same signature), they have different implementations. This issue will not lead to runtime crashes, but it can introduce inconsistent semantic hehavior by changing the control flows and data flows.
**_Workaround solution:_**
An easy way to workaround the problem is **_reversing the declaration order_** of these two libraries (i.e., reverse the declaration order of httpclient and spring-boot-starter-web) in pom file.
Then, according to **_"first declaration wins"_** class loading strategy, class _**org.apache.commons.logging.LogFactory**_ in _**commons-logging:commons-logging:1.2**_ can be loaded (the version that **java-design-patterns** expects to reference by static analysis).
This fix will not affect other libraries or class, except the above duplicate class.
### Dependency tree---
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ api-gateway-service ---
[INFO] com.iluwatar:api-gateway-service:jar:1.20.0
[INFO] +- org.springframework:spring-webmvc:jar:4.2.4.RELEASE:compile
[INFO] | +- org.springframework:spring-beans:jar:4.2.5.RELEASE:compile
[INFO] | +- org.springframework:spring-context:jar:4.2.5.RELEASE:compile
[INFO] | | \- org.springframework:spring-aop:jar:4.2.5.RELEASE:compile
[INFO] | | \- aopalliance:aopalliance:jar:1.0:compile
[INFO] | +- org.springframework:spring-core:jar:4.2.5.RELEASE:compile
[INFO] | +- org.springframework:spring-expression:jar:4.2.5.RELEASE:compile
[INFO] | \- org.springframework:spring-web:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:1.3.3.RELEASE:compile
[INFO] | +- org.springframework.boot:spring-boot-starter:jar:1.3.3.RELEASE:compile
[INFO] | | +- org.springframework.boot:spring-boot:jar:1.3.3.RELEASE:compile
[INFO] | | +- org.springframework.boot:spring-boot-autoconfigure:jar:1.3.3.RELEASE:compile
[INFO] | | +- org.springframework.boot:spring-boot-starter-logging:jar:1.3.3.RELEASE:compile
[INFO] | | | +- _**org.slf4j:jcl-over-slf4j:jar:1.7.16:compile**_
[INFO] | | | +- org.slf4j:jul-to-slf4j:jar:1.7.16:compile
[INFO] | | | \- org.slf4j:log4j-over-slf4j:jar:1.7.16:compile
[INFO] | | \- org.yaml:snakeyaml:jar:1.16:runtime
[INFO] | +- org.springframework.boot:spring-boot-starter-tomcat:jar:1.3.3.RELEASE:compile
[INFO] | | +- org.apache.tomcat.embed:tomcat-embed-core:jar:8.0.32:compile
[INFO] | | +- org.apache.tomcat.embed:tomcat-embed-el:jar:8.0.32:compile
[INFO] | | +- org.apache.tomcat.embed:tomcat-embed-logging-juli:jar:8.0.32:compile
[INFO] | | \- org.apache.tomcat.embed:tomcat-embed-websocket:jar:8.0.32:compile
[INFO] | +- org.springframework.boot:spring-boot-starter-validation:jar:1.3.3.RELEASE:compile
[INFO] | | \- org.hibernate:hibernate-validator:jar:5.2.4.Final:compile
[INFO] | | +- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] | | +- org.jboss.logging:jboss-logging:jar:3.3.0.Final:compile
[INFO] | | \- com.fasterxml:classmate:jar:1.1.0:compile
[INFO] | \- com.fasterxml.jackson.core:jackson-databind:jar:2.6.5:compile
[INFO] | +- com.fasterxml.jackson.core:jackson-annotations:jar:2.6.5:compile
[INFO] | \- com.fasterxml.jackson.core:jackson-core:jar:2.6.5:compile
[INFO] +- org.junit.jupiter:junit-jupiter-api:jar:5.0.2:test
[INFO] | +- org.opentest4j:opentest4j:jar:1.0.0:test
[INFO] | \- org.junit.platform:junit-platform-commons:jar:1.0.2:test
[INFO] +- org.junit.jupiter:junit-jupiter-engine:jar:5.0.2:test
[INFO] | \- org.junit.platform:junit-platform-engine:jar:1.0.2:test
[INFO] +- org.mockito:mockito-core:jar:1.10.19:test
[INFO] | +- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] | \- org.objenesis:objenesis:jar:2.1:test
[INFO] +- org.apache.httpcomponents:httpclient:jar:4.5.2:compile
[INFO] | +- org.apache.httpcomponents:httpcore:jar:4.4.4:compile
[INFO] | +- _**commons-logging:commons-logging:jar:1.2:compile**_
[INFO] | \- commons-codec:commons-codec:jar:1.9:compile
[INFO] +- org.slf4j:slf4j-api:jar:1.7.21:compile
[INFO] +- ch.qos.logback:logback-classic:jar:1.1.7:compile
[INFO] \- ch.qos.logback:logback-core:jar:1.1.7:compile
Thank you very much.
Best,
Coco | [
"api-gateway/api-gateway-service/pom.xml"
] | [
"api-gateway/api-gateway-service/pom.xml"
] | [] | diff --git a/api-gateway/api-gateway-service/pom.xml b/api-gateway/api-gateway-service/pom.xml
index f947049a757c..13bbddc97d09 100644
--- a/api-gateway/api-gateway-service/pom.xml
+++ b/api-gateway/api-gateway-service/pom.xml
@@ -48,6 +48,10 @@
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpclient</artifactId>
+ </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
@@ -67,10 +71,6 @@
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- </dependency>
</dependencies>
<build>
@@ -89,4 +89,4 @@
</plugin>
</plugins>
</build>
-</project>
\ No newline at end of file
+</project>
| null | train | train | "2019-04-07T07:41:35" | "2019-04-07T12:39:23Z" | HelloCoCooo | train |
iluwatar/java-design-patterns/875_877 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/875 | iluwatar/java-design-patterns/877 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.9158216094727133)"
] | fedc2d9e47cb2b44aa4ea23aed9d117bbd4ed069 | b497d41f61b43e188f43fa0f3f70b3a2e164bb76 | [] | [] | "2019-05-02T17:28:40Z" | [
"info: help wanted",
"type: enhancement",
"epic: web site",
"info: good first issue"
] | Wrong UML in observer | The UML diagram presented in the Observer pattern description is wrong.
The multiplicity between Weather and WeatherType is stated to be 0..1, but that is not the case in the code, since you can't create a Weather object without associating it with a WeatherType (the costructor sets the type to "sunny", timepasses() _changes_ that value, but there is no way to remove the type.
Therefore, the correct cardinality should be just 1. | [
"observer/README.md",
"observer/etc/observer.ucls"
] | [
"observer/README.md",
"observer/etc/observer.ucls"
] | [] | diff --git a/observer/README.md b/observer/README.md
index 38a28032f957..afeb0b37d68d 100644
--- a/observer/README.md
+++ b/observer/README.md
@@ -19,7 +19,7 @@ Define a one-to-many dependency between objects so that when one
object changes state, all its dependents are notified and updated
automatically.
-![alt text](./etc/observer_1.png "Observer")
+![alt text](./etc/observer.png "Observer")
## Applicability
Use the Observer pattern in any of the following situations
diff --git a/observer/etc/observer.ucls b/observer/etc/observer.ucls
index 87a3dd216d4e..ac1d267f89b8 100644
--- a/observer/etc/observer.ucls
+++ b/observer/etc/observer.ucls
@@ -1,9 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
-<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
- realizations="true" associations="true" dependencies="false" nesting-relationships="true">
+<class-diagram version="1.2.3" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
+ realizations="true" associations="true" dependencies="false" nesting-relationships="true" router="FAN">
<class id="1" language="java" name="com.iluwatar.observer.Hobbits" project="observer"
file="/observer/src/main/java/com/iluwatar/observer/Hobbits.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="106" width="175" x="193" y="288"/>
+ <position height="-1" width="-1" x="723" y="333"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
@@ -12,7 +12,7 @@
</class>
<interface id="2" language="java" name="com.iluwatar.observer.WeatherObserver" project="observer"
file="/observer/src/main/java/com/iluwatar/observer/WeatherObserver.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="88" width="175" x="408" y="488"/>
+ <position height="-1" width="-1" x="454" y="330"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
@@ -21,7 +21,7 @@
</interface>
<class id="3" language="java" name="com.iluwatar.observer.Orcs" project="observer"
file="/observer/src/main/java/com/iluwatar/observer/Orcs.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="106" width="175" x="408" y="288"/>
+ <position height="-1" width="-1" x="454" y="468"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
@@ -30,7 +30,7 @@
</class>
<class id="4" language="java" name="com.iluwatar.observer.Weather" project="observer"
file="/observer/src/main/java/com/iluwatar/observer/Weather.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="160" width="252" x="623" y="288"/>
+ <position height="-1" width="-1" x="454" y="129"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
@@ -39,7 +39,7 @@
</class>
<enumeration id="5" language="java" name="com.iluwatar.observer.WeatherType" project="observer"
file="/observer/src/main/java/com/iluwatar/observer/WeatherType.java" binary="false" corner="BOTTOM_RIGHT">
- <position height="178" width="154" x="623" y="488"/>
+ <position height="-1" width="-1" x="791" y="129"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
@@ -48,28 +48,36 @@
</enumeration>
<association id="6">
<end type="SOURCE" refId="4" navigable="false">
- <attribute id="7" name="observers"/>
- <multiplicity id="8" minimum="0" maximum="2147483647"/>
+ <attribute id="7" name="observers">
+ <position height="0" width="0" x="-41" y="-202"/>
+ </attribute>
+ <multiplicity id="8" minimum="0" maximum="2147483647">
+ <position height="0" width="0" x="-41" y="-202"/>
+ </multiplicity>
</end>
<end type="TARGET" refId="2" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<realization id="9">
+ <end type="SOURCE" refId="3"/>
+ <end type="TARGET" refId="2"/>
+ </realization>
+ <realization id="10">
<end type="SOURCE" refId="1"/>
<end type="TARGET" refId="2"/>
</realization>
- <association id="10">
+ <association id="11">
<end type="SOURCE" refId="4" navigable="false">
- <attribute id="11" name="currentWeather"/>
- <multiplicity id="12" minimum="0" maximum="1"/>
+ <attribute id="12" name="currentWeather">
+ <position height="0" width="0" x="91" y="-448"/>
+ </attribute>
+ <multiplicity id="13" minimum="1" maximum="1">
+ <position height="0" width="0" x="91" y="-448"/>
+ </multiplicity>
</end>
<end type="TARGET" refId="5" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
- <realization id="13">
- <end type="SOURCE" refId="3"/>
- <end type="TARGET" refId="2"/>
- </realization>
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
| null | val | train | "2019-04-07T07:41:35" | "2019-04-24T18:27:16Z" | andreazube | train |
iluwatar/java-design-patterns/883_885 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/883 | iluwatar/java-design-patterns/885 | [
"keyword_pr_to_issue"
] | fedc2d9e47cb2b44aa4ea23aed9d117bbd4ed069 | ccb257d5250f15061499dbb63aeba1057bafc963 | [
"@iluwatar Can i take this. Thanks",
"Ok @ranjeet-floyd ",
"Is this fixed already?",
"Is this issue already resloved?"
] | [] | "2019-06-11T17:23:28Z" | [
"info: help wanted",
"type: enhancement",
"info: good first issue"
] | Dirty Flag pattern Issue | https://github.com/iluwatar/java-design-patterns/blob/fedc2d9e47cb2b44aa4ea23aed9d117bbd4ed069/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java#L60
Creating object of World class inside Thread's Run method doesn't make sense, as every time it is creating new object and reading the file. It should be outside this thread's run method.
for now it is like this
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
World world = new World();
List<String> countries = world.fetch();
but it should be like this
executorService.scheduleAtFixedRate(new Runnable() {
World world = new World();
@Override
public void run() {
List<String> countries = world.fetch(); | [
"dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java"
] | [
"dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java"
] | [] | diff --git a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java
index 4d72b34da249..827028d09a06 100644
--- a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java
+++ b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java
@@ -55,9 +55,9 @@ public void run() {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() {
+ final World world = new World();
@Override
public void run() {
- World world = new World();
List<String> countries = world.fetch();
System.out.println("Our world currently has the following countries:-");
for (String country : countries) {
| null | train | train | "2019-04-07T07:41:35" | "2019-06-05T19:52:23Z" | sajankumarma | train |
iluwatar/java-design-patterns/449_888 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/449 | iluwatar/java-design-patterns/888 | [
"timestamp(timedelta=57.0, similarity=0.9070039905061017)"
] | 11c055055934d1a78e1b98072ea5dd2c4b96da3c | 7f6067f19fe03c41cc25f704dbdab93b5069f0cb | [
"Hi @iluwatar @npathai , I would like to contribute on this issue. \n",
"@harshSE go ahead, it's all yours :)\n",
"Good to see you @harshSE. Looking forward to your long term contribution 😊\n",
"@harshSE are you still working on this?",
"This issue is free for taking again",
"Hi @iluwatar @npathai , I would like to contribute on this issue.",
"Ok @pelmegov ",
"@iluwatar Can I take over this issue?",
"@pelmegov are you still working on this? Please comment or @HaydenMeloche takes it over.",
"@iluwatar Can i take this please ?. Raised PR https://github.com/iluwatar/java-design-patterns/pull/888",
"@iluwatar Please review PR https://github.com/iluwatar/java-design-patterns/pull/888. Thanks",
"Ok @ranjeet-floyd ",
"https://docs.microsoft.com/en-us/azure/architecture/patterns/priority-queue"
] | [
"Make these final",
"Why is maven-compiler-plugin needed here?",
"Explain here more verbosely how the example works and implements the pattern",
"Ok",
"I will check. Thanks",
"i will add better comment. Thanks",
"Removed",
"Added better message",
"Done"
] | "2019-06-15T13:10:02Z" | [
"epic: pattern"
] | Priority Queue pattern | https://msdn.microsoft.com/en-us/library/dn589794.aspx
| [
"pom.xml"
] | [
"pom.xml",
"priority-queue/README.md",
"priority-queue/pom.xml",
"priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java",
"priority-queue/src/main/java/com/iluwatar/priority/queue/Message.java",
"priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java",
"priority-queue/src/main/java/com/iluwatar/priority/queue/QueueManager.java",
"priority-queue/src/main/java/com/iluwatar/priority/queue/Worker.java"
] | [
"priority-queue/src/test/java/com/iluwatar/priority/queue/PriorityMessageQueueTest.java",
"priority-queue/src/test/java/com/iluwatar/priority/queue/QueueManagerTest.java"
] | diff --git a/pom.xml b/pom.xml
index fef21534fa71..f305e97d983e 100644
--- a/pom.xml
+++ b/pom.xml
@@ -17,7 +17,9 @@
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
@@ -162,12 +164,13 @@
<module>trampoline</module>
<module>serverless</module>
<module>ambassador</module>
- <module>acyclic-visitor</module>
- <module>collection-pipeline</module>
- <module>master-worker-pattern</module>
- <module>spatial-partition</module>
- <module>commander</module>
- <module>typeobjectpattern</module>
+ <module>acyclic-visitor</module>
+ <module>collection-pipeline</module>
+ <module>master-worker-pattern</module>
+ <module>spatial-partition</module>
+ <module>priority-queue</module>
+ <module>commander</module>
+ <module>typeobjectpattern</module>
</modules>
<repositories>
diff --git a/priority-queue/README.md b/priority-queue/README.md
new file mode 100644
index 000000000000..bc8d7b8cfed0
--- /dev/null
+++ b/priority-queue/README.md
@@ -0,0 +1,27 @@
+---
+layout: pattern
+title: Priority Queue Pattern
+folder: priority-queue
+permalink: /patterns/priority-queue/
+categories: Behavioral
+tags:
+ - Java
+ - Difficulty-Beginner
+---
+
+## Intent
+Prioritize requests sent to services so that requests with a higher priority are received and processed more quickly than those of a lower priority. This pattern is useful in applications that offer different service level guarantees to individual clients.
+
+## Explanation
+Applications may delegate specific tasks to other services; for example, to perform background processing or to integrate with other applications or services. In the cloud, a message queue is typically used to delegate tasks to background processing. In many cases the order in which requests are received by a service is not important. However, in some cases it may be necessary to prioritize specific requests. These requests should be processed earlier than others of a lower priority that may have been sent previously by the application.
+
+## Applicability
+Use the Property pattern when
+
+* The system must handle multiple tasks that might have different priorities.
+* Different users or tenants should be served with different priority..
+
+## Real world examples
+
+* [ Priority Queue Pattern](https://docs.microsoft.com/en-us/previous-versions/msp-n-p/dn589794(v=pandp.10))
+Microsoft Azure does not provide a queuing mechanism that natively support automatic prioritization of messages through sorting. However, it does provide Azure Service Bus topics and subscriptions, which support a queuing mechanism that provides message filtering, together with a wide range of flexible capabilities that make it ideal for use in almost all priority queue implementations.
diff --git a/priority-queue/pom.xml b/priority-queue/pom.xml
new file mode 100644
index 000000000000..9e5a788066c3
--- /dev/null
+++ b/priority-queue/pom.xml
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+ The MIT License
+ Copyright (c) 2014 Ilkka Seppälä
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>priority-queue</artifactId>
+ <parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>java-design-patterns</artifactId>
+ <version>1.21.0-SNAPSHOT</version>
+ </parent>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+</project>
\ No newline at end of file
diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java
new file mode 100644
index 000000000000..5ec1dc0cbaae
--- /dev/null
+++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java
@@ -0,0 +1,60 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ * <p>
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ * <p>
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ * <p>
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.priority.queue;
+
+/**
+ * Prioritize requests sent to services so that requests with a higher priority are received and
+ * processed more quickly than those of a lower priority.
+ * This pattern is useful in applications that offer different service level guarantees
+ * to individual clients.
+ * Example :Send multiple message with different priority to worker queue.
+ * Worker execute higher priority message first
+ * @see "https://docs.microsoft.com/en-us/previous-versions/msp-n-p/dn589794(v=pandp.10)"
+ */
+public class Application {
+ /**
+ * main entry
+ */
+ public static void main(String[] args) throws Exception {
+
+ QueueManager queueManager = new QueueManager(100);
+
+ // push some message to queue
+ // Low Priority message
+ for (int i = 0; i < 100; i++) {
+ queueManager.publishMessage(new Message("Low Message Priority", 0));
+ }
+
+ // High Priority message
+ for (int i = 0; i < 100; i++) {
+ queueManager.publishMessage(new Message("High Message Priority", 1));
+ }
+
+
+ // run worker
+ Worker worker = new Worker(queueManager);
+ worker.run();
+
+
+ }
+}
diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/Message.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/Message.java
new file mode 100644
index 000000000000..66c561d64269
--- /dev/null
+++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/Message.java
@@ -0,0 +1,50 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.priority.queue;
+
+/**
+ * Message bean
+ */
+public class Message implements Comparable<Message> {
+ private final String message;
+ private final int priority; // define message priority in queue
+
+
+ public Message(String message, int priority) {
+ this.message = message;
+ this.priority = priority;
+ }
+
+ @Override
+ public int compareTo(Message o) {
+ return priority - o.priority;
+ }
+
+ @Override
+ public String toString() {
+ return "Message{"
+ + "message='" + message + '\''
+ + ", priority=" + priority
+ + '}';
+ }
+}
diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java
new file mode 100644
index 000000000000..2a49d94b53e3
--- /dev/null
+++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java
@@ -0,0 +1,178 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ * <p>
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ * <p>
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ * <p>
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.priority.queue;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static java.util.Arrays.copyOf;
+
+/**
+ * Keep high Priority message on top using maxHeap.
+ *
+ * @param <T> : DataType to push in Queue
+ */
+public class PriorityMessageQueue<T extends Comparable> {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(PriorityMessageQueue.class);
+
+ private int size = 0;
+
+ private int capacity;
+
+
+ private T[] queue;
+
+ public PriorityMessageQueue(T[] queue) {
+ this.queue = queue;
+ this.capacity = queue.length;
+ }
+
+ /**
+ * Remove top message from queue
+ */
+ public T remove() {
+ if (isEmpty()) {
+ return null;
+ }
+
+ T root = queue[0];
+ queue[0] = queue[size - 1];
+ size--;
+ maxHeapifyDown();
+ return root;
+ }
+
+ /**
+ * Add message to queue
+ */
+ public void add(T t) {
+ ensureCapacity();
+ queue[size] = t;
+ size++;
+ maxHeapifyUp();
+ }
+
+ /**
+ * Check queue size
+ */
+ public boolean isEmpty() {
+ return size == 0;
+ }
+
+
+ private void maxHeapifyDown() {
+ int index = 0;
+ while (hasLeftChild(index)) {
+
+ int smallerIndex = leftChildIndex(index);
+
+ if (hasRightChild(index) && right(index).compareTo(left(index)) > 0) {
+ smallerIndex = rightChildIndex(index);
+ }
+
+ if (queue[index].compareTo(queue[smallerIndex]) > 0) {
+ break;
+ } else {
+ swap(index, smallerIndex);
+ }
+
+ index = smallerIndex;
+
+
+ }
+
+ }
+
+ private void maxHeapifyUp() {
+ int index = size - 1;
+ while (hasParent(index) && parent(index).compareTo(queue[index]) < 0) {
+ swap(parentIndex(index), index);
+ index = parentIndex(index);
+ }
+ }
+
+
+ // index
+ private int parentIndex(int pos) {
+ return (pos - 1) / 2;
+ }
+
+ private int leftChildIndex(int parentPos) {
+ return 2 * parentPos + 1;
+ }
+
+ private int rightChildIndex(int parentPos) {
+ return 2 * parentPos + 2;
+ }
+
+ // value
+ private T parent(int childIndex) {
+ return queue[parentIndex(childIndex)];
+ }
+
+ private T left(int parentIndex) {
+ return queue[leftChildIndex(parentIndex)];
+ }
+
+ private T right(int parentIndex) {
+ return queue[rightChildIndex(parentIndex)];
+ }
+
+ // check
+ private boolean hasLeftChild(int index) {
+ return leftChildIndex(index) < size;
+ }
+
+ private boolean hasRightChild(int index) {
+ return rightChildIndex(index) < size;
+ }
+
+ private boolean hasParent(int index) {
+ return parentIndex(index) >= 0;
+ }
+
+ private void swap(int fpos, int tpos) {
+ T tmp = queue[fpos];
+ queue[fpos] = queue[tpos];
+ queue[tpos] = tmp;
+ }
+
+ private void ensureCapacity() {
+ if (size == capacity) {
+ capacity = capacity * 2;
+ queue = copyOf(queue, capacity);
+ }
+ }
+
+ /**
+ * For debug .. print current state of queue
+ */
+ public void print() {
+ for (int i = 0; i <= size / 2; i++) {
+ LOGGER.info(" PARENT : " + queue[i] + " LEFT CHILD : "
+ + left(i) + " RIGHT CHILD :" + right(i));
+ }
+ }
+
+}
diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/QueueManager.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/QueueManager.java
new file mode 100644
index 000000000000..7eb68500b178
--- /dev/null
+++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/QueueManager.java
@@ -0,0 +1,57 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ * <p>
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ * <p>
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ * <p>
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.priority.queue;
+
+/**
+ * Manage priority queue
+ */
+public class QueueManager {
+ /*
+ Priority message
+ */
+ private final PriorityMessageQueue<Message> messagePriorityMessageQueue;
+
+ public QueueManager(int initialCapacity) {
+ messagePriorityMessageQueue = new PriorityMessageQueue<Message>(new Message[initialCapacity]);
+ }
+
+ /**
+ * Publish message to queue
+ */
+ public void publishMessage(Message message) {
+ messagePriorityMessageQueue.add(message);
+ }
+
+
+ /**
+ * recive message from queue
+ */
+ public Message receiveMessage() {
+ if (messagePriorityMessageQueue.isEmpty()) {
+ return null;
+ }
+ return messagePriorityMessageQueue.remove();
+ }
+
+
+}
diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/Worker.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/Worker.java
new file mode 100644
index 000000000000..22faa1519e34
--- /dev/null
+++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/Worker.java
@@ -0,0 +1,63 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ * <p>
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ * <p>
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ * <p>
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.priority.queue;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Message Worker
+ */
+public class Worker {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(Worker.class);
+
+ private final QueueManager queueManager;
+
+ public Worker(QueueManager queueManager) {
+ this.queueManager = queueManager;
+ }
+
+ /**
+ * Keep checking queue for message
+ */
+ public void run() throws Exception {
+ while (true) {
+ Message message = queueManager.receiveMessage();
+ if (message == null) {
+ LOGGER.info("No Message ... waiting");
+ Thread.sleep(200);
+ } else {
+ processMessage(message);
+ }
+ }
+ }
+
+ /**
+ * Process message
+ */
+ private void processMessage(Message message) {
+ LOGGER.info(message.toString());
+ }
+
+}
| diff --git a/priority-queue/src/test/java/com/iluwatar/priority/queue/PriorityMessageQueueTest.java b/priority-queue/src/test/java/com/iluwatar/priority/queue/PriorityMessageQueueTest.java
new file mode 100644
index 000000000000..6dc26fcf67e2
--- /dev/null
+++ b/priority-queue/src/test/java/com/iluwatar/priority/queue/PriorityMessageQueueTest.java
@@ -0,0 +1,73 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.priority.queue;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test case for order of messages
+ */
+public class PriorityMessageQueueTest {
+
+
+ @Test
+ public void remove() {
+ PriorityMessageQueue<String> stringPriorityMessageQueue = new PriorityMessageQueue<>(new String[2]);
+ String pushMessage = "test";
+ stringPriorityMessageQueue.add(pushMessage);
+ assertEquals(stringPriorityMessageQueue.remove(), pushMessage);
+ }
+
+ @Test
+ public void add() {
+ PriorityMessageQueue<Integer> stringPriorityMessageQueue = new PriorityMessageQueue<>(new Integer[2]);
+ stringPriorityMessageQueue.add(1);
+ stringPriorityMessageQueue.add(5);
+ stringPriorityMessageQueue.add(10);
+ stringPriorityMessageQueue.add(3);
+ assertTrue(stringPriorityMessageQueue.remove() == 10);
+ }
+
+ @Test
+ public void isEmpty() {
+ PriorityMessageQueue<Integer> stringPriorityMessageQueue = new PriorityMessageQueue<>(new Integer[2]);
+ assertTrue(stringPriorityMessageQueue.isEmpty());
+ stringPriorityMessageQueue.add(1);
+ stringPriorityMessageQueue.remove();
+ assertTrue(stringPriorityMessageQueue.isEmpty());
+ }
+
+ @Test
+ public void testEnsureSize() {
+ PriorityMessageQueue<Integer> stringPriorityMessageQueue = new PriorityMessageQueue<>(new Integer[2]);
+ assertTrue(stringPriorityMessageQueue.isEmpty());
+ stringPriorityMessageQueue.add(1);
+ stringPriorityMessageQueue.add(2);
+ stringPriorityMessageQueue.add(2);
+ stringPriorityMessageQueue.add(3);
+ assertTrue(stringPriorityMessageQueue.remove() == 3);
+ }
+}
\ No newline at end of file
diff --git a/priority-queue/src/test/java/com/iluwatar/priority/queue/QueueManagerTest.java b/priority-queue/src/test/java/com/iluwatar/priority/queue/QueueManagerTest.java
new file mode 100644
index 000000000000..721fea4deea1
--- /dev/null
+++ b/priority-queue/src/test/java/com/iluwatar/priority/queue/QueueManagerTest.java
@@ -0,0 +1,53 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.priority.queue;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * Check queue manager
+ */
+public class QueueManagerTest {
+
+ @Test
+ public void publishMessage() {
+ QueueManager queueManager = new QueueManager(2);
+ Message testMessage = new Message("Test Message", 1);
+ queueManager.publishMessage(testMessage);
+ Message recivedMessage = queueManager.receiveMessage();
+ assertEquals(testMessage, recivedMessage);
+ }
+
+ @Test
+ public void receiveMessage() {
+ QueueManager queueManager = new QueueManager(2);
+ Message testMessage1 = new Message("Test Message 1", 1);
+ queueManager.publishMessage(testMessage1);
+ Message testMessage2 = new Message("Test Message 2", 2);
+ queueManager.publishMessage(testMessage2);
+ Message recivedMessage = queueManager.receiveMessage();
+ assertEquals(testMessage2, recivedMessage);
+ }
+}
\ No newline at end of file
| val | train | "2019-08-21T20:51:27" | "2016-07-02T17:07:38Z" | iluwatar | train |
iluwatar/java-design-patterns/553_896 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/553 | iluwatar/java-design-patterns/896 | [
"timestamp(timedelta=116.0, similarity=0.9137941367497018)"
] | 7f6067f19fe03c41cc25f704dbdab93b5069f0cb | 318f811fead95c4a363d776e968b0b1a4a112c86 | [
"Hey @iluwatar, I would love to work on this if no one else has claimed it yet.",
"Ok @abhishek7 ",
"@abhishek7 are you still implementing this?",
"@iluwatar apologies for the delay, did not have a chance to make additional progress on it. Feel free to give it to someone else. If I do have time, I'll open up a PR and reference the issue accordingly.",
"The issue is free to take again",
"Hi @iluwatar, if nobody is working on this then I can try to implement this pattern.",
"Ok @pzawitowski "
] | [] | "2019-07-07T18:27:39Z" | [
"epic: pattern"
] | Bytecode pattern | http://gameprogrammingpatterns.com/bytecode.html | [
"pom.xml"
] | [
"bytecode/README.md",
"bytecode/etc/bytecode.ucls",
"bytecode/pom.xml",
"bytecode/src/main/java/com/iluwatar/bytecode/App.java",
"bytecode/src/main/java/com/iluwatar/bytecode/Instruction.java",
"bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java",
"bytecode/src/main/java/com/iluwatar/bytecode/Wizard.java",
"bytecode/src/main/java/com/iluwatar/bytecode/util/InstructionConverterUtil.java",
"pom.xml"
] | [
"bytecode/src/test/java/com/iluwatar/bytecode/AppTest.java",
"bytecode/src/test/java/com/iluwatar/bytecode/VirtualMachineTest.java",
"bytecode/src/test/java/com/iluwatar/bytecode/util/InstructionConverterUtilTest.java"
] | diff --git a/bytecode/README.md b/bytecode/README.md
new file mode 100644
index 000000000000..d2fc45e1e2d1
--- /dev/null
+++ b/bytecode/README.md
@@ -0,0 +1,25 @@
+---
+layout: pattern
+title: Bytecode
+folder: bytecode
+permalink: /patterns/bytecode/
+categories: Behavioral
+tags:
+ - Java
+ - Difficulty-Beginner
+---
+
+## Intent
+Allows to encode behaviour as instructions for virtual machine.
+
+## Applicability
+Use the Bytecode pattern when you have a lot of behavior you need to define and your
+game’s implementation language isn’t a good fit because:
+
+* it’s too low-level, making it tedious or error-prone to program in.
+* iterating on it takes too long due to slow compile times or other tooling issues.
+* it has too much trust. If you want to ensure the behavior being defined can’t break the game, you need to sandbox it from the rest of the codebase.
+
+## Credits
+
+* [Game programming patterns](http://gameprogrammingpatterns.com/bytecode.html)
diff --git a/bytecode/etc/bytecode.ucls b/bytecode/etc/bytecode.ucls
new file mode 100644
index 000000000000..3ec390458956
--- /dev/null
+++ b/bytecode/etc/bytecode.ucls
@@ -0,0 +1,49 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<class-diagram version="1.2.3" icons="true" always-add-relationships="false" generalizations="true" realizations="true"
+ associations="true" dependencies="false" nesting-relationships="true" router="FAN">
+ <class id="1" language="java" name="com.iluwatar.bytecode.VirtualMachine" project="bytecode"
+ file="/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="455" y="173"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <class id="2" language="java" name="com.iluwatar.bytecode.App" project="bytecode"
+ file="/bytecode/src/main/java/com/iluwatar/bytecode/App.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="148" y="110"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <class id="3" language="java" name="com.iluwatar.bytecode.Wizard" project="bytecode"
+ file="/bytecode/src/main/java/com/iluwatar/bytecode/Wizard.java" binary="false" corner="BOTTOM_RIGHT">
+ <position height="-1" width="-1" x="148" y="416"/>
+ <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </display>
+ </class>
+ <association id="4">
+ <end type="SOURCE" refId="1" navigable="false" variant="ASSOCIATION">
+ <attribute id="5" name="wizards">
+ <position height="18" width="48" x="296" y="291"/>
+ </attribute>
+ <multiplicity id="6" minimum="0" maximum="2147483647">
+ <position height="0" width="0" x="-327" y="-27"/>
+ </multiplicity>
+ </end>
+ <end type="TARGET" refId="3" navigable="true" variant="ASSOCIATION"/>
+ <display labels="true" multiplicity="true"/>
+ </association>
+ <classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
+ sort-features="false" accessors="true" visibility="true">
+ <attributes public="true" package="true" protected="true" private="true" static="true"/>
+ <operations public="true" package="true" protected="true" private="true" static="true"/>
+ </classifier-display>
+ <association-display labels="true" multiplicity="true"/>
+</class-diagram>
\ No newline at end of file
diff --git a/bytecode/pom.xml b/bytecode/pom.xml
new file mode 100644
index 000000000000..e9e6247f8eb2
--- /dev/null
+++ b/bytecode/pom.xml
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+ The MIT License
+ Copyright (c) 2019 Ilkka Seppälä
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <parent>
+ <artifactId>java-design-patterns</artifactId>
+ <groupId>com.iluwatar</groupId>
+ <version>1.21.0-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+
+ <artifactId>bytecode</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+</project>
\ No newline at end of file
diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/App.java b/bytecode/src/main/java/com/iluwatar/bytecode/App.java
new file mode 100644
index 000000000000..90b97bd33308
--- /dev/null
+++ b/bytecode/src/main/java/com/iluwatar/bytecode/App.java
@@ -0,0 +1,79 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.bytecode;
+
+import com.iluwatar.bytecode.util.InstructionConverterUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * The intention of Bytecode pattern is to give behavior the flexibility of data by encoding it as instructions
+ * for a virtual machine.
+ * An instruction set defines the low-level operations that can be performed. A series of instructions is encoded as
+ * a sequence of bytes. A virtual machine executes these instructions one at a time,
+ * using a stack for intermediate values. By combining instructions, complex high-level behavior can be defined.
+ *
+ * This pattern should be used when there is a need to define high number of behaviours and implementation engine
+ * is not a good choice because
+ * It is too lowe level
+ * Iterating on it takes too long due to slow compile times or other tooling issues.
+ * It has too much trust. If you want to ensure the behavior being defined can’t break the game,
+ * you need to sandbox it from the rest of the codebase.
+ *
+ */
+public class App {
+ private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
+
+ /**
+ * Main app method
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ VirtualMachine vm = new VirtualMachine();
+
+ Wizard wizard = new Wizard();
+ wizard.setHealth(45);
+ wizard.setAgility(7);
+ wizard.setWisdom(11);
+ vm.getWizards()[0] = wizard;
+
+ interpretInstruction("LITERAL 0", vm);
+ interpretInstruction( "LITERAL 0", vm);
+ interpretInstruction( "GET_HEALTH", vm);
+ interpretInstruction( "LITERAL 0", vm);
+ interpretInstruction( "GET_AGILITY", vm);
+ interpretInstruction( "LITERAL 0", vm);
+ interpretInstruction( "GET_WISDOM ", vm);
+ interpretInstruction( "ADD", vm);
+ interpretInstruction( "LITERAL 2", vm);
+ interpretInstruction( "DIVIDE", vm);
+ interpretInstruction( "ADD", vm);
+ interpretInstruction( "SET_HEALTH", vm);
+ }
+
+ private static void interpretInstruction(String instruction, VirtualMachine vm) {
+ InstructionConverterUtil converter = new InstructionConverterUtil();
+ vm.execute(converter.convertToByteCode(instruction));
+ LOGGER.info(instruction + String.format("%" + (12 - instruction.length()) + "s", "" ) + vm.getStack());
+ }
+}
diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/Instruction.java b/bytecode/src/main/java/com/iluwatar/bytecode/Instruction.java
new file mode 100644
index 000000000000..2ceb66e3bdc2
--- /dev/null
+++ b/bytecode/src/main/java/com/iluwatar/bytecode/Instruction.java
@@ -0,0 +1,65 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.bytecode;
+
+/**
+ * Representation of instructions understandable by virtual machine
+ */
+public enum Instruction {
+
+ LITERAL(1),
+ SET_HEALTH(2),
+ SET_WISDOM (3),
+ SET_AGILITY(4),
+ PLAY_SOUND(5),
+ SPAWN_PARTICLES(6),
+ GET_HEALTH(7),
+ GET_AGILITY(8),
+ GET_WISDOM(9),
+ ADD(10),
+ DIVIDE (11);
+
+ private int value;
+
+ Instruction(int value) {
+ this.value = value;
+ }
+
+ public int getIntValue() {
+ return value;
+ }
+
+ /**
+ * Converts integer value to Instruction
+ * @param value value of instruction
+ * @return representation of the instruction
+ */
+ public static Instruction getInstruction(int value) {
+ for (int i = 0; i < Instruction.values().length; i++) {
+ if (Instruction.values()[i].getIntValue() == value) {
+ return Instruction.values()[i];
+ }
+ }
+ throw new IllegalArgumentException("Invalid instruction value");
+ }
+}
diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java b/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java
new file mode 100644
index 000000000000..aedafe514dce
--- /dev/null
+++ b/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java
@@ -0,0 +1,142 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.bytecode;
+
+import java.util.Stack;
+
+/**
+ * Implementation of virtual machine
+ */
+public class VirtualMachine {
+
+ private Stack<Integer> stack = new Stack();
+
+ private Wizard[] wizards = new Wizard[2];
+
+ /**
+ * Constructor
+ */
+ public VirtualMachine() {
+ for (int i = 0; i < wizards.length; i++) {
+ wizards[i] = new Wizard();
+ }
+ }
+
+ /**
+ * Executes provided bytecode
+ * @param bytecode to execute
+ */
+ public void execute(int[] bytecode) {
+ for (int i = 0; i < bytecode.length; i++) {
+ Instruction instruction = Instruction.getInstruction(bytecode[i]);
+ int wizard;
+ int amount;
+ switch (instruction) {
+ case LITERAL:
+ // Read the next byte from the bytecode.
+ int value = bytecode[++i];
+ stack.push(value);
+ break;
+ case SET_AGILITY:
+ amount = stack.pop();
+ wizard = stack.pop();
+ setAgility(wizard, amount);
+ break;
+ case SET_WISDOM:
+ amount = stack.pop();
+ wizard = stack.pop();
+ setWisdom(wizard, amount);
+ break;
+ case SET_HEALTH:
+ amount = stack.pop();
+ wizard = stack.pop();
+ setHealth(wizard, amount);
+ break;
+ case GET_HEALTH:
+ wizard = stack.pop();
+ stack.push(getHealth(wizard));
+ break;
+ case GET_AGILITY:
+ wizard = stack.pop();
+ stack.push(getAgility(wizard));
+ break;
+ case GET_WISDOM:
+ wizard = stack.pop();
+ stack.push(getWisdom(wizard));
+ break;
+ case ADD:
+ int a = stack.pop();
+ int b = stack.pop();
+ stack.push(a + b);
+ break;
+ case DIVIDE:
+ a = stack.pop();
+ b = stack.pop();
+ stack.push(b / a);
+ break;
+ case PLAY_SOUND:
+ wizard = stack.pop();
+ getWizards()[wizard].playSound();
+ break;
+ case SPAWN_PARTICLES:
+ wizard = stack.pop();
+ getWizards()[wizard].spawnParticles();
+ break;
+ default:
+ throw new IllegalArgumentException("Invalid instruction value");
+ }
+ }
+ }
+
+ public Stack<Integer> getStack() {
+ return stack;
+ }
+
+ public void setHealth(int wizard, int amount) {
+ wizards[wizard].setHealth(amount);
+ }
+
+ public void setWisdom(int wizard, int amount) {
+ wizards[wizard].setWisdom(amount);
+ }
+
+ public void setAgility(int wizard, int amount) {
+ wizards[wizard].setAgility(amount);
+ }
+
+ public int getHealth(int wizard) {
+ return wizards[wizard].getHealth();
+ }
+
+ public int getWisdom(int wizard) {
+ return wizards[wizard].getWisdom();
+ }
+
+ public int getAgility(int wizard) {
+ return wizards[wizard].getAgility();
+ }
+
+ public Wizard[] getWizards() {
+ return wizards;
+ }
+}
diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/Wizard.java b/bytecode/src/main/java/com/iluwatar/bytecode/Wizard.java
new file mode 100644
index 000000000000..ca47fd28f873
--- /dev/null
+++ b/bytecode/src/main/java/com/iluwatar/bytecode/Wizard.java
@@ -0,0 +1,83 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.bytecode;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class represent game objects which properties can be changed by instructions interpreted by virtual machine
+ */
+public class Wizard {
+ private static final Logger LOGGER = LoggerFactory.getLogger(Wizard.class);
+
+ private int health;
+
+ private int agility;
+ private int wisdom;
+
+ private int numberOfPlayedSounds;
+ private int numberOfSpawnedParticles;
+
+ public int getHealth() {
+ return health;
+ }
+
+ public void setHealth(int health) {
+ this.health = health;
+ }
+
+ public int getAgility() {
+ return agility;
+ }
+
+ public void setAgility(int agility) {
+ this.agility = agility;
+ }
+
+ public int getWisdom() {
+ return wisdom;
+ }
+
+ public void setWisdom(int wisdom) {
+ this.wisdom = wisdom;
+ }
+
+ public void playSound() {
+ LOGGER.info("Playing sound");
+ numberOfPlayedSounds++;
+ }
+
+ public void spawnParticles() {
+ LOGGER.info("Spawning particles");
+ numberOfSpawnedParticles++;
+ }
+
+ public int getNumberOfPlayedSounds() {
+ return numberOfPlayedSounds;
+ }
+
+ public int getNumberOfSpawnedParticles() {
+ return numberOfSpawnedParticles;
+ }
+}
diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/util/InstructionConverterUtil.java b/bytecode/src/main/java/com/iluwatar/bytecode/util/InstructionConverterUtil.java
new file mode 100644
index 000000000000..202784d5a96c
--- /dev/null
+++ b/bytecode/src/main/java/com/iluwatar/bytecode/util/InstructionConverterUtil.java
@@ -0,0 +1,76 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.bytecode.util;
+
+import com.iluwatar.bytecode.Instruction;
+
+/**
+ * Utility class used for instruction validation and conversion
+ */
+public class InstructionConverterUtil {
+ /**
+ * Converts instructions represented as String
+ *
+ * @param instructions to convert
+ * @return array of int representing bytecode
+ */
+ public static int[] convertToByteCode(String instructions) {
+ if (instructions == null || instructions.trim().length() == 0) {
+ return new int[0];
+ }
+
+ String[] splitedInstructions = instructions.trim().split(" ");
+ int[] bytecode = new int[splitedInstructions.length];
+ for (int i = 0; i < splitedInstructions.length; i++) {
+ if (isValidInstruction(splitedInstructions[i])) {
+ bytecode[i] = Instruction.valueOf(splitedInstructions[i]).getIntValue();
+ } else if (isValidInt(splitedInstructions[i])) {
+ bytecode[i] = Integer.valueOf(splitedInstructions[i]);
+ } else {
+ throw new IllegalArgumentException("Invalid instruction or number: " + splitedInstructions[i]);
+ }
+ }
+
+ return bytecode;
+ }
+
+ private static boolean isValidInstruction(String instruction) {
+ try {
+ Instruction.valueOf(instruction);
+ return true;
+ } catch (IllegalArgumentException e) {
+ return false;
+ }
+ }
+
+ private static boolean isValidInt(String value) {
+ try {
+ Integer.parseInt(value);
+ return true;
+ } catch (NumberFormatException e) {
+ return false;
+ }
+ }
+
+
+}
diff --git a/pom.xml b/pom.xml
index f305e97d983e..c55ed6492211 100644
--- a/pom.xml
+++ b/pom.xml
@@ -171,6 +171,7 @@
<module>priority-queue</module>
<module>commander</module>
<module>typeobjectpattern</module>
+ <module>bytecode</module>
</modules>
<repositories>
| diff --git a/bytecode/src/test/java/com/iluwatar/bytecode/AppTest.java b/bytecode/src/test/java/com/iluwatar/bytecode/AppTest.java
new file mode 100644
index 000000000000..014ec787569c
--- /dev/null
+++ b/bytecode/src/test/java/com/iluwatar/bytecode/AppTest.java
@@ -0,0 +1,37 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.bytecode;
+
+import org.junit.jupiter.api.Test;
+
+/**
+ * Application test
+ */
+public class AppTest {
+
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
+}
diff --git a/bytecode/src/test/java/com/iluwatar/bytecode/VirtualMachineTest.java b/bytecode/src/test/java/com/iluwatar/bytecode/VirtualMachineTest.java
new file mode 100644
index 000000000000..e4379c9ede38
--- /dev/null
+++ b/bytecode/src/test/java/com/iluwatar/bytecode/VirtualMachineTest.java
@@ -0,0 +1,154 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.bytecode;
+
+import org.junit.jupiter.api.Test;
+
+import static com.iluwatar.bytecode.Instruction.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * Test for {@Link VirtualMachine}
+ */
+public class VirtualMachineTest {
+
+ @Test
+ public void testLiteral() {
+ int[] bytecode = new int[2];
+ bytecode[0] = LITERAL.getIntValue();
+ bytecode[1] = 10;
+
+ VirtualMachine vm = new VirtualMachine();
+ vm.execute(bytecode);
+
+ assertEquals(1, vm.getStack().size());
+ assertEquals(Integer.valueOf(10), vm.getStack().pop());
+ }
+
+ @Test
+ public void testSetHealth() {
+ int wizardNumber = 0;
+ int[] bytecode = new int[5];
+ bytecode[0] = LITERAL.getIntValue();
+ bytecode[1] = wizardNumber;
+ bytecode[2] = LITERAL.getIntValue();
+ bytecode[3] = 50; // health amount
+ bytecode[4] = SET_HEALTH.getIntValue();
+
+ VirtualMachine vm = new VirtualMachine();
+ vm.execute(bytecode);
+
+ assertEquals(50, vm.getWizards()[wizardNumber].getHealth());
+ }
+
+ @Test
+ public void testSetAgility() {
+ int wizardNumber = 0;
+ int[] bytecode = new int[5];
+ bytecode[0] = LITERAL.getIntValue();
+ bytecode[1] = wizardNumber;
+ bytecode[2] = LITERAL.getIntValue();
+ bytecode[3] = 50; // agility amount
+ bytecode[4] = SET_AGILITY.getIntValue();
+
+ VirtualMachine vm = new VirtualMachine();
+ vm.execute(bytecode);
+
+ assertEquals(50, vm.getWizards()[wizardNumber].getAgility());
+ }
+
+ @Test
+ public void testSetWisdom() {
+ int wizardNumber = 0;
+ int[] bytecode = new int[5];
+ bytecode[0] = LITERAL.getIntValue();
+ bytecode[1] = wizardNumber;
+ bytecode[2] = LITERAL.getIntValue();
+ bytecode[3] = 50; // wisdom amount
+ bytecode[4] = SET_WISDOM.getIntValue();
+
+ VirtualMachine vm = new VirtualMachine();
+ vm.execute(bytecode);
+
+ assertEquals(50, vm.getWizards()[wizardNumber].getWisdom());
+ }
+
+ @Test
+ public void testGetHealth() {
+ int wizardNumber = 0;
+ int[] bytecode = new int[8];
+ bytecode[0] = LITERAL.getIntValue();
+ bytecode[1] = wizardNumber;
+ bytecode[2] = LITERAL.getIntValue();
+ bytecode[3] = 50; // health amount
+ bytecode[4] = SET_HEALTH.getIntValue();
+ bytecode[5] = LITERAL.getIntValue();;
+ bytecode[6] = wizardNumber;
+ bytecode[7] = GET_HEALTH.getIntValue();
+
+ VirtualMachine vm = new VirtualMachine();
+ vm.execute(bytecode);
+
+ assertEquals(Integer.valueOf(50), vm.getStack().pop());
+ }
+
+ @Test
+ public void testPlaySound() {
+ int wizardNumber = 0;
+ int[] bytecode = new int[3];
+ bytecode[0] = LITERAL.getIntValue();
+ bytecode[1] = wizardNumber;
+ bytecode[2] = PLAY_SOUND.getIntValue();
+
+ VirtualMachine vm = new VirtualMachine();
+ vm.execute(bytecode);
+
+ assertEquals(0, vm.getStack().size());
+ assertEquals(1, vm.getWizards()[0].getNumberOfPlayedSounds());
+ }
+
+ @Test
+ public void testSpawnParticles() {
+ int wizardNumber = 0;
+ int[] bytecode = new int[3];
+ bytecode[0] = LITERAL.getIntValue();
+ bytecode[1] = wizardNumber;
+ bytecode[2] = SPAWN_PARTICLES.getIntValue();
+
+ VirtualMachine vm = new VirtualMachine();
+ vm.execute(bytecode);
+
+ assertEquals(0, vm.getStack().size());
+ assertEquals(1, vm.getWizards()[0].getNumberOfSpawnedParticles());
+ }
+
+ @Test
+ public void testInvalidInstruction() {
+ int[] bytecode = new int[1];
+ bytecode[0] = 999;
+ VirtualMachine vm = new VirtualMachine();
+
+ assertThrows(IllegalArgumentException.class, () -> vm.execute(bytecode));
+ }
+}
diff --git a/bytecode/src/test/java/com/iluwatar/bytecode/util/InstructionConverterUtilTest.java b/bytecode/src/test/java/com/iluwatar/bytecode/util/InstructionConverterUtilTest.java
new file mode 100644
index 000000000000..4743ac109e12
--- /dev/null
+++ b/bytecode/src/test/java/com/iluwatar/bytecode/util/InstructionConverterUtilTest.java
@@ -0,0 +1,63 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.bytecode.util;
+
+import com.iluwatar.bytecode.Instruction;
+import com.iluwatar.bytecode.util.InstructionConverterUtil;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Test for {@Link InstructionConverterUtil}
+ */
+public class InstructionConverterUtilTest {
+ @Test
+ public void testEmptyInstruction() {
+ String instruction = "";
+
+ int[] bytecode = InstructionConverterUtil.convertToByteCode(instruction);
+
+ Assertions.assertEquals(0, bytecode.length);
+ }
+
+ @Test
+ public void testInstructions() {
+ String instructions =
+ "LITERAL 35 SET_HEALTH SET_WISDOM SET_AGILITY PLAY_SOUND SPAWN_PARTICLES GET_HEALTH ADD DIVIDE";
+
+ int[] bytecode = InstructionConverterUtil.convertToByteCode(instructions);
+
+ Assertions.assertEquals(10, bytecode.length);
+ Assertions.assertEquals(Instruction.LITERAL.getIntValue(), bytecode[0]);
+ Assertions.assertEquals(35, bytecode[1]);
+ Assertions.assertEquals(Instruction.SET_HEALTH.getIntValue(), bytecode[2]);
+ Assertions.assertEquals(Instruction.SET_WISDOM.getIntValue(), bytecode[3]);
+ Assertions.assertEquals(Instruction.SET_AGILITY.getIntValue(), bytecode[4]);
+ Assertions.assertEquals(Instruction.PLAY_SOUND.getIntValue(), bytecode[5]);
+ Assertions.assertEquals(Instruction.SPAWN_PARTICLES.getIntValue(), bytecode[6]);
+ Assertions.assertEquals(Instruction.GET_HEALTH.getIntValue(), bytecode[7]);
+ Assertions.assertEquals(Instruction.ADD.getIntValue(), bytecode[8]);
+ Assertions.assertEquals(Instruction.DIVIDE.getIntValue(), bytecode[9]);
+ }
+
+}
| val | train | "2019-08-31T20:10:35" | "2017-04-01T08:53:45Z" | iluwatar | train |
iluwatar/java-design-patterns/895_901 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/895 | iluwatar/java-design-patterns/901 | [
"keyword_pr_to_issue"
] | fedc2d9e47cb2b44aa4ea23aed9d117bbd4ed069 | 35dc25d4806f898bfc8f1ee31e4c9479bcc496d8 | [
"I am working on this issue.",
"Ok @saksham93 ",
"Pull Request raised"
] | [] | "2019-07-19T05:41:51Z" | [
"type: bug",
"info: good first issue"
] | typo in FYI comment at "java-design-pattern/acyclic-visitor" | From here:
https://github.com/iluwatar/java-design-patterns/blob/fedc2d9e47cb2b44aa4ea23aed9d117bbd4ed069/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/App.java#L50
The comment should be:
```text
// Hayes modem with Dos configurator
``` | [
"acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/App.java"
] | [
"acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/App.java"
] | [] | diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/App.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/App.java
index 06e4bd2f255d..2a2f64591b6c 100644
--- a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/App.java
+++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/App.java
@@ -47,7 +47,7 @@ public static void main(String[] args) {
Zoom zoom = new Zoom();
Hayes hayes = new Hayes();
- hayes.accept(conDos); // Hayes modem with Unix configurator
+ hayes.accept(conDos); // Hayes modem with Dos configurator
zoom.accept(conDos); // Zoom modem with Dos configurator
hayes.accept(conUnix); // Hayes modem with Unix configurator
zoom.accept(conUnix); // Zoom modem with Unix configurator
| null | train | train | "2019-04-07T07:41:35" | "2019-07-06T21:34:43Z" | ljleb | train |
iluwatar/java-design-patterns/898_906 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/898 | iluwatar/java-design-patterns/906 | [
"timestamp(timedelta=24.0, similarity=0.845261461277026)"
] | 0c6237c225584a3a28bdd81cb19a40de698ed7f7 | 37fb276f28908353edb9a45be9c1e41799c18125 | [
"Describe your idea in this issue."
] | [] | "2019-07-25T08:22:19Z" | [
"type: support",
"resolution: won't fix"
] | A new way for Factory Method | I wan to attach a fork with my idea for this project | [] | [
"simple-factory/README.md",
"simple-factory/src/main/java/com/iluwater/simplefactory/Apple.java",
"simple-factory/src/main/java/com/iluwater/simplefactory/Fruit.java",
"simple-factory/src/main/java/com/iluwater/simplefactory/FruitFactory.java",
"simple-factory/src/main/java/com/iluwater/simplefactory/Main.java",
"simple-factory/src/main/java/com/iluwater/simplefactory/Pear.java"
] | [
"simple-factory/src/test/java/com/iluwater/simplefactory/SimpleFactorytest.java"
] | diff --git a/simple-factory/README.md b/simple-factory/README.md
new file mode 100644
index 000000000000..ec464c63732c
--- /dev/null
+++ b/simple-factory/README.md
@@ -0,0 +1,239 @@
+
+
+
+Simple Factory Pattern
+========================================
+|layout|title|folder|permalink|categories|tags|
+|---|---|---|---|---|---|
+|pattern|Simple Factory|simple-factory|/patterns/simple-factory/|Structural|java|
+
+## Intent
+![alt text](./etc/SimpleFactory.jpg "Simple-Factory")
+![alt text](./etc/seq_SimpleFactory.jpg "Sequence Simple-Factory")
+
+
+Model Motivation
+--------------------
+
+Considering a simple software application scenario, a software system can provide multiple buttons with different appearance (such as circular button, rectangular button, diamond button, etc.).
+
+These buttons all originate from the same base class, but after inheriting the base class, different subclasses modify some attributes so that they can present different appearance. If we want to use these buttons, we don't need to know the name of these specific button classes, just need to know a parameter representing the button class, and mention it. For a convenient method to call, the parameter can be passed into the method to return a corresponding button object, at this time, you can use the simple factory mode.
+
+
+
+Schema Definition
+--------------------
+
+Simple Factory Pattern: Also known as Static Factory Method, it belongs to the class creation pattern. In simple factory mode, instances of different classes can be returned according to different parameters. The Simple Factory pattern specifically defines a class to create instances of other classes, which usually have a common parent class.
+
+
+
+
+Model structure
+--------------------
+
+The simple factory model includes the following roles:
+
+
+
+- Factory: Factory role
+
+The factory role is responsible for implementing the internal logic for creating all instances
+
+- Product: abstract product roles
+
+The abstract product role is the parent class of all objects created and is responsible for describing the common interfaces shared by all instances.
+
+- ConcreteProduct: Specific Product Roles
+
+A specific product role is to create a goal, and all created objects act as instances of a specific class of that role.
+
+
+
+
+Code analysing
+--------------------
+interface Fruit
+
+```java
+public interface Fruit {
+ void whatIm();
+}
+```
+
+class Apple
+
+```java
+public class Apple implements Fruit {
+ @Override
+ public void whatIm() {
+ //apple
+ }
+}
+```
+
+class Pear
+
+```java
+public class Pear implements Fruit {
+ @Override
+ public void whatIm() {
+ //pear
+ }
+}
+```
+class FruitFactory
+
+```java
+public class FruitFactory {
+
+ public Fruit createFruit(String type) {
+
+ if (type.equals("apple")) {//produce apple
+ return new Apple();
+ } else if (type.equals("pear")) {//produce pear
+ return new Pear();
+ }
+
+ return null;
+ }
+}
+```
+
+product use
+
+```java
+ FruitFactory mFactory = new FruitFactory();
+ Apple apple = (Apple) mFactory.createFruit("apple");//get apple
+ Pear pear = (Pear) mFactory.createFruit("pear");//get pear
+
+```
+
+
+
+Linenos:
+
+
+
+
+pattern analysis
+--------------------
+
+
+
+- Separating the creation of objects from the business processing of the objects themselves can reduce the coupling degree of the system and make it relatively easy to modify both.
+
+- When calling the factory method of the factory class, because the factory method is static and convenient to use, it can be called directly by the class name, and only need to pass in a simple parameter. In practical development, the parameters can be saved in the configuration file of XML and other formats when calling, and the parameters can be modified. There is no need to modify any source code.
+
+- The biggest problem of the simple factory model is that the responsibility of the factory class is relatively heavy. Adding new products requires modifying the judgment logic of the factory class, which is contrary to the principle of opening and closing.
+
+- The point of the simple factory pattern is that when you need something, you just need to pass in a correct parameter to get the object you need without knowing the details of its creation.
+
+
+
+Example
+--------------------
+(Brief)
+
+
+
+
+Advantages of Simple Factory Model
+--------------------
+
+
+
+- The factory class contains the necessary judgment logic, which can decide when to create an instance of which product class. The client can exempt the responsibility of directly creating the product object, but only "consume" the product. Simple factory mode achieves the division of responsibility by this way. It provides a special factory class for creating. Object.
+
+- The client does not need to know the class name of the specific product class, but only the corresponding parameters of the specific product class. For some complex class names, simple factory mode can reduce the user's memory.
+
+- By introducing configuration files, new product classes can be replaced and added without modifying any client code, which improves the flexibility of the system to a certain extent.
+
+
+
+Disadvantages of Simple Factory Model
+--------------------
+
+
+
+- Because the factory class centralizes all the product creation logic, once it does not work properly, the whole system will be affected.
+
+- Using simple factory mode will increase the number of classes in the system, and increase the complexity and difficulty of understanding the system in a certain program.
+
+- System expansion is difficult, once new products are added, factory logic has to be modified. When there are many types of products, factory logic may be too complex, which is not conducive to system expansion and maintenance.
+
+- Simple factory model uses static factory method, which makes it impossible for factory roles to form hierarchical structure based on inheritance.
+
+
+
+Applicable environment
+
+-----------------------------------------
+
+Simple factory mode can be used in the following cases:
+
+
+
+- The factory class is responsible for creating fewer objects: because fewer objects are created, the business logic in the factory method is not too complex.
+
+- The client only knows the parameters passed into the factory class, and does not care about how to create the object: the client does not need to care about the creation details, or even the class name, but only knows the parameters corresponding to the type.
+
+
+
+Model application
+--------------------
+
+1. Simple factory patterns are widely used in JDK class libraries, such as the tool class java. text. DateFormat, which is used to format a local date or time.
+
+
+
+:
+
+
+
+Public final static DateFormat getDateInstance ();
+
+Public final static DateFormat getDateInstance (int style);
+
+Public final static DateFormat getDateInstance (int style, Locale)
+
+Locale;
+
+
+
+2. Java Encryption Technology
+
+
+
+Get the key generator of different encryption algorithms::
+
+
+
+KeyGenerator keyGen = KeyGenerator. getInstance ("DESede");
+
+
+
+Create a password::
+
+
+
+Cipher CP = Cipher. getInstance ("DESede");
+
+
+
+summary
+--------------------
+
+
+
+- Creative schemas abstract the instantiation process of classes and separate the creation of objects from the use process of objects.
+
+- Simple factory pattern, also known as static factory method pattern, belongs to class creation pattern. In simple factory mode, instances of different classes can be returned according to different parameters. The Simple Factory pattern specifically defines a class to create instances of other classes, which usually have a common parent class.
+
+- The simple factory pattern consists of three roles: the factory role is responsible for implementing the internal logic of creating all instances; the abstract product role is the parent class of all objects created and is responsible for describing the common interfaces shared by all instances; the specific product role is to create the goal, and all created objects act as one of the roles. Instances of body classes.
+
+- The point of the simple factory pattern is that when you need something, you just need to pass in a correct parameter to get the object you need without knowing the details of its creation.
+
+- The greatest advantage of simple factory mode is to realize the separation of object creation and object usage. The creation of object is entrusted to the special factory class. But its greatest disadvantage is that the factory class is not flexible enough. Adding new specific products needs to modify the judgment logic code of the factory class. Moreover, when there are more products, the factory method. The code will be very complex.
+
+- The application of simple factory mode includes: the factory class is responsible for creating fewer objects; the client only knows the parameters passed into the factory class, and does not care about how to create objects.
diff --git a/simple-factory/src/main/java/com/iluwater/simplefactory/Apple.java b/simple-factory/src/main/java/com/iluwater/simplefactory/Apple.java
new file mode 100644
index 000000000000..de30a740a0f7
--- /dev/null
+++ b/simple-factory/src/main/java/com/iluwater/simplefactory/Apple.java
@@ -0,0 +1,32 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.simplefactory;
+
+public class Apple implements Fruit{
+
+ @Override
+ public String whatIm() {
+ return "I am an apple!";
+ }
+
+}
diff --git a/simple-factory/src/main/java/com/iluwater/simplefactory/Fruit.java b/simple-factory/src/main/java/com/iluwater/simplefactory/Fruit.java
new file mode 100644
index 000000000000..3ba9a10579a4
--- /dev/null
+++ b/simple-factory/src/main/java/com/iluwater/simplefactory/Fruit.java
@@ -0,0 +1,27 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.simplefactory;
+
+public interface Fruit {
+ String whatIm();
+}
diff --git a/simple-factory/src/main/java/com/iluwater/simplefactory/FruitFactory.java b/simple-factory/src/main/java/com/iluwater/simplefactory/FruitFactory.java
new file mode 100644
index 000000000000..4fb78e31a21a
--- /dev/null
+++ b/simple-factory/src/main/java/com/iluwater/simplefactory/FruitFactory.java
@@ -0,0 +1,35 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.simplefactory;
+
+public class FruitFactory {
+
+ public Fruit createFruit(String type) {
+ if (type.equals("apple")) {//Produce Apple
+ return new Apple();
+ } else if (type.equals("pear")) {//Produce Pear
+ return new Pear();
+ }
+ return null;
+ }
+}
diff --git a/simple-factory/src/main/java/com/iluwater/simplefactory/Main.java b/simple-factory/src/main/java/com/iluwater/simplefactory/Main.java
new file mode 100644
index 000000000000..6762c5abbbed
--- /dev/null
+++ b/simple-factory/src/main/java/com/iluwater/simplefactory/Main.java
@@ -0,0 +1,34 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.simplefactory;
+
+public class Main {
+
+ public static void main(String[] args) {
+ FruitFactory mFactory = new FruitFactory();
+ Apple apple = (Apple) mFactory.createFruit("apple");//get apple
+ Pear pear = (Pear) mFactory.createFruit("pear");//get pear
+ System.out.println(apple.whatIm());
+ System.out.println(pear.whatIm());
+ }
+}
diff --git a/simple-factory/src/main/java/com/iluwater/simplefactory/Pear.java b/simple-factory/src/main/java/com/iluwater/simplefactory/Pear.java
new file mode 100644
index 000000000000..f41bf3869b13
--- /dev/null
+++ b/simple-factory/src/main/java/com/iluwater/simplefactory/Pear.java
@@ -0,0 +1,31 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.simplefactory;
+public class Pear implements Fruit{
+
+ @Override
+ public String whatIm() {
+ return "I am a pear!";
+ }
+
+}
| diff --git a/simple-factory/src/test/java/com/iluwater/simplefactory/SimpleFactorytest.java b/simple-factory/src/test/java/com/iluwater/simplefactory/SimpleFactorytest.java
new file mode 100644
index 000000000000..a79f737d4d3b
--- /dev/null
+++ b/simple-factory/src/test/java/com/iluwater/simplefactory/SimpleFactorytest.java
@@ -0,0 +1,57 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.simplefactory;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import main.Apple;
+import main.FruitFactory;
+import main.Pear;
+import org.junit.jupiter.api.Test;
+
+public class SimpleFactorytest {
+
+ FruitFactory mFactory = new FruitFactory();
+ Apple apple = (Apple) mFactory.createFruit("apple");
+ Pear pear = (Pear) mFactory.createFruit("pear");
+
+
+ @Test
+ public void testApple() {
+ assertEquals("class main.Apple", apple.getClass().toString());
+ assertEquals("I am an apple!", apple.whatIm());
+ }
+
+
+ @Test
+ public void testPear() {
+ assertEquals("class main.Pear", pear.getClass().toString());
+ assertEquals("I am a pear!", pear.whatIm());
+ }
+
+
+ @Test
+ public void testOther() {
+ assertEquals(null, mFactory.createFruit("banana"));
+ }
+}
| train | train | "2019-07-24T21:08:30" | "2019-07-08T13:40:50Z" | ac-ancheon | train |
iluwatar/java-design-patterns/761_920 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/761 | iluwatar/java-design-patterns/920 | [
"keyword_pr_to_issue"
] | 318f811fead95c4a363d776e968b0b1a4a112c86 | f1410337b570c6d444e98713036d13b53bdefe68 | [
"Yes, that is true. But I think that is the way the code is supposed to work. It allows creating one and only one instance, right?",
"Actually you can create another instance via `ThreadSafeDoubleCheckLocking.getInstance()`, or as many instances as possible via reflection.",
"Can someone verify this?",
"@iluwatar Sure. I will have a look at it.",
"I tried testing this and it is still possible to create multiple instances if only using reflection. I saw this solution on StackOverflow which will not allow reflection to access private methods and it worked for me.\r\n\r\nSo I made this change:\r\n\r\nprivate ThreadSafeDoubleCheckLocking() {\r\n // to prevent instantiating by Reflection call\r\n\t checkPermission();\r\n if (instance != null) {\r\n throw new IllegalStateException(\"Already initialized.\");\r\n }\r\n numOfInstances++;\r\n }\r\n \r\n void checkPermission() {\r\n Class self = sun.reflect.Reflection.getCallerClass(1);\r\n Class caller = sun.reflect.Reflection.getCallerClass(3);\r\n if (self != caller) {\r\n throw new java.lang.IllegalAccessError();\r\n }\r\n }\r\n\r\nI would really appreciate feedback. ",
"I think we can create multiple instances of a singleton class only in case of lazy initialization as in the above example.\r\nIf we change that to eager initialization, this check will be sufficient to create multiple instances of this class.",
"Using sun.reflect.Reflection is not recommended and I don't really understand why it is able to create multiple instances inspite of what you have done in the constructor to try to avoid it, but this is something that can be done. Using reflection is not allowed on Google App Engine, I just saw, so maybe people are working around the security threat in that way. I found this solution here btw, forgot to mention in the previous comment: https://stackoverflow.com/questions/7566626/how-to-restrict-developers-to-use-reflection-to-access-private-methods-and-const",
"@iluwatar May I pick this up?",
"@Azureyjt please go ahead",
"PR created. Please kindly review it :) @iluwatar "
] | [] | "2019-09-05T06:00:01Z" | [
"type: bug",
"info: help wanted"
] | ThreadSafeDoubleCheckLocking.java: Instantiating by Reflection call will be successful if you do that firstly | https://github.com/iluwatar/java-design-patterns/blob/987994f0fe5747e5524bc43c3b2000bee478c0c3/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java#L43-L45
Instance will be null, and you can create a singleton object by reflection without an exception. | [
"singleton/pom.xml",
"singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java"
] | [
"singleton/pom.xml",
"singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java"
] | [
"singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java"
] | diff --git a/singleton/pom.xml b/singleton/pom.xml
index e3d8f06e2ea5..038d6fdac040 100644
--- a/singleton/pom.xml
+++ b/singleton/pom.xml
@@ -38,5 +38,9 @@
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </dependency>
</dependencies>
</project>
diff --git a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java
index a7557fda37e0..6c17f7c3f001 100644
--- a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java
+++ b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java
@@ -35,12 +35,16 @@ public final class ThreadSafeDoubleCheckLocking {
private static volatile ThreadSafeDoubleCheckLocking instance;
+ private static boolean flag = true;
+
/**
* private constructor to prevent client from instantiating.
*/
private ThreadSafeDoubleCheckLocking() {
// to prevent instantiating by Reflection call
- if (instance != null) {
+ if (flag) {
+ flag = false;
+ } else {
throw new IllegalStateException("Already initialized.");
}
}
| diff --git a/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java b/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java
index 1d00d9f8f624..6286b09fb2a4 100644
--- a/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java
+++ b/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java
@@ -22,6 +22,11 @@
*/
package com.iluwatar.singleton;
+import org.junit.Test;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+
/**
* Date: 12/29/15 - 19:26 PM
*
@@ -36,4 +41,15 @@ public ThreadSafeDoubleCheckLockingTest() {
super(ThreadSafeDoubleCheckLocking::getInstance);
}
+ /**
+ * Test creating new instance by refection
+ */
+ @Test(expected = InvocationTargetException.class)
+ public void testCreatingNewInstanceByRefection() throws Exception {
+ ThreadSafeDoubleCheckLocking instance1 = ThreadSafeDoubleCheckLocking.getInstance();
+ Constructor constructor = ThreadSafeDoubleCheckLocking.class.getDeclaredConstructor();
+ constructor.setAccessible(true);
+ ThreadSafeDoubleCheckLocking instance2 = (ThreadSafeDoubleCheckLocking) constructor.newInstance(null);
+ }
+
}
\ No newline at end of file
| test | train | "2019-09-03T20:50:48" | "2018-06-24T06:57:35Z" | DovahYol | train |
iluwatar/java-design-patterns/915_921 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/915 | iluwatar/java-design-patterns/921 | [
"keyword_pr_to_issue"
] | 318f811fead95c4a363d776e968b0b1a4a112c86 | 88fae070e64dd90c94ed6008a7e15cd549badc17 | [
"@iluwatar , \r\nHi, can I look at this change? ",
"Yes @snehalatapandit ",
"Hi @iluwatar, it seems this is again failing for different link\r\nhttps://travis-ci.org/iluwatar/java-design-patterns/builds/583292258\r\nIn https://github.com/iluwatar/java-design-patterns/tree/master/partial-response credit section we are providing link for Partial Response in RESTful API Design and its respective URL is no more active and gives Page Not found error, hence Automagic is also failing\r\n\r\nDo let me know if I can take this up ?",
"Please go ahead @hbothra15 ",
"Done, and created a PR for the same"
] | [] | "2019-09-05T12:53:40Z" | [
"type: bug",
"epic: web site",
"info: good first issue",
"epic: build issue"
] | Fix broken links | The html-proofer that is included in Travis build indicates that we have some broken links.
```shell
Running ["HtmlCheck", "ImageCheck", "ScriptCheck", "LinkCheck"] on ["./_site/"] on *.html...
Checking 391 external links...
Ran on 133 files!
- ./_site/patterns/acyclic-visitor/index.html
* internally linking to ../visitor/README.md, which does not exist (line 1)
- ./_site/patterns/half-sync-half-async/index.html
* External link http://www.cs.wustl.edu/~schmidt/PDF/PLoP-95.pdf failed: 404 No error
- ./_site/patterns/intercepting-filter/index.html
* External link http://www.javagyan.com/tutorials/corej2eepatterns/presentation-tier-patterns failed: 403 No error
* External link https://struts.apache.org/docs/interceptors.html failed: 404 No error
htmlproofer 3.0.6 | Error: HTML-Proofer found 4 failures!
The command "bash cibuild.sh" exited with 1.
```
See full log at https://travis-ci.org/iluwatar/java-design-patterns/builds/565304449 | [
"half-sync-half-async/README.md",
"intercepting-filter/README.md"
] | [
"half-sync-half-async/README.md",
"intercepting-filter/README.md"
] | [] | diff --git a/half-sync-half-async/README.md b/half-sync-half-async/README.md
index 8a091f8133a3..ef463edadc6f 100644
--- a/half-sync-half-async/README.md
+++ b/half-sync-half-async/README.md
@@ -27,11 +27,11 @@ Use Half-Sync/Half-Async pattern when
## Real world examples
-* [BSD Unix networking subsystem](http://www.cs.wustl.edu/~schmidt/PDF/PLoP-95.pdf)
+* [BSD Unix networking subsystem](https://www.dre.vanderbilt.edu/~schmidt/PDF/PLoP-95.pdf)
* [Real Time CORBA](http://www.omg.org/news/meetings/workshops/presentations/realtime2001/4-3_Pyarali_thread-pool.pdf)
* [Android AsyncTask framework](http://developer.android.com/reference/android/os/AsyncTask.html)
## Credits
-* [Douglas C. Schmidt and Charles D. Cranor - Half Sync/Half Async](http://www.cs.wustl.edu/~schmidt/PDF/PLoP-95.pdf)
+* [Douglas C. Schmidt and Charles D. Cranor - Half Sync/Half Async](https://www.dre.vanderbilt.edu/~schmidt/PDF/PLoP-95.pdf)
* [Pattern Oriented Software Architecture Vol I-V](http://www.amazon.com/Pattern-Oriented-Software-Architecture-Volume-Patterns/dp/0471958697)
diff --git a/intercepting-filter/README.md b/intercepting-filter/README.md
index 0d35044de8a7..c287138953eb 100644
--- a/intercepting-filter/README.md
+++ b/intercepting-filter/README.md
@@ -30,9 +30,8 @@ Use the Intercepting Filter pattern when
## Real world examples
* [javax.servlet.FilterChain](https://tomcat.apache.org/tomcat-8.0-doc/servletapi/javax/servlet/FilterChain.html) and [javax.servlet.Filter](https://tomcat.apache.org/tomcat-8.0-doc/servletapi/javax/servlet/Filter.html)
-* [Struts 2 - Interceptors](https://struts.apache.org/docs/interceptors.html)
+* [Struts 2 - Interceptors](https://struts.apache.org/core-developers/interceptors.html)
## Credits
* [TutorialsPoint - Intercepting Filter](http://www.tutorialspoint.com/design_pattern/intercepting_filter_pattern.htm)
-* [Presentation Tier Patterns](http://www.javagyan.com/tutorials/corej2eepatterns/presentation-tier-patterns)
| null | test | train | "2019-09-03T20:50:48" | "2019-07-30T05:07:14Z" | iluwatar | train |
iluwatar/java-design-patterns/929_931 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/929 | iluwatar/java-design-patterns/931 | [
"keyword_pr_to_issue"
] | 5f39f7fbf71fd2799bb48384fc79efc4aba8e1ea | 3d62e02891d269890e86680b06b22033498d6bc6 | [] | [] | "2019-09-29T14:32:26Z" | [
"type: bug",
"info: help wanted"
] | half-sync-half-async pattern need to enhance | In the App class of half-sync-half-async pattern, the workers in threadpool is still running when the main thread has finished. This also makes the AppTest less effective (after the test, we expect to see task results, but we get nothing because junit will terminate jvm when the main thread has finished).
To improve on it, we can add a close method to the AsynchronousService class and call the method at the end of the main thread. I can create a PR, if needed. | [
"half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java",
"half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java"
] | [
"half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java",
"half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java"
] | [] | diff --git a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java
index 90cb5ecbfb0d..b24e29b6a55c 100644
--- a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java
+++ b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java
@@ -94,6 +94,8 @@ public static void main(String[] args) {
service.execute(new ArithmeticSumTask(500));
service.execute(new ArithmeticSumTask(2000));
service.execute(new ArithmeticSumTask(1));
+
+ service.close();
}
/**
diff --git a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java
index 4e2f9c23a6cd..3e64edd9894c 100644
--- a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java
+++ b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java
@@ -22,6 +22,9 @@
*/
package com.iluwatar.halfsynchalfasync;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
@@ -38,6 +41,7 @@
*/
public class AsynchronousService {
+ private static final Logger LOGGER = LoggerFactory.getLogger(AsynchronousService.class);
/*
* This represents the queuing layer as well as synchronous layer of the pattern. The thread pool
* contains worker threads which execute the tasks in blocking/synchronous manner. Long running
@@ -95,4 +99,16 @@ protected void done() {
}
});
}
+
+ /**
+ * Stops the pool of workers. This is a blocking call to wait for all tasks to be completed.
+ */
+ public void close() {
+ service.shutdown();
+ try {
+ service.awaitTermination(10, TimeUnit.SECONDS);
+ } catch (InterruptedException ie) {
+ LOGGER.error("Error waiting for executor service shutdown!");
+ }
+ }
}
| null | train | train | "2019-09-20T07:08:43" | "2019-09-28T04:05:40Z" | npczwh | train |
iluwatar/java-design-patterns/834_940 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/834 | iluwatar/java-design-patterns/940 | [
"keyword_pr_to_issue"
] | 823c58bef2197c30d7f8a40c2701973ee9a04ea2 | 05d0f0babfcb37fc46bc92c384db6e096d78ddca | [
"Hi,\r\n\r\nThis error is coming, because 'spring-boot-dependencies' dependency is redeclared inside dependencyManagement section of image-microservice project without specifying it's version. This dependency has already a version in the top parent pom.xml (https://github.com/iluwatar/java-design-patterns/blob/master/pom.xml).\r\n\r\nTo correct this issue remove dependencyManagement section from java-design-patterns\\api-gateway\\image-microservice\\pom.xml and declare this dependency in dependencies section of this pom.xml.\r\n\r\nKind Regards,\r\nNeeraj Mahajan",
"Hi,\r\nMaven build is still failing.\r\nI have found below modules in which the spring-boot-dependencies are redeclared in the 'dependencyManagement' section due to which the mavel build fails :\r\n1. 'aggregator-microservices\\aggregator-service\\pom.xml'\r\n2. 'aggregator-microservices\\information-microservice\\pom.xml'\r\n3. 'aggregator-microservices\\inventory-microservice\\pom.xml'\r\n4. 'api-gateway\\image-microservice\\pom.xml'\r\n5. 'api-gateway\\api-gateway-service\\pom.xml'\r\n6. 'api-gateway\\price-microservice\\pom.xml'\r\nThe build succeeds if the redeclaration is removed. Should these dependencies be removed.\r\n",
"I can fix this one!",
"Ok @perwramdemark "
] | [] | "2019-10-03T18:08:17Z" | [
"epic: ide issue"
] | Maven build fail - Project "image-microservice" pom.xml lack of version field | Hi. When I run "mvn eclipse:eclipse" in the base path to convert to eclipse project.
An error occur and it's error info as below.
`[ERROR] Failed to execute goal org.apache.maven.plugins:maven-eclipse-plugin:2.10:eclipse (default-cli) on project image-microservice: Execution default-cli of goal org.apache.maven.plugins:maven-eclipse-plugin:2.10:eclipse failed: For artifact {org.springframework.boot:spring-boot-dependencies:null:jar}: The version cannot be empty. -> [Help 1] `
Does the 'version' field is abscent?
The target dependency in java-design-patterns\api-gateway\image-microservice\pom.xml is:
## <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
</dependency>
## </dependencies>
| [
"aggregator-microservices/aggregator-service/pom.xml",
"aggregator-microservices/information-microservice/pom.xml",
"aggregator-microservices/inventory-microservice/pom.xml",
"api-gateway/api-gateway-service/pom.xml",
"api-gateway/image-microservice/pom.xml",
"api-gateway/price-microservice/pom.xml",
"pom.xml"
] | [
"aggregator-microservices/aggregator-service/pom.xml",
"aggregator-microservices/information-microservice/pom.xml",
"aggregator-microservices/inventory-microservice/pom.xml",
"api-gateway/api-gateway-service/pom.xml",
"api-gateway/image-microservice/pom.xml",
"api-gateway/price-microservice/pom.xml",
"pom.xml"
] | [] | diff --git a/aggregator-microservices/aggregator-service/pom.xml b/aggregator-microservices/aggregator-service/pom.xml
index dbe303809f9b..6ad8c3c8c5a4 100644
--- a/aggregator-microservices/aggregator-service/pom.xml
+++ b/aggregator-microservices/aggregator-service/pom.xml
@@ -32,18 +32,8 @@
<version>1.22.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
-
<artifactId>aggregator-service</artifactId>
<packaging>jar</packaging>
-
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-dependencies</artifactId>
- </dependency>
- </dependencies>
- </dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
@@ -74,7 +64,6 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
- <version>${spring-boot.version}</version>
<executions>
<execution>
<goals>
diff --git a/aggregator-microservices/information-microservice/pom.xml b/aggregator-microservices/information-microservice/pom.xml
index b15af35e4b82..54113d3ad2eb 100644
--- a/aggregator-microservices/information-microservice/pom.xml
+++ b/aggregator-microservices/information-microservice/pom.xml
@@ -36,14 +36,6 @@
<artifactId>information-microservice</artifactId>
<packaging>jar</packaging>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-dependencies</artifactId>
- </dependency>
- </dependencies>
- </dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
@@ -65,7 +57,6 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
- <version>${spring-boot.version}</version>
<executions>
<execution>
<goals>
diff --git a/aggregator-microservices/inventory-microservice/pom.xml b/aggregator-microservices/inventory-microservice/pom.xml
index 1791ee72c9e8..3a24e9540edf 100644
--- a/aggregator-microservices/inventory-microservice/pom.xml
+++ b/aggregator-microservices/inventory-microservice/pom.xml
@@ -32,18 +32,9 @@
<version>1.22.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
-
<artifactId>inventory-microservice</artifactId>
- <packaging>jar</packaging>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-dependencies</artifactId>
- </dependency>
- </dependencies>
- </dependencyManagement>
+ <packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
@@ -65,7 +56,6 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
- <version>${spring-boot.version}</version>
<executions>
<execution>
<goals>
diff --git a/api-gateway/api-gateway-service/pom.xml b/api-gateway/api-gateway-service/pom.xml
index 82aa6aedef80..44a8bde37923 100644
--- a/api-gateway/api-gateway-service/pom.xml
+++ b/api-gateway/api-gateway-service/pom.xml
@@ -34,15 +34,6 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>api-gateway-service</artifactId>
<packaging>jar</packaging>
-
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-dependencies</artifactId>
- </dependency>
- </dependencies>
- </dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
@@ -73,7 +64,6 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
- <version>${spring-boot.version}</version>
<executions>
<execution>
<goals>
diff --git a/api-gateway/image-microservice/pom.xml b/api-gateway/image-microservice/pom.xml
index c4367cdd8f45..4c897325d931 100644
--- a/api-gateway/image-microservice/pom.xml
+++ b/api-gateway/image-microservice/pom.xml
@@ -31,19 +31,9 @@
<groupId>com.iluwatar</groupId>
<version>1.22.0-SNAPSHOT</version>
</parent>
-
<modelVersion>4.0.0</modelVersion>
<artifactId>image-microservice</artifactId>
<packaging>jar</packaging>
-
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-dependencies</artifactId>
- </dependency>
- </dependencies>
- </dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
@@ -65,7 +55,6 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
- <version>${spring-boot.version}</version>
<executions>
<execution>
<goals>
diff --git a/api-gateway/price-microservice/pom.xml b/api-gateway/price-microservice/pom.xml
index 89aaba7ae7d4..21a68dc6efd3 100644
--- a/api-gateway/price-microservice/pom.xml
+++ b/api-gateway/price-microservice/pom.xml
@@ -36,14 +36,6 @@
<artifactId>price-microservice</artifactId>
<packaging>jar</packaging>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-dependencies</artifactId>
- </dependency>
- </dependencies>
- </dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
@@ -65,7 +57,6 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
- <version>${spring-boot.version}</version>
<executions>
<execution>
<goals>
diff --git a/pom.xml b/pom.xml
index ce773f61a243..5dfb1fff4376 100644
--- a/pom.xml
+++ b/pom.xml
@@ -211,11 +211,6 @@
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- <version>${spring-boot.version}</version>
- </dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
| null | val | train | "2019-10-02T09:53:57" | "2018-12-18T09:56:22Z" | zhangyuejia | train |
iluwatar/java-design-patterns/943_947 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/943 | iluwatar/java-design-patterns/947 | [
"timestamp(timedelta=108225.0, similarity=0.9053963176279485)"
] | 05d0f0babfcb37fc46bc92c384db6e096d78ddca | c24c0cbb9a60a4b3fe83373f92b262bfe096b694 | [
"I'll fix..",
"Thanks @perwramdemark, go ahead"
] | [] | "2019-10-04T04:52:40Z" | [
"info: good first issue",
"epic: build issue",
"epic: dependencies"
] | Java 11 support: Maven plugin upgrade | This task is part of the Java 11 transition plan https://github.com/iluwatar/java-design-patterns/wiki/16.-Java-11-Transition
We need to update the Maven plugins used in the build to versions that support Java 11. The plugins include at least
- maven-compiler-plugin
- jacoco-maven-plugin
- maven-checkstyle-plugin
- maven-surefire-plugin
- maven-pmd-plugin
- license-maven-plugin
| [
"pom.xml",
"trampoline/pom.xml"
] | [
"pom.xml",
"trampoline/pom.xml"
] | [] | diff --git a/pom.xml b/pom.xml
index 5dfb1fff4376..eb3b68c498fb 100644
--- a/pom.xml
+++ b/pom.xml
@@ -38,7 +38,7 @@
<junit-vintage.version>${junit.version}.2</junit-vintage.version>
<junit-platform.version>1.0.2</junit-platform.version>
<sping-test-junit5.version>1.0.2</sping-test-junit5.version>
- <compiler.version>3.0</compiler.version>
+ <compiler.version>3.8.0</compiler.version>
<jacoco.version>0.7.2.201409121644</jacoco.version>
<commons-dbcp.version>1.4</commons-dbcp.version>
<camel.version>2.16.1</camel.version>
@@ -357,15 +357,14 @@
</pluginManagement>
<plugins>
- <!-- Tell maven to compile using Java 8 -->
+ <!-- Tell maven to compile using Java 11 -->
<plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
<version>${compiler.version}</version>
- <configuration>
- <source>1.8</source>
- <target>1.8</target>
- </configuration>
+ <configuration>
+ <release>11</release>
+ </configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
diff --git a/trampoline/pom.xml b/trampoline/pom.xml
index e6f2e620afac..1bd675c30576 100644
--- a/trampoline/pom.xml
+++ b/trampoline/pom.xml
@@ -51,7 +51,7 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
- <version>1.16.18</version>
+ <version>1.18.2</version>
</dependency>
| null | train | train | "2019-10-03T20:50:50" | "2019-10-03T19:07:47Z" | iluwatar | train |
iluwatar/java-design-patterns/944_947 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/944 | iluwatar/java-design-patterns/947 | [
"timestamp(timedelta=119589.0, similarity=0.8487298047756754)"
] | 05d0f0babfcb37fc46bc92c384db6e096d78ddca | c24c0cbb9a60a4b3fe83373f92b262bfe096b694 | [
"@iluwatar compiling project with java 8 I don't get any other compiler warnings.",
"Yes, I can confirm. We can close this issue."
] | [] | "2019-10-04T04:52:40Z" | [
"type: bug",
"info: help wanted",
"info: good first issue",
"epic: build issue"
] | Java 11 support: Get rid of compiler warnings | This task is part of the Java 11 transition plan https://github.com/iluwatar/java-design-patterns/wiki/16.-Java-11-Transition
In this task we run the regular build and inspect the compiler output for warnings. We are especially interested in deprecation warnings, those are going to break things when Java version is updated. The target of the task is to get rid of as many warnings as possible. | [
"pom.xml",
"trampoline/pom.xml"
] | [
"pom.xml",
"trampoline/pom.xml"
] | [] | diff --git a/pom.xml b/pom.xml
index 5dfb1fff4376..eb3b68c498fb 100644
--- a/pom.xml
+++ b/pom.xml
@@ -38,7 +38,7 @@
<junit-vintage.version>${junit.version}.2</junit-vintage.version>
<junit-platform.version>1.0.2</junit-platform.version>
<sping-test-junit5.version>1.0.2</sping-test-junit5.version>
- <compiler.version>3.0</compiler.version>
+ <compiler.version>3.8.0</compiler.version>
<jacoco.version>0.7.2.201409121644</jacoco.version>
<commons-dbcp.version>1.4</commons-dbcp.version>
<camel.version>2.16.1</camel.version>
@@ -357,15 +357,14 @@
</pluginManagement>
<plugins>
- <!-- Tell maven to compile using Java 8 -->
+ <!-- Tell maven to compile using Java 11 -->
<plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
<version>${compiler.version}</version>
- <configuration>
- <source>1.8</source>
- <target>1.8</target>
- </configuration>
+ <configuration>
+ <release>11</release>
+ </configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
diff --git a/trampoline/pom.xml b/trampoline/pom.xml
index e6f2e620afac..1bd675c30576 100644
--- a/trampoline/pom.xml
+++ b/trampoline/pom.xml
@@ -51,7 +51,7 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
- <version>1.16.18</version>
+ <version>1.18.2</version>
</dependency>
| null | train | train | "2019-10-03T20:50:50" | "2019-10-03T19:12:41Z" | iluwatar | train |
iluwatar/java-design-patterns/941_947 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/941 | iluwatar/java-design-patterns/947 | [
"timestamp(timedelta=51.0, similarity=0.927590914655598)"
] | 05d0f0babfcb37fc46bc92c384db6e096d78ddca | c24c0cbb9a60a4b3fe83373f92b262bfe096b694 | [
"![image](https://user-images.githubusercontent.com/582346/66183018-eb094880-e67f-11e9-84eb-a66b36b008b8.png)\r\n"
] | [] | "2019-10-04T04:52:40Z" | [
"info: help wanted",
"type: support",
"epic: developer wiki",
"info: good first issue",
"epic: build issue"
] | Java 11 support: Maven version | This task is part of the Java 11 transition plan https://github.com/iluwatar/java-design-patterns/wiki/16.-Java-11-Transition
Find out what is the minimum Maven version that supports Java 11. Hopefully this information can be found on the Maven web site somewhere. | [
"pom.xml",
"trampoline/pom.xml"
] | [
"pom.xml",
"trampoline/pom.xml"
] | [] | diff --git a/pom.xml b/pom.xml
index 5dfb1fff4376..eb3b68c498fb 100644
--- a/pom.xml
+++ b/pom.xml
@@ -38,7 +38,7 @@
<junit-vintage.version>${junit.version}.2</junit-vintage.version>
<junit-platform.version>1.0.2</junit-platform.version>
<sping-test-junit5.version>1.0.2</sping-test-junit5.version>
- <compiler.version>3.0</compiler.version>
+ <compiler.version>3.8.0</compiler.version>
<jacoco.version>0.7.2.201409121644</jacoco.version>
<commons-dbcp.version>1.4</commons-dbcp.version>
<camel.version>2.16.1</camel.version>
@@ -357,15 +357,14 @@
</pluginManagement>
<plugins>
- <!-- Tell maven to compile using Java 8 -->
+ <!-- Tell maven to compile using Java 11 -->
<plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
<version>${compiler.version}</version>
- <configuration>
- <source>1.8</source>
- <target>1.8</target>
- </configuration>
+ <configuration>
+ <release>11</release>
+ </configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
diff --git a/trampoline/pom.xml b/trampoline/pom.xml
index e6f2e620afac..1bd675c30576 100644
--- a/trampoline/pom.xml
+++ b/trampoline/pom.xml
@@ -51,7 +51,7 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
- <version>1.16.18</version>
+ <version>1.18.2</version>
</dependency>
| null | train | train | "2019-10-03T20:50:50" | "2019-10-03T18:58:37Z" | iluwatar | train |
iluwatar/java-design-patterns/591_947 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/591 | iluwatar/java-design-patterns/947 | [
"timestamp(timedelta=124592.0, similarity=0.8593589023804361)"
] | 05d0f0babfcb37fc46bc92c384db6e096d78ddca | c24c0cbb9a60a4b3fe83373f92b262bfe096b694 | [
"There is now branch called `java9` where we aim to make the project work with JDK9. Pull requests helping towards that goal will be gratefully accepted.",
"The Java 9 build fails with the following output: \r\n[build.txt](https://github.com/iluwatar/java-design-patterns/files/1272821/build.txt)\r\n\r\nWith skip tests the build fails with the following output:\r\n[skiptests.txt](https://github.com/iluwatar/java-design-patterns/files/1272828/skiptests.txt)\r\n",
"List of changes for Java 9: https://docs.oracle.com/javase/9/whatsnew/toc.htm",
"The following commands install the Oracle's JDK9 EA on Ubuntu.\r\n\r\n```\r\nsudo add-apt-repository ppa:webupd8team/java\r\nsudo apt-get update\r\nsudo apt-get install oracle-java9-installer\r\n```\r\n\r\nI also had to edit .bashrc and set\r\n`export JAVA_HOME=/usr/lib/jvm/java-9-oracle/`\r\n\r\nAfter which Java version displays as follows\r\n```\r\n$ java -version\r\njava version \"9\"\r\nJava(TM) SE Runtime Environment (build 9+181)\r\nJava HotSpot(TM) 64-Bit Server VM (build 9+181, mixed mode)\r\n```\r\n\r\nListing installed Java versions and selecting the default Java version\r\n`sudo update-alternatives --config java`",
"I'll take a look at this issue",
"Ok @danielsiwiec ",
"@iluwatar the PR above makes `mvn test` pass. Tested with Java 9ea14-zulu",
"@iluwatar What else is needed for this issue to be resolved?",
"- We should switch to using JDK9 at some point. When is the proper time? Does Travis support it already? The Travis build file should be modified for this and `java9` branch merged to master.\r\n- How do we utilize the new Java 9 features? Separate issues should be created.",
"Tried the branch with openjdk-9 but the build fails with\r\n```\r\nUnrecognized option: --add-modules\r\nError: Could not create the Java Virtual Machine.\r\nError: A fatal exception has occurred. Program will exit.\r\n```",
"I hope this pom from my project can help you.\r\n\r\nhttps://github.com/javatlacati/datastrructureskotlin/blob/Java9/pom.xml",
"@iluwatar There is a sample shared at [SO-46084751](https://stackoverflow.com/questions/46084751/how-to-express-dependency-in-maven-on-java-ee-features-for-transition-to-java-9/46086920#46086920) on how to use the `--add-modules` to compiler args with Maven. Still curious to know what modules are you actually adding explicitly? (Reason being, one could look at the [JEP-320](http://openjdk.java.net/jeps/320) and see if using those dependencies could be the ideal state that the application should move to.)",
"Plans shifter to Java 11 support https://github.com/iluwatar/java-design-patterns/wiki/16.-Java-11-Transition"
] | [] | "2019-10-04T04:52:40Z" | [
"info: needs splitting",
"resolution: won't fix"
] | Java 9 support | Java 9 general availability is just a few months away and we should start migrating the codebase to work on top of that. This is a huge issue and needs more discussion, planning and splitting. | [
"pom.xml",
"trampoline/pom.xml"
] | [
"pom.xml",
"trampoline/pom.xml"
] | [] | diff --git a/pom.xml b/pom.xml
index 5dfb1fff4376..eb3b68c498fb 100644
--- a/pom.xml
+++ b/pom.xml
@@ -38,7 +38,7 @@
<junit-vintage.version>${junit.version}.2</junit-vintage.version>
<junit-platform.version>1.0.2</junit-platform.version>
<sping-test-junit5.version>1.0.2</sping-test-junit5.version>
- <compiler.version>3.0</compiler.version>
+ <compiler.version>3.8.0</compiler.version>
<jacoco.version>0.7.2.201409121644</jacoco.version>
<commons-dbcp.version>1.4</commons-dbcp.version>
<camel.version>2.16.1</camel.version>
@@ -357,15 +357,14 @@
</pluginManagement>
<plugins>
- <!-- Tell maven to compile using Java 8 -->
+ <!-- Tell maven to compile using Java 11 -->
<plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
<version>${compiler.version}</version>
- <configuration>
- <source>1.8</source>
- <target>1.8</target>
- </configuration>
+ <configuration>
+ <release>11</release>
+ </configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
diff --git a/trampoline/pom.xml b/trampoline/pom.xml
index e6f2e620afac..1bd675c30576 100644
--- a/trampoline/pom.xml
+++ b/trampoline/pom.xml
@@ -51,7 +51,7 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
- <version>1.16.18</version>
+ <version>1.18.2</version>
</dependency>
| null | train | train | "2019-10-03T20:50:50" | "2017-06-11T15:14:28Z" | iluwatar | train |
iluwatar/java-design-patterns/939_952 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/939 | iluwatar/java-design-patterns/952 | [
"keyword_pr_to_issue"
] | 218ba44dbfcaaacc12f11ec4830cf6cd13451388 | 933de30d42271f422a487b0a74d6d7ccf6053709 | [
"I can fix it!",
"Nice @perwramdemark, go ahead!",
"Related to https://github.com/iluwatar/java-design-patterns/issues/944"
] | [] | "2019-10-05T11:52:31Z" | [
"type: bug",
"info: good first issue",
"epic: build issue",
"epic: dependencies"
] | WARNING when building project | When building project with mvn install you get below warning. You need to setup the JXR plugin to get ride of this for multi-module projects.
[INFO] --- maven-pmd-plugin:3.6:pmd (pmd) @ abstract-factory ---
[WARNING] Unable to locate Source XRef to link to - DISABLED
Unable to locate Source XRef to link to - DISABLED | [
"pom.xml"
] | [
"pom.xml"
] | [] | diff --git a/pom.xml b/pom.xml
index d985b6c62fe2..874bf66dddee 100644
--- a/pom.xml
+++ b/pom.xml
@@ -465,6 +465,11 @@
<artifactId>maven-pmd-plugin</artifactId>
<version>${pmd.version}</version>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jxr-plugin</artifactId>
+ <version>3.0.0</version>
+ </plugin>
</plugins>
</reporting>
| null | train | train | "2019-10-05T13:23:20" | "2019-10-03T17:09:56Z" | perwramdemark | train |
iluwatar/java-design-patterns/954_957 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/954 | iluwatar/java-design-patterns/957 | [
"keyword_pr_to_issue"
] | 933de30d42271f422a487b0a74d6d7ccf6053709 | 94ca25462667b15d2d4f7d5120c94a0733f53bf7 | [
"Hi, I have created a pull request for this issue. ",
"https://github.com/iluwatar/java-design-patterns/pull/957",
"A lot of this stuff has just been migrated to community projects...\r\n\r\nShouldn't J-EE move to Jakarta? I didn't think J-EE was truly deprecated.\r\nJavaFX to https://openjfx.io/\r\n",
"@ryantheleach yes, I agree that stuff should be moved and not totally removed. Maybe an inaccurate term there in the issue subject..",
"Links:\r\nhttps://blog.codefx.org/java/java-9-migration-guide/#Dependencies-On-Java-EE-Modules\r\nhttps://jaxenter.com/jdk-11-java-ee-modules-140674.html"
] | [
"Please specify the version numbers in the main `pom.xml` dependencyManagement section",
"I have moved the version numbers to main pom.xml's dependencyManagement section and updated the pull request."
] | "2019-10-05T19:25:49Z" | [
"info: help wanted",
"info: good first issue",
"epic: dependencies"
] | Java 11 support: Get rid of JavaEE, Corba and JavaFX | This task is part of the Java 11 transition plan https://github.com/iluwatar/java-design-patterns/wiki/16.-Java-11-Transition
Java EE, Corba and JavaFX have been deprecated in newer JDK versions. Are there any dependencies to those in this project? If there is, we should get rid of them. (see https://blog.codefx.org/java/java-9-migration-guide/) | [
"pom.xml",
"repository/pom.xml"
] | [
"pom.xml",
"repository/pom.xml"
] | [] | diff --git a/pom.xml b/pom.xml
index f1a586eb8b34..acaaef6181c5 100644
--- a/pom.xml
+++ b/pom.xml
@@ -55,6 +55,8 @@
<aws-lambda-java-events.version>2.0.1</aws-lambda-java-events.version>
<jackson.version>2.8.5</jackson.version>
<pmd.version>3.12.0</pmd.version>
+ <jaxb-api.version>2.3.0</jaxb-api.version>
+ <annotation-api.version>1.3.1</annotation-api.version>
</properties>
<modules>
<module>abstract-factory</module>
@@ -298,6 +300,16 @@
<artifactId>mongo-java-driver</artifactId>
<version>${mongo-java-driver.version}</version>
</dependency>
+ <dependency>
+ <groupId>javax.xml.bind</groupId>
+ <artifactId>jaxb-api</artifactId>
+ <version>${jaxb-api.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.annotation</groupId>
+ <artifactId>javax.annotation-api</artifactId>
+ <version>${annotation-api.version}</version>
+ </dependency>
</dependencies>
</dependencyManagement>
diff --git a/repository/pom.xml b/repository/pom.xml
index 48bca0cf2ba8..2ccdc9da7ba5 100644
--- a/repository/pom.xml
+++ b/repository/pom.xml
@@ -63,5 +63,13 @@
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
+ <dependency>
+ <groupId>javax.xml.bind</groupId>
+ <artifactId>jaxb-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>javax.annotation</groupId>
+ <artifactId>javax.annotation-api</artifactId>
+ </dependency>
</dependencies>
</project>
| null | train | train | "2019-10-05T17:01:23" | "2019-10-05T15:08:36Z" | iluwatar | train |
iluwatar/java-design-patterns/549_958 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/549 | iluwatar/java-design-patterns/958 | [
"keyword_pr_to_issue"
] | 933de30d42271f422a487b0a74d6d7ccf6053709 | 60171e3c873257b86f66b0a67935321735d2c7d1 | [
"Can't we consider \r\n\r\n` try (CloseableHttpClient httpClient = HttpClients.createDefault()) {\r\n HttpGet httpGet = new HttpGet(\"http://localhost:51515/information\");\r\n try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {\r\n response = EntityUtils.toString(httpResponse.getEntity());\r\n }\r\n } catch (IOException e) {\r\n LOGGER.error(\"Exception caught.\", e);\r\n }`\r\n\r\nin com.iluwatar.aggregator.microservices.ProductInformationClientImpl as example of fallback strategy ([https://blogs.oracle.com/developers/getting-started-with-microservices-part-three](url))?\r\nOr do i not understand the task?",
"Has this issue been resolved?",
"@ddunig2 I don't see a PR against this. If you want to resolve, you can go ahead.",
"Hi, I am raising a PR for this, where ClientProtocolException is caught and the error log statements are updated.",
"https://github.com/iluwatar/java-design-patterns/pull/958",
"Exception handling was improved, but the original issue still remains unsolved",
"Under investigation by @jarpit96 ",
"@iluwatar @ddunig2 To implement fallback pattern in Aggregator Service, is returning default literals/constants sufficient ?",
"I would probably display an error message to the user in case one of the microservices does not respond or some other fault occurs",
"#971",
"I have added fall backs in Aggregator Service when other microservices fail. Default error messages (Product Title and Inventory) are returned to the user."
] | [] | "2019-10-05T19:57:19Z" | [
"type: enhancement",
"info: good first issue",
"epic: code quality"
] | "Aggregator microservices" design pattern doesn't show exception handling | "Aggregator microservices" design pattern doesn't show how exception handling would be done if the one or multiple services used are down and how client calling the aggregator microservice would cope in this situation. | [
"aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java",
"aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java"
] | [
"aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java",
"aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java"
] | [] | diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java
index 16849d529386..131fbf8695cd 100644
--- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java
+++ b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java
@@ -22,6 +22,7 @@
*/
package com.iluwatar.aggregator.microservices;
+import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
@@ -49,8 +50,10 @@ public String getProductTitle() {
try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
response = EntityUtils.toString(httpResponse.getEntity());
}
- } catch (IOException e) {
- LOGGER.error("Exception caught.", e);
+ } catch (ClientProtocolException cpe) {
+ LOGGER.error("ClientProtocolException Occured", cpe);
+ } catch (IOException ioe) {
+ LOGGER.error("IOException Occurred", ioe);
}
return response;
}
diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java
index 89f1a25e0580..780dccb78e20 100644
--- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java
+++ b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java
@@ -22,6 +22,7 @@
*/
package com.iluwatar.aggregator.microservices;
+import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
@@ -49,8 +50,10 @@ public int getProductInventories() {
try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
response = EntityUtils.toString(httpResponse.getEntity());
}
- } catch (IOException e) {
- LOGGER.error("Exception caught.", e);
+ } catch (ClientProtocolException cpe) {
+ LOGGER.error("ClientProtocolException Occured", cpe);
+ } catch (IOException ioe) {
+ LOGGER.error("IOException Occurred", ioe);
}
return Integer.parseInt(response);
}
| null | test | train | "2019-10-05T17:01:23" | "2017-03-26T17:51:56Z" | neerajmahajan | train |