From 1777058a9e225628691f842a4fddad79becc7288 Mon Sep 17 00:00:00 2001 From: Woonduk Kang Date: Fri, 2 Jan 2015 20:51:50 +0900 Subject: [PATCH] fix indent tab to space --- .../interceptor/LoggingInterceptor.java | 32 +- .../bootstrap/config/ExcludeUrlFilter.java | 84 +-- .../pinpoint/bootstrap/config/Filter.java | 4 +- .../bootstrap/config/HttpDumpConfig.java | 200 +++--- .../config/ProfilableClassFilter.java | 88 +-- .../pinpoint/bootstrap/config/SkipFilter.java | 8 +- .../pinpoint/bootstrap/context/Header.java | 122 ++-- .../instrument/InstrumentException.java | 24 +- .../NotFoundInstrumentException.java | 4 +- .../pinpoint/bootstrap/instrument/Type.java | 2 +- .../interceptor/MethodDescriptor.java | 20 +- .../bootstrap/util/InterceptorUtils.java | 20 +- .../bootstrap/ValidIdCheckerTest.java | 40 +- .../config/ExcludeUrlFilterTest.java | 48 +- .../config/ProfilableClassFilterTest.java | 50 +- .../bootstrap/config/ProfilerConfigTest.java | 12 +- .../interceptor/MockTraceContext.java | 16 +- .../cluster/AbstractClusterService.java | 12 +- .../cluster/ChannelContextClusterPoint.java | 114 +-- .../pinpoint/collector/cluster/Cluster.java | 6 +- .../collector/cluster/ClusterPoint.java | 4 +- .../cluster/ClusterPointLocator.java | 4 +- .../cluster/ClusterPointRepository.java | 62 +- .../collector/cluster/ClusterService.java | 10 +- .../collector/cluster/TargetClusterPoint.java | 10 +- .../collector/cluster/WebCluster.java | 126 ++-- .../collector/cluster/WorkerState.java | 16 +- .../collector/cluster/WorkerStateContext.java | 70 +- .../route/DefaultRouteFilterChain.java | 42 +- .../cluster/route/DefaultRouteHandler.java | 88 +-- .../cluster/route/LoggingFilter.java | 54 +- .../cluster/route/ResponseEvent.java | 32 +- .../collector/cluster/route/RouteEvent.java | 8 +- .../collector/cluster/route/RouteFilter.java | 4 +- .../cluster/route/RouteFilterChain.java | 8 +- .../collector/cluster/route/RouteHandler.java | 10 +- .../collector/cluster/route/RouteResult.java | 42 +- .../collector/cluster/route/RouteStatus.java | 52 +- .../cluster/zookeeper/ZookeeperClient.java | 362 +++++----- .../zookeeper/ZookeeperClusterService.java | 314 ++++---- .../zookeeper/ZookeeperEventWatcher.java | 2 +- .../zookeeper/ZookeeperLatestJobWorker.java | 668 +++++++++--------- .../ZookeeperProfilerClusterManager.java | 230 +++--- .../cluster/zookeeper/ZookeeperUtils.java | 56 +- .../zookeeper/ZookeeperWebClusterManager.java | 300 ++++---- .../zookeeper/exception/AuthException.java | 22 +- .../exception/BadOperationException.java | 22 +- .../exception/ConnectionException.java | 22 +- .../exception/PinpointZookeeperException.java | 24 +- .../zookeeper/exception/TimeoutException.java | 22 +- .../zookeeper/exception/UnknownException.java | 22 +- .../cluster/zookeeper/job/AbstractJob.java | 84 +-- .../cluster/zookeeper/job/DeleteJob.java | 8 +- .../collector/cluster/zookeeper/job/Job.java | 18 +- .../cluster/zookeeper/job/UpdateJob.java | 28 +- .../config/CollectorConfiguration.java | 48 +- .../dao/AgentIdApplicationIndexDao.java | 4 +- .../dao/ApplicationTraceIndexDao.java | 2 +- .../pinpoint/collector/dao/AutoFlusher.java | 94 +-- .../collector/dao/CachedStatisticsDao.java | 2 +- .../collector/dao/HostApplicationMapDao.java | 2 +- .../collector/dao/MapStatisticsCalleeDao.java | 2 +- .../collector/dao/MapStatisticsCallerDao.java | 2 +- .../HbaseAgentIdApplicationIndexDao.java | 36 +- .../dao/hbase/HbaseAgentInfoDao.java | 56 +- .../hbase/HbaseApplicationTraceIndexDao.java | 46 +- .../dao/hbase/HbaseHostApplicationMapDao.java | 18 +- .../dao/hbase/HbaseMapResponseTimeDao.java | 50 +- .../hbase/HbaseMapStatisticsCalleeDao.java | 48 +- .../hbase/HbaseMapStatisticsCallerDao.java | 52 +- .../collector/handler/AgentInfoHandler.java | 70 +- .../collector/handler/ApiMetaDataHandler.java | 32 +- .../pinpoint/collector/handler/Handler.java | 2 +- .../handler/RequestResponseHandler.java | 2 +- .../collector/handler/SimpleHandler.java | 2 +- .../collector/handler/SpanChunkHandler.java | 82 +-- .../collector/handler/SpanHandler.java | 46 +- .../collector/handler/SqlMetaDataHandler.java | 34 +- .../collector/handler/StatisticsHandler.java | 20 +- .../handler/StringMetaDataHandler.java | 32 +- .../mapper/ApplicationNameMapper.java | 26 +- .../collector/receiver/DataReceiver.java | 4 +- .../collector/receiver/DispatchHandler.java | 10 +- .../receiver/TcpDispatchHandler.java | 2 +- .../tcp/AgentHandshakePropertyType.java | 86 +-- .../collector/receiver/tcp/TCPReceiver.java | 76 +- .../receiver/udp/AbstractUDPReceiver.java | 2 +- .../collector/util/CollectorUtils.java | 16 +- ...HbaseApplicationTrraceIndexColumnTest.java | 62 +- .../receiver/udp/NettyUdpReceiverTest.java | 6 +- .../receiver/udp/UDPReceiverTest.java | 30 +- .../pinpoint/common/HistogramSchema.java | 40 +- .../pinpoint/common/ServiceType.java | 26 +- .../pinpoint/common/ServiceTypeConstants.java | 6 +- .../navercorp/pinpoint/common/SlotType.java | 2 +- .../navercorp/pinpoint/common/bo/Span.java | 10 +- .../navercorp/pinpoint/common/bo/SpanBo.java | 28 +- .../pinpoint/common/bo/SpanEventBo.java | 316 ++++----- .../pinpoint/common/hbase/HbaseTemplate2.java | 28 +- .../hbase/LimitRowMapperResultsExtractor.java | 46 +- ...plicationTraceIndexResponseTimeFilter.java | 80 +-- .../pinpoint/common/util/AnnotationUtils.java | 4 +- .../pinpoint/common/util/BytesUtils.java | 24 +- .../common/util/DelegateEnumeration.java | 152 ++-- .../common/util/EmptyEnumeration.java | 34 +- .../pinpoint/common/util/JvmUtils.java | 56 +- .../pinpoint/common/util/JvmVersion.java | 94 +-- .../pinpoint/common/util/NetUtils.java | 236 +++---- .../common/util/NextElementAction.java | 2 +- .../util/NoSuchElementExceptionAction.java | 8 +- .../common/util/NullNextElementAction.java | 8 +- .../pinpoint/common/util/SpanUtils.java | 42 +- .../common/util/SystemPropertyKey.java | 40 +- .../common/util/TransactionIdUtils.java | 12 +- .../pinpoint/common/ServiceTypeTest.java | 6 +- .../common/bo/AgentStatCpuLoadBoTest.java | 132 ++-- .../common/bo/AgentStatMemoryGcBoTest.java | 54 +- .../common/buffer/AutomaticBufferTest.java | 2 +- .../common/util/DelegateEnumerationTest.java | 260 +++---- .../pinpoint/common/util/JvmVersionTest.java | 178 ++--- .../common/util/TransactionIdUtilsTest.java | 20 +- .../cpu/metric/EnhancedCpuLoadMetricSet.java | 46 +- .../profiler/AgentHandshakePropertyType.java | 90 +-- .../profiler/AgentInfoSenderListener.java | 60 +- .../pinpoint/profiler/AgentInformation.java | 24 +- .../profiler/AgentInformationFactory.java | 14 +- .../pinpoint/profiler/AgentStatus.java | 6 +- .../pinpoint/profiler/ClassFileFilter.java | 6 +- .../pinpoint/profiler/DefaultAgent.java | 10 +- .../profiler/DefaultClassFileFilter.java | 52 +- .../profiler/context/DefaultTrace.java | 2 +- .../profiler/context/DefaultTraceId.java | 52 +- .../pinpoint/profiler/context/Span.java | 8 +- .../interceptor/bci/AspectWeaverClass.java | 330 ++++----- .../modifier/DefaultModifierRegistry.java | 146 ++-- .../pinpoint/profiler/modifier/Modifier.java | 2 +- .../modifier/arcus/ArcusClientModifier.java | 48 +- .../arcus/MemcachedClientModifier.java | 54 +- .../arcus/interceptor/AddOpInterceptor.java | 22 +- .../arcus/interceptor/ApiInterceptor.java | 6 +- .../BaseOperationCancelInterceptor.java | 44 +- .../BaseOperationConstructInterceptor.java | 30 +- ...seOperationTransitionStateInterceptor.java | 156 ++-- .../CacheManagerConstructInterceptor.java | 16 +- .../interceptor/FutureGetInterceptor.java | 38 +- .../FutureSetOperationInterceptor.java | 14 +- .../SetCacheManagerInterceptor.java | 28 +- .../AsyncHttpClientModifier.java | 42 +- .../ExecuteRequestInterceptor.java | 602 ++++++++-------- .../httpclient4/BasicFutureModifier.java | 66 +- .../ClosableHttpAsyncClientModifier.java | 100 +-- .../InternalHttpAsyncClientModifier.java | 66 +- .../AsyncClientExecuteInterceptor.java | 32 +- ...AsyncInternalClientExecuteInterceptor.java | 90 +-- .../BasicFutureCompletedInterceptor.java | 106 +-- .../BasicFutureFailedInterceptor.java | 106 +-- .../BasicFutureGetInterceptor.java | 140 ++-- .../HttpUriRequestExecuteInterceptor.java | 100 +-- .../HttpURLConnectionModifier.java | 38 +- .../interceptor/ConnectMethodInterceptor.java | 76 +- .../modifier/db/DefaultDatabaseInfo.java | 42 +- .../profiler/modifier/db/JDBCUrlParser.java | 8 +- .../db/cubrid/CubridConnectionModifier.java | 40 +- .../cubrid/CubridConnectionStringParser.java | 30 +- .../db/cubrid/CubridDriverModifier.java | 40 +- .../CubridPreparedStatementModifier.java | 78 +- .../db/cubrid/CubridResultSetModifier.java | 26 +- .../db/cubrid/CubridStatementModifier.java | 46 +- .../db/cubrid/CubridUStatementModifier.java | 42 +- .../modifier/method/MethodModifier.java | 54 +- .../method/interceptor/MethodInterceptor.java | 48 +- .../orm/SqlMapOperationInterceptor.java | 24 +- .../orm/ibatis/IbatisClientModifier.java | 46 +- .../orm/ibatis/SqlMapClientImplModifier.java | 28 +- .../orm/ibatis/SqlMapSessionImplModifier.java | 24 +- .../orm/ibatis/filter/IbatisInterfaceApi.java | 62 +- .../orm/ibatis/filter/IbatisMethodFilter.java | 64 +- .../filter/SqlMapClientMethodFilter.java | 16 +- .../filter/SqlMapSessionMethodFilter.java | 20 +- .../IbatisSqlMapOperationInterceptor.java | 6 +- .../mybatis/SqlSessionTemplateModifier.java | 16 +- .../filter/SqlSessionMethodFilter.java | 62 +- .../MyBatisSqlMapOperationInterceptor.java | 8 +- .../modifier/servlet/FilterModifier.java | 44 +- .../modifier/servlet/HttpServletModifier.java | 42 +- .../SpringFrameworkServletModifier.java | 44 +- .../interceptor/HttpServletInterceptor.java | 50 +- .../ibatis/SqlMapClientTemplateModifier.java | 64 +- .../tomcat/RequestFacadeModifier.java | 40 +- .../tomcat/StandardServiceModifier.java | 4 +- .../tomcat/TomcatConnectorModifier.java | 22 +- .../modifier/tomcat/WebappLoaderModifier.java | 4 +- .../tomcat/aspect/RequestFacadeAspect.java | 52 +- .../StandardHostValveInvokeInterceptor.java | 18 +- .../profiler/monitor/CounterMonitor.java | 16 +- .../profiler/monitor/EventRateMonitor.java | 14 +- .../profiler/monitor/HistogramMonitor.java | 8 +- .../profiler/monitor/MonitorName.java | 22 +- .../profiler/monitor/MonitorRegistry.java | 8 +- .../codahale/MetricCounterMonitor.java | 70 +- .../codahale/MetricEventRateMonitor.java | 62 +- .../codahale/MetricHistogramMonitor.java | 54 +- .../cpu/metric/DefaultCpuLoadMetricSet.java | 110 +-- .../monitor/codahale/gc/GarbageCollector.java | 4 +- .../profiler/receiver/CommandDispatcher.java | 2 +- .../receiver/ProfilerCommandService.java | 4 +- .../ProfilerCommandServiceLocator.java | 10 +- .../ProfilerRequestCommandService.java | 4 +- .../ProfilerSimpleCommandService.java | 4 +- .../receiver/service/EchoService.java | 26 +- .../profiler/sender/AbstractDataSender.java | 100 +-- .../profiler/sender/LoggingDataSender.java | 38 +- .../profiler/sender/TcpDataSender.java | 82 +-- .../profiler/sender/UdpDataSender.java | 78 +- .../tools/NetworkAvailabilityChecker.java | 4 +- .../pinpoint/profiler/util/ApiUtils.java | 76 +- .../profiler/util/QueryStringUtil.java | 2 +- .../profiler/util/StackTraceUtil.java | 12 +- .../bindvalue/converter/BytesConverter.java | 30 +- .../bindvalue/converter/ObjectConverter.java | 70 +- .../pinpoint/test/BaseInterceptorTest.java | 64 +- .../test/MockTraceContextFactory.java | 6 +- .../profiler/DefaultClassFileFilterTest.java | 30 +- .../pinpoint/profiler/context/HeaderTest.java | 58 +- .../bci/AspectWeaverClassTest.java | 240 +++---- .../interceptor/bci/JavaAssistTest.java | 2 +- .../profiler/interceptor/bci/TestObject.java | 64 +- .../interceptor/bci/mock/ErrorAspect.java | 12 +- .../interceptor/bci/mock/ErrorAspect2.java | 14 +- .../bci/mock/ErrorAspect_InvalidExtents.java | 12 +- .../interceptor/bci/mock/Original.java | 114 +-- .../interceptor/bci/mock/OriginalSub.java | 6 +- .../interceptor/bci/mock/TestAspect.java | 112 +-- .../bci/mock/TestAspect_ExtentsSub.java | 16 +- .../bci/mock/TestAspect_NoExtents.java | 12 +- .../arcus/interceptor/ApiInterceptorTest.java | 66 +- .../interceptor/FutureGetInterceptorTest.java | 212 +++--- .../ibatis/SqlMapClientImplModifierTest.java | 470 ++++++------ .../ibatis/SqlMapSessionImplModifierTest.java | 516 +++++++------- .../DefaultSqlSessionModifierTest.java | 44 +- .../mybatis/MyBatisClientModifierTest.java | 470 ++++++------ .../SqlSessionTemplateModifierTest.java | 174 ++--- .../aspect/RequestFacadeAspectTest.java | 90 +-- .../codahale/MetricMonitorRegistryTest.java | 178 ++--- .../gc/GarbageCollectorFactoryTest.java | 4 +- .../sender/TcpDataSenderReconnectTest.java | 22 +- .../profiler/sender/TcpDataSenderTest.java | 18 +- .../navercorp/pinpoint/rpc/DefaultFuture.java | 40 +- .../RequestResponseServerMessageListener.java | 6 +- ...yPinpointSocketReconnectEventListener.java | 8 +- .../pinpoint/rpc/client/MessageListener.java | 4 +- .../pinpoint/rpc/client/PinpointSocket.java | 42 +- .../rpc/client/PinpointSocketFactory.java | 62 +- .../rpc/client/PinpointSocketHandler.java | 6 +- .../PinpointSocketReconnectEventListener.java | 12 +- .../client/ReconnectStateSocketHandler.java | 32 +- .../client/SimpleLoggingMessageListener.java | 16 +- .../pinpoint/rpc/client/SocketHandler.java | 8 +- .../navercorp/pinpoint/rpc/client/State.java | 26 +- .../pinpoint/rpc/codec/PacketDecoder.java | 22 +- .../rpc/control/ControlMessageDecoder.java | 138 ++-- .../rpc/control/ControlMessageEncoder.java | 274 +++---- .../ControlMessageProtocolConstant.java | 22 +- .../rpc/packet/ControlHandshakePacket.java | 94 +-- .../ControlHandshakeResponsePacket.java | 94 +-- .../pinpoint/rpc/packet/ControlPacket.java | 22 +- .../rpc/packet/stream/BasicStreamPacket.java | 102 +-- .../rpc/packet/stream/StreamClosePacket.java | 84 +-- .../packet/stream/StreamCreateFailPacket.java | 84 +-- .../rpc/packet/stream/StreamCreatePacket.java | 72 +- .../stream/StreamCreateSuccessPacket.java | 50 +- .../rpc/packet/stream/StreamPingPacket.java | 88 +-- .../rpc/packet/stream/StreamPongPacket.java | 88 +-- .../packet/stream/StreamResponsePacket.java | 72 +- .../pinpoint/rpc/server/ChannelContext.java | 168 ++--- .../DoNothingChannelStateEventListener.java | 14 +- .../rpc/server/PinpointServerSocket.java | 254 +++---- .../rpc/server/PinpointServerSocketState.java | 126 ++-- .../server/PinpointServerSocketStateCode.java | 136 ++-- .../pinpoint/rpc/server/SocketChannel.java | 22 +- ...SocketChannelStateChangeEventListener.java | 4 +- .../rpc/stream/ClientStreamChannel.java | 36 +- .../stream/ClientStreamChannelContext.java | 30 +- .../ClientStreamChannelMessageListener.java | 4 +- ...ledServerStreamChannelMessageListener.java | 24 +- .../LoggingStreamChannelMessageListener.java | 48 +- .../rpc/stream/ServerStreamChannel.java | 36 +- .../stream/ServerStreamChannelContext.java | 18 +- .../ServerStreamChannelMessageListener.java | 4 +- .../rpc/stream/StreamChannelContext.java | 50 +- .../rpc/stream/StreamChannelManager.java | 454 ++++++------ .../rpc/stream/StreamChannelState.java | 102 +-- .../rpc/stream/StreamChannelStateCode.java | 38 +- .../pinpoint/rpc/util/ClassUtils.java | 174 ++--- .../rpc/util/ControlMessageEncodingUtils.java | 20 +- .../pinpoint/rpc/util/CopyUtils.java | 36 +- .../pinpoint/rpc/util/IDGenerator.java | 54 +- .../navercorp/pinpoint/rpc/util/MapUtils.java | 56 +- .../navercorp/pinpoint/rpc/FutureTest.java | 60 +- .../RecordedStreamChannelMessageListener.java | 16 +- .../rpc/client/PinpointSocketHandlerTest.java | 2 +- .../pinpoint/rpc/client/ReconnectTest.java | 14 +- .../server/AgentHandshakePropertyType.java | 86 +-- .../rpc/server/ControlPacketServerTest.java | 384 +++++----- .../rpc/server/EventListenerTest.java | 246 +++---- .../rpc/server/MessageListenerTest.java | 528 +++++++------- .../server/PinpointServerSocketStateTest.java | 128 ++-- .../rpc/stream/StreamChannelManagerTest.java | 462 ++++++------ .../rpc/stream/StreamChannelStateTest.java | 104 +-- .../pinpoint/rpc/util/CopyUtilsTest.java | 84 +-- .../pinpoint/rpc/util/IDGeneratorTest.java | 30 +- .../ChunkHeaderTBaseDeserializerFactory.java | 4 +- ...CommandHeaderTBaseDeserializerFactory.java | 22 +- .../CommandHeaderTBaseSerializerFactory.java | 30 +- .../thrift/io/DefaultTBaseLocator.java | 44 +- .../io/HeaderTBaseDeserializerFactory.java | 4 +- .../thrift/io/HeaderTBaseSerializer.java | 12 +- .../io/NetworkAvailabilityCheckPacket.java | 90 +-- .../pinpoint/thrift/io/TBaseLocator.java | 12 +- .../pinpoint/thrift/io/TCommandRegistry.java | 86 +-- .../pinpoint/thrift/io/TCommandType.java | 120 ++-- .../thrift/io/TCommandTypeVersion.java | 124 ++-- .../io/UnsafeByteArrayOutputStream.java | 296 ++++---- .../HeaderTBaseDeserializerFactoryTest.java | 28 +- .../thrift/io/HeaderTBaseSerializerTest.java | 16 +- .../thrift/io/TCommandRegistryTest.java | 86 +-- .../thrift/io/TCommandTypeVersionTest.java | 54 +- .../web/alarm/checker/SlowRateChecker.java | 6 +- .../navercorp/pinpoint/web/alarm/vo/Rule.java | 142 ++-- .../web/applicationmap/ApplicationMap.java | 16 +- .../pinpoint/web/applicationmap/Link.java | 28 +- .../pinpoint/web/applicationmap/Node.java | 24 +- .../web/applicationmap/ServerInstance.java | 26 +- .../applicationmap/ServerInstanceList.java | 72 +- .../applicationmap/histogram/Histogram.java | 54 +- .../rawdata/AgentHistogram.java | 26 +- .../applicationmap/rawdata/LinkCallData.java | 6 +- .../web/applicationmap/rawdata/LinkData.java | 30 +- .../rawdata/LinkDataDuplexMap.java | 4 +- .../applicationmap/rawdata/LinkDataMap.java | 12 +- .../pinpoint/web/batch/JobLaunchSupport.java | 108 +-- .../pinpoint/web/calltree/span/SpanAlign.java | 70 +- .../web/calltree/span/SpanAligner2.java | 46 +- .../pinpoint/web/cluster/ClusterManager.java | 6 +- .../CollectorClusterInfoRepository.java | 106 +-- .../cluster/zookeeper/ZookeeperClient.java | 280 ++++---- .../zookeeper/ZookeeperClusterManager.java | 548 +++++++------- .../zookeeper/exception/AuthException.java | 22 +- .../exception/BadOperationException.java | 22 +- .../exception/ConnectionException.java | 22 +- .../exception/PinpointZookeeperException.java | 22 +- .../zookeeper/exception/TimeoutException.java | 22 +- .../zookeeper/exception/UnknownException.java | 22 +- .../pinpoint/web/config/WebConfig.java | 122 ++-- .../web/controller/AdminController.java | 60 +- .../BusinessTransactionController.java | 100 +-- .../web/controller/CommandController.java | 332 ++++----- .../web/controller/FilteredMapController.java | 84 +-- .../web/controller/MainController.java | 22 +- .../web/controller/MapController.java | 116 +-- .../controller/ScatterChartController.java | 278 ++++---- .../pinpoint/web/dao/ApplicationIndexDao.java | 12 +- .../web/dao/ApplicationTraceIndexDao.java | 30 +- .../web/dao/MapStatisticsCalleeDao.java | 4 +- .../web/dao/MapStatisticsCallerDao.java | 4 +- .../web/dao/hbase/HbaseAgentInfoDao.java | 58 +- .../web/dao/hbase/HbaseAgentStatDao.java | 64 +- .../dao/hbase/HbaseApplicationIndexDao.java | 54 +- .../hbase/HbaseApplicationTraceIndexDao.java | 232 +++--- .../dao/hbase/HbaseHostApplicationMapDao.java | 30 +- .../hbase/HbaseMapStatisticsCalleeDao.java | 106 +-- .../hbase/HbaseMapStatisticsCallerDao.java | 104 +-- .../pinpoint/web/dao/hbase/HbaseTraceDao.java | 88 +-- .../web/filter/DefaultFilterBuilder.java | 136 ++-- .../navercorp/pinpoint/web/filter/Filter.java | 14 +- .../pinpoint/web/filter/FilterBuilder.java | 4 +- .../pinpoint/web/filter/FilterChain.java | 66 +- .../pinpoint/web/filter/FilterDescriptor.java | 330 ++++----- .../pinpoint/web/filter/FilterHint.java | 48 +- .../pinpoint/web/filter/FromToFilter.java | 140 ++-- .../web/filter/FromToResponseFilter.java | 424 +++++------ .../pinpoint/web/filter/URLPatternFilter.java | 62 +- .../pinpoint/web/mapper/AgentIdMapper.java | 16 +- .../web/mapper/ApplicationNameMapper.java | 12 +- .../web/mapper/HostApplicationMapper.java | 22 +- .../web/mapper/HostApplicationMapperVer2.java | 10 +- .../web/mapper/MapStatisticsCalleeMapper.java | 10 +- .../web/mapper/MapStatisticsCallerMapper.java | 10 +- .../web/mapper/TraceIndexScatterMapper.java | 24 +- .../web/mapper/TraceIndexScatterMapper2.java | 80 +-- .../web/mapper/TransactionIdMapper.java | 50 +- .../web/server/PinpointSocketManager.java | 250 +++---- .../pinpoint/web/service/AdminService.java | 6 +- .../web/service/AdminServiceImpl.java | 14 +- .../web/service/AgentInfoService.java | 2 +- .../web/service/AgentInfoServiceImpl.java | 92 +-- .../web/service/CommonServiceImpl.java | 12 +- .../web/service/FilteredMapServiceImpl.java | 22 +- .../web/service/ScatterChartServiceImpl.java | 80 +-- .../pinpoint/web/service/SpanServiceImpl.java | 340 ++++----- .../web/service/TransactionInfoService.java | 4 +- .../service/TransactionInfoServiceImpl.java | 214 +++--- .../web/servletfilter/NoCacheFilter.java | 28 +- .../pinpoint/web/vo/AgentStatus.java | 34 +- .../pinpoint/web/vo/Application.java | 24 +- .../pinpoint/web/vo/BusinessTransaction.java | 104 +-- .../pinpoint/web/vo/BusinessTransactions.java | 44 +- .../pinpoint/web/vo/LimitedScanResult.java | 24 +- .../navercorp/pinpoint/web/vo/LoadFactor.java | 210 +++--- .../com/navercorp/pinpoint/web/vo/Range.java | 2 +- .../pinpoint/web/vo/ResponseTimeRange.java | 116 +-- .../pinpoint/web/vo/SelectedScatterArea.java | 116 +-- .../com/navercorp/pinpoint/web/vo/Trace.java | 42 +- .../pinpoint/web/vo/TransactionId.java | 42 +- .../pinpoint/web/vo/callstacks/Record.java | 114 +-- .../pinpoint/web/vo/callstacks/RecordSet.java | 56 +- .../web/vo/linechart/DownSampler.java | 8 +- .../web/vo/linechart/DownSamplers.java | 24 +- .../pinpoint/web/vo/scatter/Dot.java | 26 +- .../pinpoint/web/alarm/MainCategoryTest.java | 18 +- .../pinpoint/web/cluster/ClusterTest.java | 262 +++---- .../zookeeper/ZookeeperClusterTest.java | 314 ++++---- .../dao/hbase/filter/PrefixFilterTest.java | 40 +- .../web/filter/FilterDescriptorTest.java | 82 +-- .../pinpoint/web/filter/FilterHintTest.java | 78 +- .../navercorp/pinpoint/web/path/PathTest.java | 88 +-- .../pinpoint/web/vo/TransactionIdTest.java | 92 +-- 427 files changed, 14796 insertions(+), 14796 deletions(-) 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 8de0d6a51..58e732bde 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 @@ -25,25 +25,25 @@ import java.util.logging.Logger; */ public class LoggingInterceptor implements StaticAroundInterceptor, SimpleAroundInterceptor { - private final Logger logger; + private final Logger logger; - public LoggingInterceptor(String loggerName) { - this.logger = Logger.getLogger(loggerName); - } + public LoggingInterceptor(String loggerName) { + this.logger = Logger.getLogger(loggerName); + } - @Override - public void before(Object target, String className, String methodName, String parameterDescription, Object[] args) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("before " + defaultString(target) + " " + className + "." + methodName + parameterDescription + " args:" + Arrays.toString(args)); - } - } + @Override + public void before(Object target, String className, String methodName, String parameterDescription, Object[] args) { + if (logger.isLoggable(Level.FINE)) { + logger.fine("before " + defaultString(target) + " " + className + "." + methodName + parameterDescription + " args:" + Arrays.toString(args)); + } + } - @Override - public void after(Object target, String className, String methodName, String parameterDescription, Object[] args, Object result, Throwable throwable) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("after " + defaultString(target) + " " + className + "." + methodName + parameterDescription + " args:" + Arrays.toString(args) + " result:" + result + " Throwable:" + throwable); - } - } + @Override + public void after(Object target, String className, String methodName, String parameterDescription, Object[] args, Object result, Throwable throwable) { + if (logger.isLoggable(Level.FINE)) { + logger.fine("after " + defaultString(target) + " " + className + "." + methodName + parameterDescription + " args:" + Arrays.toString(args) + " result:" + result + " Throwable:" + throwable); + } + } @Override public void before(Object target, Object[] args) { diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/ExcludeUrlFilter.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/ExcludeUrlFilter.java index f4ec14184..49835f2a1 100644 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/ExcludeUrlFilter.java +++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/ExcludeUrlFilter.java @@ -25,53 +25,53 @@ import java.util.List; */ public class ExcludeUrlFilter implements Filter { - private final List excludeUrlList; + private final List excludeUrlList; - public ExcludeUrlFilter(String excludeFormat) { - this(excludeFormat, ","); - } + public ExcludeUrlFilter(String excludeFormat) { + this(excludeFormat, ","); + } - public ExcludeUrlFilter(String excludeFormat, String separator) { - if (isEmpty(excludeFormat)) { - this.excludeUrlList = Collections.emptyList(); - return; - } - final String[] split = excludeFormat.split(separator); - final List buildList = new ArrayList(); - for (String value : split) { - if (isEmpty(value)) { - continue; - } - value = value.trim(); - if (value.isEmpty()) { - continue; - } - buildList.add(value); - } + public ExcludeUrlFilter(String excludeFormat, String separator) { + if (isEmpty(excludeFormat)) { + this.excludeUrlList = Collections.emptyList(); + return; + } + final String[] split = excludeFormat.split(separator); + final List buildList = new ArrayList(); + for (String value : split) { + if (isEmpty(value)) { + continue; + } + value = value.trim(); + if (value.isEmpty()) { + continue; + } + buildList.add(value); + } - this.excludeUrlList = buildList; - } + this.excludeUrlList = buildList; + } - private boolean isEmpty(String string) { - return string == null || string.isEmpty(); - } + private boolean isEmpty(String string) { + return string == null || string.isEmpty(); + } - @Override - public boolean filter(String requestURI) { - for (String excludeUrl : this.excludeUrlList) { - if (excludeUrl.equals(requestURI)) { - return FILTERED; - } - } - return false; - } + @Override + public boolean filter(String requestURI) { + for (String excludeUrl : this.excludeUrlList) { + if (excludeUrl.equals(requestURI)) { + return FILTERED; + } + } + return false; + } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("ExcludeUrlFilter{"); - sb.append("excludeUrlList=").append(excludeUrlList); - sb.append('}'); - return sb.toString(); - } + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("ExcludeUrlFilter{"); + sb.append("excludeUrlList=").append(excludeUrlList); + sb.append('}'); + return sb.toString(); + } } diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/Filter.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/Filter.java index 931bf49db..f7635d4fe 100644 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/Filter.java +++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/Filter.java @@ -20,7 +20,7 @@ package com.navercorp.pinpoint.bootstrap.config; * @author emeroad */ public interface Filter { - public static final boolean FILTERED = true; + public static final boolean FILTERED = true; - boolean filter(T value); + boolean filter(T value); } diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/HttpDumpConfig.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/HttpDumpConfig.java index 94ecfc52e..df87580b7 100644 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/HttpDumpConfig.java +++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/HttpDumpConfig.java @@ -26,135 +26,135 @@ import com.navercorp.pinpoint.bootstrap.util.SimpleSamplerFactory; */ public class HttpDumpConfig { - public static HttpDumpConfig getDefault() { - HttpDumpConfig config = new HttpDumpConfig(); + public static HttpDumpConfig getDefault() { + HttpDumpConfig config = new HttpDumpConfig(); - config.setDumpCookie(false); - config.setCookieDumpType(DumpType.EXCEPTION); - config.setCookieSampler(SimpleSamplerFactory.createSampler(false, 1)); - config.setCookieDumpSize(128); + config.setDumpCookie(false); + config.setCookieDumpType(DumpType.EXCEPTION); + config.setCookieSampler(SimpleSamplerFactory.createSampler(false, 1)); + config.setCookieDumpSize(128); - config.setDumpEntity(false); - config.setEntityDumpType(DumpType.EXCEPTION); - config.setEntitySampler(SimpleSamplerFactory.createSampler(false, 1)); - config.setEntityDumpSize(128); + config.setDumpEntity(false); + config.setEntityDumpType(DumpType.EXCEPTION); + config.setEntitySampler(SimpleSamplerFactory.createSampler(false, 1)); + config.setEntityDumpSize(128); - config.setDumpParam(false); - config.setParamDumpType(DumpType.EXCEPTION); - config.setParamSampler(SimpleSamplerFactory.createSampler(false, 1)); - config.setParamDumpSize(128); + config.setDumpParam(false); + config.setParamDumpType(DumpType.EXCEPTION); + config.setParamSampler(SimpleSamplerFactory.createSampler(false, 1)); + config.setParamDumpSize(128); - return config; - } + return config; + } - private boolean dumpCookie = false; - private DumpType cookieDumpType = DumpType.EXCEPTION; - private SimpleSampler cookieSampler; - private int cookieDumpSize; + private boolean dumpCookie = false; + private DumpType cookieDumpType = DumpType.EXCEPTION; + private SimpleSampler cookieSampler; + private int cookieDumpSize; - private boolean dumpEntity; - private DumpType entityDumpType; - private SimpleSampler entitySampler; - private int entityDumpSize; + private boolean dumpEntity; + private DumpType entityDumpType; + private SimpleSampler entitySampler; + private int entityDumpSize; - private boolean dumpParam; - private DumpType paramDumpType; - private SimpleSampler paramSampler; - private int paramDumpSize; + private boolean dumpParam; + private DumpType paramDumpType; + private SimpleSampler paramSampler; + private int paramDumpSize; - public boolean isDumpCookie() { - return dumpCookie; - } + public boolean isDumpCookie() { + return dumpCookie; + } - public void setDumpCookie(boolean dumpCookie) { - this.dumpCookie = dumpCookie; - } + public void setDumpCookie(boolean dumpCookie) { + this.dumpCookie = dumpCookie; + } - public DumpType getCookieDumpType() { - return cookieDumpType; - } + public DumpType getCookieDumpType() { + return cookieDumpType; + } - public void setCookieDumpType(DumpType cookieDumpType) { - this.cookieDumpType = cookieDumpType; - } + public void setCookieDumpType(DumpType cookieDumpType) { + this.cookieDumpType = cookieDumpType; + } - public SimpleSampler getCookieSampler() { - return cookieSampler; - } + public SimpleSampler getCookieSampler() { + return cookieSampler; + } - public void setCookieSampler(SimpleSampler cookieSampler) { - this.cookieSampler = cookieSampler; - } + public void setCookieSampler(SimpleSampler cookieSampler) { + this.cookieSampler = cookieSampler; + } - public int getCookieDumpSize() { - return cookieDumpSize; - } + public int getCookieDumpSize() { + return cookieDumpSize; + } - public void setCookieDumpSize(int cookieDumpSize) { - this.cookieDumpSize = cookieDumpSize; - } + public void setCookieDumpSize(int cookieDumpSize) { + this.cookieDumpSize = cookieDumpSize; + } - public boolean isDumpEntity() { - return dumpEntity; - } + public boolean isDumpEntity() { + return dumpEntity; + } - public void setDumpEntity(boolean dumpEntity) { - this.dumpEntity = dumpEntity; - } + public void setDumpEntity(boolean dumpEntity) { + this.dumpEntity = dumpEntity; + } - public DumpType getEntityDumpType() { - return entityDumpType; - } + public DumpType getEntityDumpType() { + return entityDumpType; + } - public void setEntityDumpType(DumpType entityDumpType) { - this.entityDumpType = entityDumpType; - } + public void setEntityDumpType(DumpType entityDumpType) { + this.entityDumpType = entityDumpType; + } - public SimpleSampler getEntitySampler() { - return entitySampler; - } + public SimpleSampler getEntitySampler() { + return entitySampler; + } - public void setEntitySampler(SimpleSampler entitySampler) { - this.entitySampler = entitySampler; - } + public void setEntitySampler(SimpleSampler entitySampler) { + this.entitySampler = entitySampler; + } - public int getEntityDumpSize() { - return entityDumpSize; - } + public int getEntityDumpSize() { + return entityDumpSize; + } - public void setEntityDumpSize(int entityDumpSize) { - this.entityDumpSize = entityDumpSize; - } + public void setEntityDumpSize(int entityDumpSize) { + this.entityDumpSize = entityDumpSize; + } - public boolean isDumpParam() { - return dumpParam; - } + public boolean isDumpParam() { + return dumpParam; + } - public void setDumpParam(boolean dumpParam) { - this.dumpParam = dumpParam; - } + public void setDumpParam(boolean dumpParam) { + this.dumpParam = dumpParam; + } - public DumpType getParamDumpType() { - return paramDumpType; - } + public DumpType getParamDumpType() { + return paramDumpType; + } - public void setParamDumpType(DumpType paramDumpType) { - this.paramDumpType = paramDumpType; - } + public void setParamDumpType(DumpType paramDumpType) { + this.paramDumpType = paramDumpType; + } - public SimpleSampler getParamSampler() { - return paramSampler; - } + public SimpleSampler getParamSampler() { + return paramSampler; + } - public void setParamSampler(SimpleSampler paramSampler) { - this.paramSampler = paramSampler; - } + public void setParamSampler(SimpleSampler paramSampler) { + this.paramSampler = paramSampler; + } - public int getParamDumpSize() { - return paramDumpSize; - } + public int getParamDumpSize() { + return paramDumpSize; + } - public void setParamDumpSize(int paramDumpSize) { - this.paramDumpSize = paramDumpSize; - } + public void setParamDumpSize(int paramDumpSize) { + this.paramDumpSize = paramDumpSize; + } } diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilableClassFilter.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilableClassFilter.java index 3d12c9dc3..c6dfc1e72 100644 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilableClassFilter.java +++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/ProfilableClassFilter.java @@ -24,52 +24,52 @@ import java.util.Set; */ public class ProfilableClassFilter implements Filter { - private final Set profileInclude = new HashSet(); - private final Set profileIncludeSub = new HashSet(); + private final Set profileInclude = new HashSet(); + private final Set profileIncludeSub = new HashSet(); - public ProfilableClassFilter(String profilableClass) { - if (profilableClass == null || profilableClass.isEmpty()) { - return; - } - String[] className = profilableClass.split(","); - for (String str : className) { - if (str.endsWith(".*")) { - this.profileIncludeSub.add(str.substring(0, str.length() - 2).replace('.', '/') + "/"); - } else { - String replace = str.trim().replace('.', '/'); - this.profileInclude.add(replace); - } - } - } + public ProfilableClassFilter(String profilableClass) { + if (profilableClass == null || profilableClass.isEmpty()) { + return; + } + String[] className = profilableClass.split(","); + for (String str : className) { + if (str.endsWith(".*")) { + this.profileIncludeSub.add(str.substring(0, str.length() - 2).replace('.', '/') + "/"); + } else { + String replace = str.trim().replace('.', '/'); + this.profileInclude.add(replace); + } + } + } - /** - * TODO remove this. Added this method to test the "call stack view" on a test server - * - * @param className - * @return - */ - @Override - public boolean filter(String className) { - if (profileInclude.contains(className)) { - return true; - } else { - final String packageName = className.substring(0, className.lastIndexOf("/") + 1); - for (String pkg : profileIncludeSub) { - if (packageName.startsWith(pkg)) { - return true; - } - } - } - return false; - } + /** + * TODO remove this. Added this method to test the "call stack view" on a test server + * + * @param className + * @return + */ + @Override + public boolean filter(String className) { + if (profileInclude.contains(className)) { + return true; + } else { + final String packageName = className.substring(0, className.lastIndexOf("/") + 1); + for (String pkg : profileIncludeSub) { + if (packageName.startsWith(pkg)) { + return true; + } + } + } + return false; + } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("ProfilableClassFilter{"); - sb.append("profileInclude=").append(profileInclude); - sb.append(", profileIncludeSub=").append(profileIncludeSub); - sb.append('}'); - return sb.toString(); - } + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("ProfilableClassFilter{"); + sb.append("profileInclude=").append(profileInclude); + sb.append(", profileIncludeSub=").append(profileIncludeSub); + sb.append('}'); + return sb.toString(); + } } diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/SkipFilter.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/SkipFilter.java index a8c2b9937..dda7d08ad 100644 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/SkipFilter.java +++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/config/SkipFilter.java @@ -20,8 +20,8 @@ package com.navercorp.pinpoint.bootstrap.config; * @author emeroad */ public class SkipFilter implements Filter { - @Override - public boolean filter(T value) { - return false; - } + @Override + public boolean filter(T value) { + return false; + } } diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/context/Header.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/context/Header.java index 4cfa07a40..774be9e9a 100644 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/context/Header.java +++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/context/Header.java @@ -28,78 +28,78 @@ import java.util.Map; */ public enum Header { - HTTP_TRACE_ID("Pinpoint-TraceID"), - HTTP_SPAN_ID("Pinpoint-SpanID"), - HTTP_PARENT_SPAN_ID("Pinpoint-pSpanID"), - HTTP_SAMPLED("Pinpoint-Sampled"), - HTTP_FLAGS("Pinpoint-Flags"), - HTTP_PARENT_APPLICATION_NAME("Pinpoint-pAppName"), - HTTP_PARENT_APPLICATION_TYPE("Pinpoint-pAppType"); + HTTP_TRACE_ID("Pinpoint-TraceID"), + HTTP_SPAN_ID("Pinpoint-SpanID"), + HTTP_PARENT_SPAN_ID("Pinpoint-pSpanID"), + HTTP_SAMPLED("Pinpoint-Sampled"), + HTTP_FLAGS("Pinpoint-Flags"), + HTTP_PARENT_APPLICATION_NAME("Pinpoint-pAppName"), + HTTP_PARENT_APPLICATION_TYPE("Pinpoint-pAppType"); - private String name; + private String name; - Header(String name) { - this.name = name; - } + Header(String name) { + this.name = name; + } - public String toString() { - return name; - } + public String toString() { + return name; + } - private static final Map NAME_SET = createMap(); + private static final Map NAME_SET = createMap(); - private static Map createMap() { - Header[] headerList = values(); - Map map = new HashMap(); - for (Header header : headerList) { - map.put(header.name, header); - } - return map; - } + private static Map createMap() { + Header[] headerList = values(); + Map map = new HashMap(); + for (Header header : headerList) { + map.put(header.name, header); + } + return map; + } - public static Header getHeader(String name) { - if (name == null) { - return null; - } - if (!startWithPinpointHeader(name)) { - return null; - } - return NAME_SET.get(name); - } + public static Header getHeader(String name) { + if (name == null) { + return null; + } + if (!startWithPinpointHeader(name)) { + return null; + } + return NAME_SET.get(name); + } - public static boolean hasHeader(String name) { - return getHeader(name) != null; - } + public static boolean hasHeader(String name) { + return getHeader(name) != null; + } - public static Enumeration getHeaders(String name) { - if (name == null) { - return null; - } - final Header header = getHeader(name); - if (header == null) { - return null; - } - // if pinpoint header - return new EmptyEnumeration(); - } + public static Enumeration getHeaders(String name) { + if (name == null) { + return null; + } + final Header header = getHeader(name); + if (header == null) { + return null; + } + // if pinpoint header + return new EmptyEnumeration(); + } - public static Enumeration filteredHeaderNames(final Enumeration enumeration) { - return new DelegateEnumeration(enumeration, FILTER); - } + public static Enumeration filteredHeaderNames(final Enumeration enumeration) { + return new DelegateEnumeration(enumeration, FILTER); + } - private static DelegateEnumeration.Filter FILTER = new DelegateEnumeration.Filter() { - @Override - public boolean filter(Object o) { - if (o instanceof String) { - return hasHeader((String )o); - } - return false; - } - }; + private static DelegateEnumeration.Filter FILTER = new DelegateEnumeration.Filter() { + @Override + public boolean filter(Object o) { + if (o instanceof String) { + return hasHeader((String )o); + } + return false; + } + }; - private static boolean startWithPinpointHeader(String name) { - return name.startsWith("Pinpoint-"); - } + private static boolean startWithPinpointHeader(String name) { + return name.startsWith("Pinpoint-"); + } } diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/InstrumentException.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/InstrumentException.java index 125b80add..ea4a1f2ac 100644 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/InstrumentException.java +++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/InstrumentException.java @@ -22,20 +22,20 @@ package com.navercorp.pinpoint.bootstrap.instrument; */ public class InstrumentException extends Exception { - private static final long serialVersionUID = 7594176009977030312L; + private static final long serialVersionUID = 7594176009977030312L; - public InstrumentException() { - } + public InstrumentException() { + } - public InstrumentException(String message) { - super(message); - } + public InstrumentException(String message) { + super(message); + } - public InstrumentException(String message, Throwable cause) { - super(message, cause); - } + public InstrumentException(String message, Throwable cause) { + super(message, cause); + } - public InstrumentException(Throwable cause) { - super(cause); - } + public InstrumentException(Throwable cause) { + super(cause); + } } diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/NotFoundInstrumentException.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/NotFoundInstrumentException.java index 7c1a0cc91..3ebe1c723 100644 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/NotFoundInstrumentException.java +++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/NotFoundInstrumentException.java @@ -22,9 +22,9 @@ package com.navercorp.pinpoint.bootstrap.instrument; */ public class NotFoundInstrumentException extends InstrumentException { - private static final long serialVersionUID = -9079014055408569735L; + private static final long serialVersionUID = -9079014055408569735L; - public NotFoundInstrumentException() { + public NotFoundInstrumentException() { } public NotFoundInstrumentException(String message) { diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/Type.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/Type.java index e17e36f85..97ca21903 100644 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/Type.java +++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/instrument/Type.java @@ -20,5 +20,5 @@ package com.navercorp.pinpoint.bootstrap.instrument; * @author emeroad */ public enum Type { - around(), before(), after() + around(), before(), after() } diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/MethodDescriptor.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/MethodDescriptor.java index d71bf935b..7a67df93c 100644 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/MethodDescriptor.java +++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/interceptor/MethodDescriptor.java @@ -20,23 +20,23 @@ package com.navercorp.pinpoint.bootstrap.interceptor; * @author emeroad */ public interface MethodDescriptor { - String getMethodName(); + String getMethodName(); - String getClassName(); + String getClassName(); - String[] getParameterTypes(); + String[] getParameterTypes(); - String[] getParameterVariableName(); + String[] getParameterVariableName(); - String getParameterDescriptor(); + String getParameterDescriptor(); - int getLineNumber(); + int getLineNumber(); - String getFullName(); + String getFullName(); - void setApiId(int apiId); + void setApiId(int apiId); - int getApiId(); + int getApiId(); - String getApiDescriptor(); + String getApiDescriptor(); } diff --git a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/util/InterceptorUtils.java b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/util/InterceptorUtils.java index 5f4a185b5..0ee1eb5e8 100644 --- a/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/util/InterceptorUtils.java +++ b/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/util/InterceptorUtils.java @@ -34,17 +34,17 @@ public final class InterceptorUtils { public static String exceptionToString(Throwable ex) { - if (ex != null) { - StringBuilder sb = new StringBuilder(128); - sb.append(ex.toString()).append("\n"); + if (ex != null) { + StringBuilder sb = new StringBuilder(128); + sb.append(ex.toString()).append("\n"); - Writer writer = new StringWriter(); - PrintWriter printWriter = new PrintWriter(writer); + Writer writer = new StringWriter(); + PrintWriter printWriter = new PrintWriter(writer); ex.printStackTrace(printWriter); - sb.append(writer.toString()); + sb.append(writer.toString()); - return sb.toString(); - } - return null; - } + return sb.toString(); + } + return null; + } } diff --git a/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/ValidIdCheckerTest.java b/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/ValidIdCheckerTest.java index 9f05ed6e9..fceb47608 100644 --- a/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/ValidIdCheckerTest.java +++ b/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/ValidIdCheckerTest.java @@ -29,26 +29,26 @@ import org.junit.Test; */ public class ValidIdCheckerTest { - private final Pattern p = Pattern.compile("[^a-zA-Z0-9._(\\-)]"); + private final Pattern p = Pattern.compile("[^a-zA-Z0-9._(\\-)]"); - @Test - public void checkValidId() { - Assert.assertFalse(p.matcher("PINPOINT123").find()); - Assert.assertFalse(p.matcher("P1NPOINT").find()); - Assert.assertFalse(p.matcher("1PNPOINT").find()); - Assert.assertFalse(p.matcher("P1NPOINT.DEV").find()); - Assert.assertFalse(p.matcher("P1NPOINT..DEV").find()); - Assert.assertFalse(p.matcher("P1N.POINT.DEV").find()); - Assert.assertFalse(p.matcher("P1NPOINT-DEV").find()); - Assert.assertFalse(p.matcher("P1NPOINT_DEV").find()); - Assert.assertFalse(p.matcher("P1N_POINT_DEV").find()); - } + @Test + public void checkValidId() { + Assert.assertFalse(p.matcher("PINPOINT123").find()); + Assert.assertFalse(p.matcher("P1NPOINT").find()); + Assert.assertFalse(p.matcher("1PNPOINT").find()); + Assert.assertFalse(p.matcher("P1NPOINT.DEV").find()); + Assert.assertFalse(p.matcher("P1NPOINT..DEV").find()); + Assert.assertFalse(p.matcher("P1N.POINT.DEV").find()); + Assert.assertFalse(p.matcher("P1NPOINT-DEV").find()); + Assert.assertFalse(p.matcher("P1NPOINT_DEV").find()); + Assert.assertFalse(p.matcher("P1N_POINT_DEV").find()); + } - @Test - public void checkInvalidId() { - Assert.assertTrue(p.matcher("P1NPOINT가").find()); //include Korean character for test - Assert.assertTrue(p.matcher("P1NPOINT ").find()); - Assert.assertTrue(p.matcher("P1NPOINT+").find()); - Assert.assertTrue(p.matcher("PINPO+INT").find()); - } + @Test + public void checkInvalidId() { + Assert.assertTrue(p.matcher("P1NPOINT가").find()); //include Korean character for test + Assert.assertTrue(p.matcher("P1NPOINT ").find()); + Assert.assertTrue(p.matcher("P1NPOINT+").find()); + Assert.assertTrue(p.matcher("PINPO+INT").find()); + } } diff --git a/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/config/ExcludeUrlFilterTest.java b/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/config/ExcludeUrlFilterTest.java index 4e31868cd..772ee7746 100644 --- a/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/config/ExcludeUrlFilterTest.java +++ b/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/config/ExcludeUrlFilterTest.java @@ -27,40 +27,40 @@ import static org.junit.Assert.*; public class ExcludeUrlFilterTest { - @Test - public void testFilter() throws Exception { - Filter filter = new ExcludeUrlFilter("/monitor/l7check.html, test/l4check.html"); + @Test + public void testFilter() throws Exception { + Filter filter = new ExcludeUrlFilter("/monitor/l7check.html, test/l4check.html"); - assertFilter(filter); - } + assertFilter(filter); + } - @Test - public void testFilter_InvalidExcludeURL() throws Exception { - Filter filter = new ExcludeUrlFilter("/monitor/l7check.html, test/l4check.html, ,,"); + @Test + public void testFilter_InvalidExcludeURL() throws Exception { + Filter filter = new ExcludeUrlFilter("/monitor/l7check.html, test/l4check.html, ,,"); - assertFilter(filter); - } + assertFilter(filter); + } - @Test - public void testFilter_emptyExcludeURL() throws Exception { - Filter filter = new ExcludeUrlFilter(""); + @Test + public void testFilter_emptyExcludeURL() throws Exception { + Filter filter = new ExcludeUrlFilter(""); - Assert.assertFalse(filter.filter("/monitor/l7check.html")); - Assert.assertFalse(filter.filter("test/l4check.html")); + Assert.assertFalse(filter.filter("/monitor/l7check.html")); + Assert.assertFalse(filter.filter("test/l4check.html")); - Assert.assertFalse(filter.filter("test/")); - Assert.assertFalse(filter.filter("test/l4check.htm")); - } + Assert.assertFalse(filter.filter("test/")); + Assert.assertFalse(filter.filter("test/l4check.htm")); + } - private void assertFilter(Filter filter) { - Assert.assertTrue(filter.filter("/monitor/l7check.html")); - Assert.assertTrue(filter.filter("test/l4check.html")); + private void assertFilter(Filter filter) { + Assert.assertTrue(filter.filter("/monitor/l7check.html")); + Assert.assertTrue(filter.filter("test/l4check.html")); - Assert.assertFalse(filter.filter("test/")); - Assert.assertFalse(filter.filter("test/l4check.htm")); - } + Assert.assertFalse(filter.filter("test/")); + Assert.assertFalse(filter.filter("test/l4check.htm")); + } diff --git a/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/config/ProfilableClassFilterTest.java b/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/config/ProfilableClassFilterTest.java index 859c013c0..94bc1ffc2 100644 --- a/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/config/ProfilableClassFilterTest.java +++ b/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/config/ProfilableClassFilterTest.java @@ -26,34 +26,34 @@ import java.io.IOException; public class ProfilableClassFilterTest { - @Test - public void testIsProfilableClassWithNoConfiguration() throws IOException { - ProfilableClassFilter filter = new ProfilableClassFilter("com.navercorp.pinpoint.testweb.controller.*,com.navercorp.pinpoint.testweb.MyClass"); + @Test + public void testIsProfilableClassWithNoConfiguration() throws IOException { + ProfilableClassFilter filter = new ProfilableClassFilter("com.navercorp.pinpoint.testweb.controller.*,com.navercorp.pinpoint.testweb.MyClass"); - Assert.assertFalse(filter.filter("com/navercorp/pinpoint/testweb/controllers/MyController")); - Assert.assertFalse(filter.filter("net/spider/king/wang/Jjang")); - Assert.assertFalse(filter.filter("com/navercorp/pinpoint/testweb2/controller/MyController")); - Assert.assertFalse(filter.filter("com/navercorp/pinpoint/testweb2/MyClass")); - } + Assert.assertFalse(filter.filter("com/navercorp/pinpoint/testweb/controllers/MyController")); + Assert.assertFalse(filter.filter("net/spider/king/wang/Jjang")); + Assert.assertFalse(filter.filter("com/navercorp/pinpoint/testweb2/controller/MyController")); + Assert.assertFalse(filter.filter("com/navercorp/pinpoint/testweb2/MyClass")); + } - /** - *
-	 * configuration is
-	 * profile.package.include=com.navercorp.pinpoint.testweb.controller.*,com.navercorp.pinpoint.testweb.MyClass
-	 * 
- * - * @throws IOException - */ - @Test - public void testIsProfilableClass() throws IOException { - ProfilableClassFilter filter = new ProfilableClassFilter("com.navercorp.pinpoint.testweb.controller.*,com.navercorp.pinpoint.testweb.MyClass"); + /** + *
+     * configuration is
+     * profile.package.include=com.navercorp.pinpoint.testweb.controller.*,com.navercorp.pinpoint.testweb.MyClass
+     * 
+ * + * @throws IOException + */ + @Test + public void testIsProfilableClass() throws IOException { + ProfilableClassFilter filter = new ProfilableClassFilter("com.navercorp.pinpoint.testweb.controller.*,com.navercorp.pinpoint.testweb.MyClass"); - Assert.assertTrue(filter.filter("com/navercorp/pinpoint/testweb/MyClass")); - Assert.assertTrue(filter.filter("com/navercorp/pinpoint/testweb/controller/MyController")); - Assert.assertTrue(filter.filter("com/navercorp/pinpoint/testweb/controller/customcontroller/MyCustomController")); + Assert.assertTrue(filter.filter("com/navercorp/pinpoint/testweb/MyClass")); + Assert.assertTrue(filter.filter("com/navercorp/pinpoint/testweb/controller/MyController")); + Assert.assertTrue(filter.filter("com/navercorp/pinpoint/testweb/controller/customcontroller/MyCustomController")); - Assert.assertFalse(filter.filter("com/navercorp/pinpoint/testweb/MyUnknownClass")); - Assert.assertFalse(filter.filter("com/navercorp/pinpoint/testweb/controller2/MyController")); - } + Assert.assertFalse(filter.filter("com/navercorp/pinpoint/testweb/MyUnknownClass")); + Assert.assertFalse(filter.filter("com/navercorp/pinpoint/testweb/controller2/MyController")); + } } \ No newline at end of file diff --git a/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfigTest.java b/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfigTest.java index dcde84d55..29416a79b 100644 --- a/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfigTest.java +++ b/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/config/ProfilerConfigTest.java @@ -35,12 +35,12 @@ public class ProfilerConfigTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Test - public void defaultProfilableClassFilter() throws IOException { - ProfilerConfig profilerConfig = new ProfilerConfig(); - Filter profilableClassFilter = profilerConfig.getProfilableClassFilter(); - Assert.assertFalse(profilableClassFilter.filter("net/spider/king/wang/Jjang")); - } + @Test + public void defaultProfilableClassFilter() throws IOException { + ProfilerConfig profilerConfig = new ProfilerConfig(); + Filter profilableClassFilter = profilerConfig.getProfilableClassFilter(); + Assert.assertFalse(profilableClassFilter.filter("net/spider/king/wang/Jjang")); + } @Test public void readProperty() throws IOException { diff --git a/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/interceptor/MockTraceContext.java b/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/interceptor/MockTraceContext.java index f13072cbf..735753d53 100644 --- a/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/interceptor/MockTraceContext.java +++ b/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/interceptor/MockTraceContext.java @@ -145,15 +145,15 @@ public class MockTraceContext implements TraceContext { } - @Override - public void recordAcceptResponseTime(String parentApplicationName, short parentApplicationType, int elapsedTime) { - - } + @Override + public void recordAcceptResponseTime(String parentApplicationName, short parentApplicationType, int elapsedTime) { - @Override - public void recordUserAcceptResponseTime(int elapsedTime) { - - } + } + + @Override + public void recordUserAcceptResponseTime(int elapsedTime) { + + } @Override public ServerMetaDataHolder getServerMetaDataHolder() { diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/AbstractClusterService.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/AbstractClusterService.java index 31003e316..808b4111e 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/AbstractClusterService.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/AbstractClusterService.java @@ -23,12 +23,12 @@ import com.navercorp.pinpoint.collector.config.CollectorConfiguration; */ public abstract class AbstractClusterService implements ClusterService { - protected final CollectorConfiguration config; - protected final ClusterPointRouter clusterPointRouter; + protected final CollectorConfiguration config; + protected final ClusterPointRouter clusterPointRouter; - public AbstractClusterService(CollectorConfiguration config, ClusterPointRouter clusterPointRouter) { - this.config = config; - this.clusterPointRouter = clusterPointRouter; - } + public AbstractClusterService(CollectorConfiguration config, ClusterPointRouter clusterPointRouter) { + this.config = config; + this.clusterPointRouter = clusterPointRouter; + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ChannelContextClusterPoint.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ChannelContextClusterPoint.java index f3fabc809..850c7bc97 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ChannelContextClusterPoint.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ChannelContextClusterPoint.java @@ -32,64 +32,64 @@ import com.navercorp.pinpoint.rpc.util.MapUtils; */ public class ChannelContextClusterPoint implements TargetClusterPoint { - private final ChannelContext channelContext; - private final SocketChannel socketChannel; + private final ChannelContext channelContext; + private final SocketChannel socketChannel; - private final String applicationName; - private final String agentId; - private final long startTimeStamp; + private final String applicationName; + private final String agentId; + private final long startTimeStamp; - private final String version; + private final String version; - public ChannelContextClusterPoint(ChannelContext channelContext) { - AssertUtils.assertNotNull(channelContext, "ChannelContext may not be null."); - this.channelContext = channelContext; + public ChannelContextClusterPoint(ChannelContext channelContext) { + AssertUtils.assertNotNull(channelContext, "ChannelContext may not be null."); + this.channelContext = channelContext; - this.socketChannel = channelContext.getSocketChannel(); - AssertUtils.assertNotNull(socketChannel, "SocketChannel may not be null."); + this.socketChannel = channelContext.getSocketChannel(); + AssertUtils.assertNotNull(socketChannel, "SocketChannel may not be null."); - Map properties = channelContext.getChannelProperties(); - this.version = MapUtils.getString(properties, AgentHandshakePropertyType.VERSION.getName()); - AssertUtils.assertTrue(!StringUtils.isBlank(version), "Version may not be null or empty."); + Map properties = channelContext.getChannelProperties(); + this.version = MapUtils.getString(properties, AgentHandshakePropertyType.VERSION.getName()); + AssertUtils.assertTrue(!StringUtils.isBlank(version), "Version may not be null or empty."); - this.applicationName = MapUtils.getString(properties, AgentHandshakePropertyType.APPLICATION_NAME.getName()); - AssertUtils.assertTrue(!StringUtils.isBlank(applicationName), "ApplicationName may not be null or empty."); + this.applicationName = MapUtils.getString(properties, AgentHandshakePropertyType.APPLICATION_NAME.getName()); + AssertUtils.assertTrue(!StringUtils.isBlank(applicationName), "ApplicationName may not be null or empty."); - this.agentId = MapUtils.getString(properties, AgentHandshakePropertyType.AGENT_ID.getName()); - AssertUtils.assertTrue(!StringUtils.isBlank(agentId), "AgentId may not be null or empty."); + this.agentId = MapUtils.getString(properties, AgentHandshakePropertyType.AGENT_ID.getName()); + AssertUtils.assertTrue(!StringUtils.isBlank(agentId), "AgentId may not be null or empty."); - this.startTimeStamp = MapUtils.getLong(properties, AgentHandshakePropertyType.START_TIMESTAMP.getName()); - AssertUtils.assertTrue(startTimeStamp > 0, "StartTimeStamp is must greater than zero."); - } + this.startTimeStamp = MapUtils.getLong(properties, AgentHandshakePropertyType.START_TIMESTAMP.getName()); + AssertUtils.assertTrue(startTimeStamp > 0, "StartTimeStamp is must greater than zero."); + } - @Override - public void send(byte[] data) { - socketChannel.sendMessage(data); - } + @Override + public void send(byte[] data) { + socketChannel.sendMessage(data); + } - @Override - public Future request(byte[] data) { - return socketChannel.sendRequestMessage(data); - } + @Override + public Future request(byte[] data) { + return socketChannel.sendRequestMessage(data); + } - @Override - public String getApplicationName() { - return applicationName; - } + @Override + public String getApplicationName() { + return applicationName; + } - @Override - public String getAgentId() { - return agentId; - } + @Override + public String getAgentId() { + return agentId; + } - public long getStartTimeStamp() { - return startTimeStamp; - } + public long getStartTimeStamp() { + return startTimeStamp; + } - @Override - public String gerVersion() { - return version; - } + @Override + public String gerVersion() { + return version; + } public ChannelContext getChannelContext() { return channelContext; @@ -112,21 +112,21 @@ public class ChannelContextClusterPoint implements TargetClusterPoint { return result; } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } - if (!(obj instanceof ChannelContextClusterPoint)) { - return false; - } + if (!(obj instanceof ChannelContextClusterPoint)) { + return false; + } - if (this.getChannelContext() == ((ChannelContextClusterPoint) obj).getChannelContext()) { - return true; - } + if (this.getChannelContext() == ((ChannelContextClusterPoint) obj).getChannelContext()) { + return true; + } - return false; - } + return false; + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/Cluster.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/Cluster.java index 75e1f59b9..137e79cc4 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/Cluster.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/Cluster.java @@ -20,8 +20,8 @@ import java.net.InetSocketAddress; public interface Cluster { - void connectPointIfAbsent(InetSocketAddress address); + void connectPointIfAbsent(InetSocketAddress address); + + void disconnectPoint(InetSocketAddress address); - void disconnectPoint(InetSocketAddress address); - } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPoint.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPoint.java index 106416d83..1e3a8743b 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPoint.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPoint.java @@ -20,8 +20,8 @@ import com.navercorp.pinpoint.rpc.Future; public interface ClusterPoint { - void send(byte[] data); + void send(byte[] data); - Future request(byte[] data); + Future request(byte[] data); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPointLocator.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPointLocator.java index 24f98c48b..243d5ea56 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPointLocator.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPointLocator.java @@ -20,6 +20,6 @@ import java.util.List; public interface ClusterPointLocator { - List getClusterPointList(); - + List getClusterPointList(); + } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPointRepository.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPointRepository.java index 1f1962d90..1d94bb5ef 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPointRepository.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterPointRepository.java @@ -25,36 +25,36 @@ import org.slf4j.LoggerFactory; public class ClusterPointRepository implements ClusterPointLocator { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final CopyOnWriteArrayList clusterPointRepository = new CopyOnWriteArrayList(); + + public boolean addClusterPoint(T clusterPoint) { + boolean isAdd = clusterPointRepository.addIfAbsent(clusterPoint); + + if (!isAdd) { + logger.warn("Already registered ClusterPoint({}).", clusterPoint); + } + + return isAdd; + } + + public boolean removeClusterPoint(T clusterPoint) { + boolean isRemove = clusterPointRepository.remove(clusterPoint); + + if (!isRemove) { + logger.warn("Already unregistered or not registered ClusterPoint({}).", clusterPoint); + } + + return isRemove; + } + + public List getClusterPointList() { + return new ArrayList(clusterPointRepository); + } + + public void clear() { + + } - private final CopyOnWriteArrayList clusterPointRepository = new CopyOnWriteArrayList(); - - public boolean addClusterPoint(T clusterPoint) { - boolean isAdd = clusterPointRepository.addIfAbsent(clusterPoint); - - if (!isAdd) { - logger.warn("Already registered ClusterPoint({}).", clusterPoint); - } - - return isAdd; - } - - public boolean removeClusterPoint(T clusterPoint) { - boolean isRemove = clusterPointRepository.remove(clusterPoint); - - if (!isRemove) { - logger.warn("Already unregistered or not registered ClusterPoint({}).", clusterPoint); - } - - return isRemove; - } - - public List getClusterPointList() { - return new ArrayList(clusterPointRepository); - } - - public void clear() { - - } - } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterService.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterService.java index 999155714..230b4e697 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterService.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/ClusterService.java @@ -22,9 +22,9 @@ package com.navercorp.pinpoint.collector.cluster; */ public interface ClusterService { - void setUp() throws Exception; - - void tearDown() throws Exception; - - boolean isEnable(); + void setUp() throws Exception; + + void tearDown() throws Exception; + + boolean isEnable(); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/TargetClusterPoint.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/TargetClusterPoint.java index c8fdb8b46..a4f4fe8ea 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/TargetClusterPoint.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/TargetClusterPoint.java @@ -18,12 +18,12 @@ package com.navercorp.pinpoint.collector.cluster; public interface TargetClusterPoint extends ClusterPoint { - String getApplicationName(); + String getApplicationName(); - String getAgentId(); + String getAgentId(); - long getStartTimeStamp(); + long getStartTimeStamp(); + + String gerVersion(); - String gerVersion(); - } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WebCluster.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WebCluster.java index 2548f6177..31a2fd226 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WebCluster.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WebCluster.java @@ -37,14 +37,14 @@ import com.navercorp.pinpoint.rpc.stream.ServerStreamChannelMessageListener; */ public class WebCluster implements Cluster { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final PinpointSocketFactory factory; + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final PinpointSocketFactory factory; - private final Map clusterRepository = new HashMap(); + private final Map clusterRepository = new HashMap(); - public WebCluster(String id, MessageListener messageListener) { - this(id, messageListener, DisabledServerStreamChannelMessageListener.INSTANCE); - } + public WebCluster(String id, MessageListener messageListener) { + this(id, messageListener, DisabledServerStreamChannelMessageListener.INSTANCE); + } public WebCluster(String id, MessageListener messageListener, ServerStreamChannelMessageListener serverStreamChannelMessageListener) { this.factory = new PinpointSocketFactory(); @@ -58,68 +58,68 @@ public class WebCluster implements Cluster { factory.setProperties(properties); } - // Not safe for use by multiple threads. - public void connectPointIfAbsent(InetSocketAddress address) { - logger.info("localhost -> {} connect started.", address); - - if (clusterRepository.containsKey(address)) { - logger.info("localhost -> {} already connected.", address); - return; - } - - PinpointSocket socket = createPinpointSocket(address); - clusterRepository.put(address, socket); - - logger.info("localhost -> {} connect completed.", address); - } + // Not safe for use by multiple threads. + public void connectPointIfAbsent(InetSocketAddress address) { + logger.info("localhost -> {} connect started.", address); - // Not safe for use by multiple threads. - public void disconnectPoint(InetSocketAddress address) { - logger.info("localhost -> {} disconnect started.", address); + if (clusterRepository.containsKey(address)) { + logger.info("localhost -> {} already connected.", address); + return; + } - PinpointSocket socket = clusterRepository.remove(address); - if (socket != null) { - socket.close(); - logger.info("localhost -> {} disconnect completed.", address); - } else { - logger.info("localhost -> {} already disconnected.", address); - } - } + PinpointSocket socket = createPinpointSocket(address); + clusterRepository.put(address, socket); - private PinpointSocket createPinpointSocket(InetSocketAddress address) { - String host = address.getHostName(); - int port = address.getPort(); + logger.info("localhost -> {} connect completed.", address); + } - PinpointSocket socket = null; - for (int i = 0; i < 3; i++) { - try { - socket = factory.connect(host, port); - logger.info("tcp connect success:{}/{}", host, port); - return socket; - } catch (PinpointSocketException e) { - logger.warn("tcp connect fail:{}/{} try reconnect, retryCount:{}", host, port, i); - } - } - logger.warn("change background tcp connect mode {}/{} ", host, port); - socket = factory.scheduledConnect(host, port); + // Not safe for use by multiple threads. + public void disconnectPoint(InetSocketAddress address) { + logger.info("localhost -> {} disconnect started.", address); - return socket; - } + PinpointSocket socket = clusterRepository.remove(address); + if (socket != null) { + socket.close(); + logger.info("localhost -> {} disconnect completed.", address); + } else { + logger.info("localhost -> {} already disconnected.", address); + } + } - public List getWebClusterList() { - return new ArrayList(clusterRepository.keySet()); - } - - public void close() { - for (PinpointSocket socket : clusterRepository.values()) { - if (socket != null) { - socket.close(); - } - } - - if (factory != null) { - factory.release(); - } - } + private PinpointSocket createPinpointSocket(InetSocketAddress address) { + String host = address.getHostName(); + int port = address.getPort(); + + PinpointSocket socket = null; + for (int i = 0; i < 3; i++) { + try { + socket = factory.connect(host, port); + logger.info("tcp connect success:{}/{}", host, port); + return socket; + } catch (PinpointSocketException e) { + logger.warn("tcp connect fail:{}/{} try reconnect, retryCount:{}", host, port, i); + } + } + logger.warn("change background tcp connect mode {}/{} ", host, port); + socket = factory.scheduledConnect(host, port); + + return socket; + } + + public List getWebClusterList() { + return new ArrayList(clusterRepository.keySet()); + } + + public void close() { + for (PinpointSocket socket : clusterRepository.values()) { + if (socket != null) { + socket.close(); + } + } + + if (factory != null) { + factory.release(); + } + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WorkerState.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WorkerState.java index f37713cfc..fb1f83fc6 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WorkerState.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WorkerState.java @@ -18,12 +18,12 @@ package com.navercorp.pinpoint.collector.cluster; public enum WorkerState { - - NEW, - INITIALIZING, - STARTED, - DESTROYING, - STOPPED, - ILLEGAL_STATE - + + NEW, + INITIALIZING, + STARTED, + DESTROYING, + STOPPED, + ILLEGAL_STATE + } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WorkerStateContext.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WorkerStateContext.java index e081820c5..530556649 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WorkerStateContext.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/WorkerStateContext.java @@ -19,43 +19,43 @@ package com.navercorp.pinpoint.collector.cluster; import java.util.concurrent.atomic.AtomicReference; public class WorkerStateContext { - - private final AtomicReference currentState = new AtomicReference(); - public WorkerStateContext() { - currentState.set(WorkerState.NEW); - } - - public WorkerState getCurrentState() { - return currentState.get(); - } - - public boolean changeStateInitializing() { - return currentState.compareAndSet(WorkerState.NEW, WorkerState.INITIALIZING); - } - - public boolean changeStateStarted() { - return currentState.compareAndSet(WorkerState.INITIALIZING, WorkerState.STARTED); - } + private final AtomicReference currentState = new AtomicReference(); - public boolean changeStateDestroying() { - return currentState.compareAndSet(WorkerState.STARTED, WorkerState.DESTROYING); - } + public WorkerStateContext() { + currentState.set(WorkerState.NEW); + } - public boolean changeStateStopped() { - return currentState.compareAndSet(WorkerState.DESTROYING, WorkerState.STOPPED); - } - - public boolean changeStateIllegal() { - currentState.set(WorkerState.ILLEGAL_STATE); - return true; - } + public WorkerState getCurrentState() { + return currentState.get(); + } - public boolean isStarted() { - if (currentState.get() == WorkerState.STARTED) { - return true; - } else { - return false; - } - } + public boolean changeStateInitializing() { + return currentState.compareAndSet(WorkerState.NEW, WorkerState.INITIALIZING); + } + + public boolean changeStateStarted() { + return currentState.compareAndSet(WorkerState.INITIALIZING, WorkerState.STARTED); + } + + public boolean changeStateDestroying() { + return currentState.compareAndSet(WorkerState.STARTED, WorkerState.DESTROYING); + } + + public boolean changeStateStopped() { + return currentState.compareAndSet(WorkerState.DESTROYING, WorkerState.STOPPED); + } + + public boolean changeStateIllegal() { + currentState.set(WorkerState.ILLEGAL_STATE); + return true; + } + + public boolean isStarted() { + if (currentState.get() == WorkerState.STARTED) { + return true; + } else { + return false; + } + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/DefaultRouteFilterChain.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/DefaultRouteFilterChain.java index 281b29924..00987c76c 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/DefaultRouteFilterChain.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/DefaultRouteFilterChain.java @@ -23,26 +23,26 @@ import org.slf4j.LoggerFactory; public class DefaultRouteFilterChain implements RouteFilterChain { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - private final CopyOnWriteArrayList> filterList = new CopyOnWriteArrayList>(); - - @Override - public void addLast(RouteFilter filter) { - filterList.add(filter); - } + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final CopyOnWriteArrayList> filterList = new CopyOnWriteArrayList>(); + + @Override + public void addLast(RouteFilter filter) { + filterList.add(filter); + } + + @Override + public void doEvent(T event) { + for (RouteFilter filter : filterList) { + try { + filter.doEvent(event); + } catch (Exception e) { + if (logger.isWarnEnabled()) { + logger.warn(filter.getClass().getSimpleName() + " filter occured exception. Error:" + e.getMessage() + ".", e); + } + } + } + } - @Override - public void doEvent(T event) { - for (RouteFilter filter : filterList) { - try { - filter.doEvent(event); - } catch (Exception e) { - if (logger.isWarnEnabled()) { - logger.warn(filter.getClass().getSimpleName() + " filter occured exception. Error:" + e.getMessage() + ".", e); - } - } - } - } - } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/DefaultRouteHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/DefaultRouteHandler.java index 321e0cf77..8a287ba9a 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/DefaultRouteHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/DefaultRouteHandler.java @@ -31,64 +31,64 @@ import com.navercorp.pinpoint.thrift.io.TCommandTypeVersion; */ public class DefaultRouteHandler extends AbstractRouteHandler { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final RouteFilterChain requestFilterChain; - private final RouteFilterChain responseFilterChain; + private final RouteFilterChain requestFilterChain; + private final RouteFilterChain responseFilterChain; - public DefaultRouteHandler(ClusterPointLocator targetClusterPointLocator) { - super(targetClusterPointLocator); + public DefaultRouteHandler(ClusterPointLocator targetClusterPointLocator) { + super(targetClusterPointLocator); - this.requestFilterChain = new DefaultRouteFilterChain(); - this.responseFilterChain = new DefaultRouteFilterChain(); - } + this.requestFilterChain = new DefaultRouteFilterChain(); + this.responseFilterChain = new DefaultRouteFilterChain(); + } - @Override - public void addRequestFilter(RouteFilter filter) { - this.requestFilterChain.addLast(filter); - } + @Override + public void addRequestFilter(RouteFilter filter) { + this.requestFilterChain.addLast(filter); + } - @Override - public void addResponseFilter(RouteFilter filter) { - this.responseFilterChain.addLast(filter); - } + @Override + public void addResponseFilter(RouteFilter filter) { + this.responseFilterChain.addLast(filter); + } - @Override - public RouteResult onRoute(RequestEvent event) { - requestFilterChain.doEvent(event); + @Override + public RouteResult onRoute(RequestEvent event) { + requestFilterChain.doEvent(event); - RouteResult routeResult = onRoute0(event); + RouteResult routeResult = onRoute0(event); - responseFilterChain.doEvent(new ResponseEvent(event, event.getRequestId(), routeResult)); + responseFilterChain.doEvent(new ResponseEvent(event, event.getRequestId(), routeResult)); - return routeResult; - } + return routeResult; + } - private RouteResult onRoute0(RequestEvent event) { - TBase requestObject = event.getRequestObject(); - if (requestObject == null) { - return new RouteResult(RouteStatus.BAD_REQUEST); - } + private RouteResult onRoute0(RequestEvent event) { + TBase requestObject = event.getRequestObject(); + if (requestObject == null) { + return new RouteResult(RouteStatus.BAD_REQUEST); + } - TargetClusterPoint clusterPoint = findClusterPoint(event.getDeliveryCommand()); - if (clusterPoint == null) { - return new RouteResult(RouteStatus.NOT_FOUND); - } + TargetClusterPoint clusterPoint = findClusterPoint(event.getDeliveryCommand()); + if (clusterPoint == null) { + return new RouteResult(RouteStatus.NOT_FOUND); + } - TCommandTypeVersion commandVersion = TCommandTypeVersion.getVersion(clusterPoint.gerVersion()); - if (!commandVersion.isSupportCommand(requestObject)) { - return new RouteResult(RouteStatus.NOT_ACCEPTABLE); - } + TCommandTypeVersion commandVersion = TCommandTypeVersion.getVersion(clusterPoint.gerVersion()); + if (!commandVersion.isSupportCommand(requestObject)) { + return new RouteResult(RouteStatus.NOT_ACCEPTABLE); + } - Future future = clusterPoint.request(event.getDeliveryCommand().getPayload()); - future.await(); - ResponseMessage responseMessage = future.getResult(); + Future future = clusterPoint.request(event.getDeliveryCommand().getPayload()); + future.await(); + ResponseMessage responseMessage = future.getResult(); - if (responseMessage == null) { - return new RouteResult(RouteStatus.AGENT_TIMEOUT); - } + if (responseMessage == null) { + return new RouteResult(RouteStatus.AGENT_TIMEOUT); + } - return new RouteResult(RouteStatus.OK, responseMessage); - } + return new RouteResult(RouteStatus.OK, responseMessage); + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/LoggingFilter.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/LoggingFilter.java index 1cb2b88d0..0fb2dc10b 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/LoggingFilter.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/LoggingFilter.java @@ -24,45 +24,45 @@ import org.slf4j.LoggerFactory; */ public class LoggingFilter { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - class RequestFilter implements RouteFilter { + class RequestFilter implements RouteFilter { - @Override - public void doEvent(RequestEvent event) { - logger.warn("{} doEvent {}.", this.getClass().getSimpleName(), event); - } + @Override + public void doEvent(RequestEvent event) { + logger.warn("{} doEvent {}.", this.getClass().getSimpleName(), event); + } - } - - class StreamCreateFilter implements RouteFilter { + } + + class StreamCreateFilter implements RouteFilter { @Override public void doEvent(StreamEvent event) { logger.warn("{} doEvent {}.", this.getClass().getSimpleName(), event); } - - } - class ResponseFilter implements RouteFilter { + } - @Override - public void doEvent(ResponseEvent event) { - logger.warn("{} doEvent {}.", this.getClass().getSimpleName(), event); - } + class ResponseFilter implements RouteFilter { - } + @Override + public void doEvent(ResponseEvent event) { + logger.warn("{} doEvent {}.", this.getClass().getSimpleName(), event); + } - public RequestFilter getRequestFilter() { - return new RequestFilter(); - } - - public StreamCreateFilter getStreamCreateFilter() { - return new StreamCreateFilter(); - } + } - public ResponseFilter getResponseFilter() { - return new ResponseFilter(); - } + public RequestFilter getRequestFilter() { + return new RequestFilter(); + } + + public StreamCreateFilter getStreamCreateFilter() { + return new StreamCreateFilter(); + } + + public ResponseFilter getResponseFilter() { + return new ResponseFilter(); + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/ResponseEvent.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/ResponseEvent.java index a6d56de63..21fff40b8 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/ResponseEvent.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/ResponseEvent.java @@ -27,29 +27,29 @@ public class ResponseEvent extends DefaultRouteEvent { private final int requestId; - private final RouteResult routeResult; + private final RouteResult routeResult; - public ResponseEvent(RouteEvent routeEvent, int requestId, RouteResult routeResult) { - this(routeEvent.getDeliveryCommand(), routeEvent.getSourceChannel(), requestId, routeResult); - } + public ResponseEvent(RouteEvent routeEvent, int requestId, RouteResult routeResult) { + this(routeEvent.getDeliveryCommand(), routeEvent.getSourceChannel(), requestId, routeResult); + } - public ResponseEvent(TCommandTransfer deliveryCommand, Channel sourceChannel, int requestId, RouteResult routeResult) { - super(deliveryCommand, sourceChannel); - - this.requestId = requestId; - this.routeResult = routeResult; - } + public ResponseEvent(TCommandTransfer deliveryCommand, Channel sourceChannel, int requestId, RouteResult routeResult) { + super(deliveryCommand, sourceChannel); + + this.requestId = requestId; + this.routeResult = routeResult; + } public int getRequestId() { return requestId; } public RouteResult getRouteResult() { - return routeResult; - } - - @Override - public String toString() { + return routeResult; + } + + @Override + public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(this.getClass().getSimpleName()); sb.append("{"); @@ -62,6 +62,6 @@ public class ResponseEvent extends DefaultRouteEvent { sb.append('}'); return sb.toString(); - } + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteEvent.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteEvent.java index 5d1a1586e..7b94bb20f 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteEvent.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteEvent.java @@ -25,8 +25,8 @@ import com.navercorp.pinpoint.thrift.dto.command.TCommandTransfer; */ public interface RouteEvent { - TCommandTransfer getDeliveryCommand(); - - Channel getSourceChannel(); - + TCommandTransfer getDeliveryCommand(); + + Channel getSourceChannel(); + } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteFilter.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteFilter.java index 809f9d53a..d35009ff2 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteFilter.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteFilter.java @@ -18,6 +18,6 @@ package com.navercorp.pinpoint.collector.cluster.route; public interface RouteFilter { - void doEvent(T event); - + void doEvent(T event); + } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteFilterChain.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteFilterChain.java index e8713eaff..1a0a664d8 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteFilterChain.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteFilterChain.java @@ -18,8 +18,8 @@ package com.navercorp.pinpoint.collector.cluster.route; public interface RouteFilterChain { - void addLast(RouteFilter filter); - - void doEvent(T event); - + void addLast(RouteFilter filter); + + void doEvent(T event); + } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteHandler.java index 986fdd0a0..e1b41c320 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteHandler.java @@ -22,10 +22,10 @@ package com.navercorp.pinpoint.collector.cluster.route; */ public interface RouteHandler { - void addRequestFilter(RouteFilter filter); - - void addResponseFilter(RouteFilter filter); - - RouteResult onRoute(T event); + void addRequestFilter(RouteFilter filter); + + void addResponseFilter(RouteFilter filter); + + RouteResult onRoute(T event); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteResult.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteResult.java index 388fe4aaf..0dc054640 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteResult.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteResult.java @@ -23,30 +23,30 @@ import com.navercorp.pinpoint.rpc.ResponseMessage; */ public class RouteResult { - private final RouteStatus status; - private final ResponseMessage responseMessage; + private final RouteStatus status; + private final ResponseMessage responseMessage; - public RouteResult(RouteStatus status) { - this(status, null); - } + public RouteResult(RouteStatus status) { + this(status, null); + } - public RouteResult(RouteStatus status, ResponseMessage responseMessage) { - this.status = status; - this.responseMessage = responseMessage; - } + public RouteResult(RouteStatus status, ResponseMessage responseMessage) { + this.status = status; + this.responseMessage = responseMessage; + } - public RouteStatus getStatus() { - return status; - } + public RouteStatus getStatus() { + return status; + } - public ResponseMessage getResponseMessage() { - return responseMessage; - } + public ResponseMessage getResponseMessage() { + return responseMessage; + } + + + @Override + public String toString() { + return status.toString(); + } - - @Override - public String toString() { - return status.toString(); - } - } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteStatus.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteStatus.java index ecc2f8855..d362dae95 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteStatus.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/RouteStatus.java @@ -21,41 +21,41 @@ package com.navercorp.pinpoint.collector.cluster.route; */ public enum RouteStatus { - OK(0, "OK"), + OK(0, "OK"), - BAD_REQUEST(400, "Bad Request"), + BAD_REQUEST(400, "Bad Request"), - NOT_FOUND(404, " Target Route Agent Not Found."), + NOT_FOUND(404, " Target Route Agent Not Found."), - NOT_ACCEPTABLE(406, "Target Route Agent Not Acceptable."), - - NOT_ACCEPTABLE_UNKNOWN(450, "Target Route Agent Not Acceptable."), + NOT_ACCEPTABLE(406, "Target Route Agent Not Acceptable."), + + NOT_ACCEPTABLE_UNKNOWN(450, "Target Route Agent Not Acceptable."), NOT_ACCEPTABLE_COMMAND(451, "Target Route Agent Not Acceptable command."), NOT_ACCEPTABLE_AGENT_TYPE(452, "Target Route Agent Not Acceptable agent type.."), - - AGENT_TIMEOUT(504, "Target Route Agent Timeout"), - - CLOSED(606, "Target Route Agent Closed."); - private final int value; + AGENT_TIMEOUT(504, "Target Route Agent Timeout"), - private final String reasonPhrase; + CLOSED(606, "Target Route Agent Closed."); - private RouteStatus(int value, String reasonPhrase) { - this.value = value; - this.reasonPhrase = reasonPhrase; - } + private final int value; - public int getValue() { - return value; - } + private final String reasonPhrase; - public String getReasonPhrase() { - return reasonPhrase; - } - - @Override - public String toString() { + private RouteStatus(int value, String reasonPhrase) { + this.value = value; + this.reasonPhrase = reasonPhrase; + } + + public int getValue() { + return value; + } + + public String getReasonPhrase() { + return reasonPhrase; + } + + @Override + public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(this.getClass().getSimpleName()); sb.append("{"); @@ -63,6 +63,6 @@ public enum RouteStatus { sb.append("message=").append(getReasonPhrase()); sb.append('}'); return sb.toString(); - } + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClient.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClient.java index 0ad617c10..9918129d9 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClient.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClient.java @@ -43,212 +43,212 @@ import com.navercorp.pinpoint.collector.cluster.zookeeper.exception.UnknownExcep */ public class ZookeeperClient { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - // Zookeeper clients are thread-safe - private final ZooKeeper zookeeper; - private final AtomicBoolean clientState = new AtomicBoolean(true); - - private final ZookeeperEventWatcher watcher; + // Zookeeper clients are thread-safe + private final ZooKeeper zookeeper; + private final AtomicBoolean clientState = new AtomicBoolean(true); - public ZookeeperClient(String hostPort, int sessionTimeout, ZookeeperEventWatcher watcher) throws KeeperException, IOException, InterruptedException { - this.watcher = watcher; - zookeeper = new ZooKeeper(hostPort, sessionTimeout, this.watcher); // server - } - - /** - * do not create the final node in the given path. - * - * @throws PinpointZookeeperException - * @throws InterruptedException - */ - public void createPath(String path) throws PinpointZookeeperException, InterruptedException { - createPath(path, false); - } + private final ZookeeperEventWatcher watcher; - public void createPath(String path, boolean createEndNode) throws PinpointZookeeperException, InterruptedException { - checkState(); + public ZookeeperClient(String hostPort, int sessionTimeout, ZookeeperEventWatcher watcher) throws KeeperException, IOException, InterruptedException { + this.watcher = watcher; + zookeeper = new ZooKeeper(hostPort, sessionTimeout, this.watcher); // server + } - int pos = 1; - do { - pos = path.indexOf('/', pos + 1); + /** + * do not create the final node in the given path. + * + * @throws PinpointZookeeperException + * @throws InterruptedException + */ + public void createPath(String path) throws PinpointZookeeperException, InterruptedException { + createPath(path, false); + } - if (pos == -1) { - pos = path.length(); - } + public void createPath(String path, boolean createEndNode) throws PinpointZookeeperException, InterruptedException { + checkState(); - try { - if (pos == path.length()) { - if (!createEndNode) { - return; - } - } - - String subPath = path.substring(0, pos); - if (zookeeper.exists(subPath, false) != null) { - continue; - } + int pos = 1; + do { + pos = path.indexOf('/', pos + 1); - zookeeper.create(subPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); - } catch (KeeperException exception) { - if (exception.code() != Code.NODEEXISTS) { - handleException(exception); - } - } + if (pos == -1) { + pos = path.length(); + } - } while (pos < path.length()); - } + try { + if (pos == path.length()) { + if (!createEndNode) { + return; + } + } - public String createNode(String znodePath, byte[] data) throws PinpointZookeeperException, InterruptedException { - checkState(); + String subPath = path.substring(0, pos); + if (zookeeper.exists(subPath, false) != null) { + continue; + } - try { - if (zookeeper.exists(znodePath, false) != null) { - return znodePath; - } + zookeeper.create(subPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + } catch (KeeperException exception) { + if (exception.code() != Code.NODEEXISTS) { + handleException(exception); + } + } - String pathName = zookeeper.create(znodePath, data, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); - return pathName; - } catch (KeeperException exception) { - handleException(exception); - } - return znodePath; - } - - public byte[] getData(String path) throws PinpointZookeeperException, InterruptedException { - checkState(); + } while (pos < path.length()); + } - try { - return zookeeper.getData(path, false, null); - } catch (KeeperException exception) { - handleException(exception); - } - - throw new UnknownException("UnknownException."); - } + public String createNode(String znodePath, byte[] data) throws PinpointZookeeperException, InterruptedException { + checkState(); - public void setData(String path, byte[] data) throws PinpointZookeeperException, InterruptedException { - checkState(); + try { + if (zookeeper.exists(znodePath, false) != null) { + return znodePath; + } - try { - if (zookeeper.exists(path, false) == null) { - return; - } + String pathName = zookeeper.create(znodePath, data, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); + return pathName; + } catch (KeeperException exception) { + handleException(exception); + } + return znodePath; + } - zookeeper.setData(path, data, -1); - } catch (KeeperException exception) { - handleException(exception); - } - } - - public void delete(String path) throws PinpointZookeeperException, InterruptedException { - checkState(); + public byte[] getData(String path) throws PinpointZookeeperException, InterruptedException { + checkState(); - try { - zookeeper.delete(path, -1); - } catch (KeeperException exception) { - if (exception.code() != Code.NONODE) { - handleException(exception); - } - } - } + try { + return zookeeper.getData(path, false, null); + } catch (KeeperException exception) { + handleException(exception); + } - public boolean exists(String path) throws PinpointZookeeperException, InterruptedException { - checkState(); + throw new UnknownException("UnknownException."); + } - try { - Stat stat = zookeeper.exists(path, false); - if (stat == null) { - return false; - } - } catch (KeeperException exception) { - if (exception.code() != Code.NODEEXISTS) { - handleException(exception); - } - } - return true; - } + public void setData(String path, byte[] data) throws PinpointZookeeperException, InterruptedException { + checkState(); - private void checkState() throws PinpointZookeeperException { - if (!isConnected()) { - throw new ConnectionException("instance must be connected."); - } - } + try { + if (zookeeper.exists(path, false) == null) { + return; + } - public boolean isConnected() { - if (!watcher.isConnected() || !clientState.get()) { - return false; - } - - return true; - } - - public List getChildrenNode(String path, boolean watch) throws PinpointZookeeperException, InterruptedException { - checkState(); + zookeeper.setData(path, data, -1); + } catch (KeeperException exception) { + handleException(exception); + } + } - try { - List childNodeList = zookeeper.getChildren(path, watch, null); - - logger.info("ChildNode List = {}", childNodeList); - return childNodeList; - } catch (KeeperException exception) { - if (exception.code() != Code.NONODE) { - handleException(exception); - } - } - - return Collections.emptyList(); - } - -// public byte[] getData(String path) throws KeeperException, InterruptedException { -// checkState(); + public void delete(String path) throws PinpointZookeeperException, InterruptedException { + checkState(); + + try { + zookeeper.delete(path, -1); + } catch (KeeperException exception) { + if (exception.code() != Code.NONODE) { + handleException(exception); + } + } + } + + public boolean exists(String path) throws PinpointZookeeperException, InterruptedException { + checkState(); + + try { + Stat stat = zookeeper.exists(path, false); + if (stat == null) { + return false; + } + } catch (KeeperException exception) { + if (exception.code() != Code.NODEEXISTS) { + handleException(exception); + } + } + return true; + } + + private void checkState() throws PinpointZookeeperException { + if (!isConnected()) { + throw new ConnectionException("instance must be connected."); + } + } + + public boolean isConnected() { + if (!watcher.isConnected() || !clientState.get()) { + return false; + } + + return true; + } + + public List getChildrenNode(String path, boolean watch) throws PinpointZookeeperException, InterruptedException { + checkState(); + + try { + List childNodeList = zookeeper.getChildren(path, watch, null); + + logger.info("ChildNode List = {}", childNodeList); + return childNodeList; + } catch (KeeperException exception) { + if (exception.code() != Code.NONODE) { + handleException(exception); + } + } + + return Collections.emptyList(); + } + +// public byte[] getData(String path) throws KeeperException, InterruptedException { +// checkState(); // -// return zookeeper.getData(path, false, null); -// } +// return zookeeper.getData(path, false, null); +// } // -// public List getChildrenNode(String path) throws KeeperException, InterruptedException { -// checkState(); +// public List getChildrenNode(String path) throws KeeperException, InterruptedException { +// checkState(); // -// List childNodeList = zookeeper.getChildren(path, false); -// logger.info("ChildNode List = {}", childNodeList); -// return childNodeList; -// } +// List childNodeList = zookeeper.getChildren(path, false); +// logger.info("ChildNode List = {}", childNodeList); +// return childNodeList; +// } - private void handleException(KeeperException keeperException) throws PinpointZookeeperException { - switch (keeperException.code()) { - case CONNECTIONLOSS: - case SESSIONEXPIRED: - throw new ConnectionException(keeperException.getMessage(), keeperException); - case AUTHFAILED: - case INVALIDACL: - case NOAUTH: - throw new AuthException(keeperException.getMessage(), keeperException); - case BADARGUMENTS: - case BADVERSION: - case NOCHILDRENFOREPHEMERALS: - case NOTEMPTY: - case NODEEXISTS: - throw new BadOperationException(keeperException.getMessage(), keeperException); - case NONODE: - throw new NoNodeException(keeperException.getMessage(), keeperException); - case OPERATIONTIMEOUT: - throw new TimeoutException(keeperException.getMessage(), keeperException); - default: - throw new UnknownException(keeperException.getMessage(), keeperException); - } - } - - public void close() { - if (clientState.compareAndSet(true, false)) { - if (zookeeper != null) { - try { - zookeeper.close(); - } catch (InterruptedException ignore) { - logger.info("Interrupted zookeeper.close(). Caused:" + ignore.getMessage(), ignore); + private void handleException(KeeperException keeperException) throws PinpointZookeeperException { + switch (keeperException.code()) { + case CONNECTIONLOSS: + case SESSIONEXPIRED: + throw new ConnectionException(keeperException.getMessage(), keeperException); + case AUTHFAILED: + case INVALIDACL: + case NOAUTH: + throw new AuthException(keeperException.getMessage(), keeperException); + case BADARGUMENTS: + case BADVERSION: + case NOCHILDRENFOREPHEMERALS: + case NOTEMPTY: + case NODEEXISTS: + throw new BadOperationException(keeperException.getMessage(), keeperException); + case NONODE: + throw new NoNodeException(keeperException.getMessage(), keeperException); + case OPERATIONTIMEOUT: + throw new TimeoutException(keeperException.getMessage(), keeperException); + default: + throw new UnknownException(keeperException.getMessage(), keeperException); + } + } + + public void close() { + if (clientState.compareAndSet(true, false)) { + if (zookeeper != null) { + try { + zookeeper.close(); + } catch (InterruptedException ignore) { + logger.info("Interrupted zookeeper.close(). Caused:" + ignore.getMessage(), ignore); Thread.currentThread().interrupt(); - } - } - } - } + } + } + } + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClusterService.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClusterService.java index 841505547..a74572672 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClusterService.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperClusterService.java @@ -46,187 +46,187 @@ import com.navercorp.pinpoint.rpc.server.SocketChannelStateChangeEventListener; */ public class ZookeeperClusterService extends AbstractClusterService { - private static final String PINPOINT_CLUSTER_PATH = "/pinpoint-cluster"; - private static final String PINPOINT_WEB_CLUSTER_PATH = PINPOINT_CLUSTER_PATH + "/web"; - private static final String PINPOINT_PROFILER_CLUSTER_PATH = PINPOINT_CLUSTER_PATH + "/profiler"; + private static final String PINPOINT_CLUSTER_PATH = "/pinpoint-cluster"; + private static final String PINPOINT_WEB_CLUSTER_PATH = PINPOINT_CLUSTER_PATH + "/web"; + private static final String PINPOINT_PROFILER_CLUSTER_PATH = PINPOINT_CLUSTER_PATH + "/profiler"; - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - // represented as pid@hostname (identifiers may overlap for services hosted on localhost if pids are identical) - // shouldn't be too big of a problem, but will change to MAC or IP if it becomes problematic. - private final String serverIdentifier = CollectorUtils.getServerIdentifier(); + // represented as pid@hostname (identifiers may overlap for services hosted on localhost if pids are identical) + // shouldn't be too big of a problem, but will change to MAC or IP if it becomes problematic. + private final String serverIdentifier = CollectorUtils.getServerIdentifier(); - private final WebCluster webCluster; - - private final WorkerStateContext serviceState; + private final WebCluster webCluster; - private ZookeeperClient client; + private final WorkerStateContext serviceState; - // WebClusterManager checks Zookeeper for the Web data, and manages collector -> web connections. - private ZookeeperWebClusterManager webClusterManager; - - // ProfilerClusterManager detects/manages profiler -> collector connections, and saves their information in Zookeeper. + private ZookeeperClient client; + + // WebClusterManager checks Zookeeper for the Web data, and manages collector -> web connections. + private ZookeeperWebClusterManager webClusterManager; + + // ProfilerClusterManager detects/manages profiler -> collector connections, and saves their information in Zookeeper. private ZookeeperProfilerClusterManager profilerClusterManager; - public ZookeeperClusterService(CollectorConfiguration config, ClusterPointRouter clusterPointRouter) { - super(config, clusterPointRouter); - this.serviceState = new WorkerStateContext(); - this.webCluster = new WebCluster(serverIdentifier, clusterPointRouter, clusterPointRouter); - } + public ZookeeperClusterService(CollectorConfiguration config, ClusterPointRouter clusterPointRouter) { + super(config, clusterPointRouter); + this.serviceState = new WorkerStateContext(); + this.webCluster = new WebCluster(serverIdentifier, clusterPointRouter, clusterPointRouter); + } - @PostConstruct - @Override - public void setUp() throws KeeperException, IOException, InterruptedException { - if (!config.isClusterEnable()) { - logger.info("pinpoint-collector cluster disable."); - return; - } - - switch (this.serviceState.getCurrentState()) { - case NEW: - if (this.serviceState.changeStateInitializing()) { - logger.info("{} initialization started.", this.getClass().getSimpleName()); - - ClusterManagerWatcher watcher = new ClusterManagerWatcher(); - this.client = new ZookeeperClient(config.getClusterAddress(), config.getClusterSessionTimeout(), watcher); - - this.profilerClusterManager = new ZookeeperProfilerClusterManager(client, serverIdentifier, clusterPointRouter.getTargetClusterPointRepository()); - this.profilerClusterManager.start(); - - this.webClusterManager = new ZookeeperWebClusterManager(client, PINPOINT_WEB_CLUSTER_PATH, serverIdentifier, webCluster); - this.webClusterManager.start(); - - this.serviceState.changeStateStarted(); - logger.info("{} initialization completed.", this.getClass().getSimpleName()); - - if (client.isConnected()) { - WatcherEvent watcherEvent = new WatcherEvent(EventType.None.getIntValue(), KeeperState.SyncConnected.getIntValue(), ""); - WatchedEvent event = new WatchedEvent(watcherEvent); - - watcher.process(event); - } - } - break; - case INITIALIZING: - logger.info("{} already initializing.", this.getClass().getSimpleName()); - break; - case STARTED: - logger.info("{} already started.", this.getClass().getSimpleName()); - break; - case DESTROYING: - throw new IllegalStateException("Already destroying."); - case STOPPED: - throw new IllegalStateException("Already stopped."); - case ILLEGAL_STATE: - throw new IllegalStateException("Invalid State."); - } - } + @PostConstruct + @Override + public void setUp() throws KeeperException, IOException, InterruptedException { + if (!config.isClusterEnable()) { + logger.info("pinpoint-collector cluster disable."); + return; + } - @PreDestroy - @Override - public void tearDown() { - if (!config.isClusterEnable()) { - logger.info("pinpoint-collector cluster disable."); - return; - } + switch (this.serviceState.getCurrentState()) { + case NEW: + if (this.serviceState.changeStateInitializing()) { + logger.info("{} initialization started.", this.getClass().getSimpleName()); - if (!(this.serviceState.changeStateDestroying())) { - WorkerState state = this.serviceState.getCurrentState(); - - logger.info("{} already {}.", this.getClass().getSimpleName(), state.toString()); - return; - } + ClusterManagerWatcher watcher = new ClusterManagerWatcher(); + this.client = new ZookeeperClient(config.getClusterAddress(), config.getClusterSessionTimeout(), watcher); - logger.info("{} destroying started.", this.getClass().getSimpleName()); + this.profilerClusterManager = new ZookeeperProfilerClusterManager(client, serverIdentifier, clusterPointRouter.getTargetClusterPointRepository()); + this.profilerClusterManager.start(); - if (this.profilerClusterManager != null) { - profilerClusterManager.stop(); - } + this.webClusterManager = new ZookeeperWebClusterManager(client, PINPOINT_WEB_CLUSTER_PATH, serverIdentifier, webCluster); + this.webClusterManager.start(); - if (this.webClusterManager != null) { - webClusterManager.stop(); - } - - if (client != null) { - client.close(); - } + this.serviceState.changeStateStarted(); + logger.info("{} initialization completed.", this.getClass().getSimpleName()); - if (webCluster != null) { - webCluster.close(); - } - - this.serviceState.changeStateStopped(); - logger.info("{} destroying completed.", this.getClass().getSimpleName()); - } - - @Override - public boolean isEnable() { - return config.isClusterEnable(); - } - - public SocketChannelStateChangeEventListener getChannelStateChangeEventListener() { - return profilerClusterManager; - } - - public ZookeeperProfilerClusterManager getProfilerClusterManager() { - return profilerClusterManager; - } - - public ZookeeperWebClusterManager getWebClusterManager() { - return webClusterManager; - } + if (client.isConnected()) { + WatcherEvent watcherEvent = new WatcherEvent(EventType.None.getIntValue(), KeeperState.SyncConnected.getIntValue(), ""); + WatchedEvent event = new WatchedEvent(watcherEvent); - class ClusterManagerWatcher implements ZookeeperEventWatcher { + watcher.process(event); + } + } + break; + case INITIALIZING: + logger.info("{} already initializing.", this.getClass().getSimpleName()); + break; + case STARTED: + logger.info("{} already started.", this.getClass().getSimpleName()); + break; + case DESTROYING: + throw new IllegalStateException("Already destroying."); + case STOPPED: + throw new IllegalStateException("Already stopped."); + case ILLEGAL_STATE: + throw new IllegalStateException("Invalid State."); + } + } - private final AtomicBoolean connected = new AtomicBoolean(false); + @PreDestroy + @Override + public void tearDown() { + if (!config.isClusterEnable()) { + logger.info("pinpoint-collector cluster disable."); + return; + } - @Override - public void process(WatchedEvent event) { - logger.debug("Process Zookeeper Event({})", event); - - KeeperState state = event.getState(); - EventType eventType = event.getType(); + if (!(this.serviceState.changeStateDestroying())) { + WorkerState state = this.serviceState.getCurrentState(); - // ephemeral node is removed on disconnect event (leave node management exclusively to zookeeper) - if (ZookeeperUtils.isDisconnectedEvent(state, eventType)) { - connected.compareAndSet(true, false); - return; - } + logger.info("{} already {}.", this.getClass().getSimpleName(), state.toString()); + return; + } - // on connect/reconnect event - if (ZookeeperUtils.isConnectedEvent(state, eventType)) { - // could already be connected (failure to compareAndSet doesn't really matter) - boolean changed = connected.compareAndSet(false, true); - } + logger.info("{} destroying started.", this.getClass().getSimpleName()); - if (serviceState.isStarted() && connected.get()) { + if (this.profilerClusterManager != null) { + profilerClusterManager.stop(); + } - // duplicate event possible - but the logic does not change - if (ZookeeperUtils.isConnectedEvent(state, eventType)) { - List currentChannelContextList = profilerClusterManager.getRegisteredChannelContextList(); - for (ChannelContext channelContext : currentChannelContextList) { - profilerClusterManager.eventPerformed(channelContext, channelContext.getCurrentStateCode()); - } + if (this.webClusterManager != null) { + webClusterManager.stop(); + } - webClusterManager.handleAndRegisterWatcher(PINPOINT_WEB_CLUSTER_PATH); - } else if (eventType == EventType.NodeChildrenChanged) { - String path = event.getPath(); + if (client != null) { + client.close(); + } - if (PINPOINT_WEB_CLUSTER_PATH.equals(path)) { - webClusterManager.handleAndRegisterWatcher(path); - } else { - logger.warn("Unknown Path ChildrenChanged {}.", path); - } + if (webCluster != null) { + webCluster.close(); + } - } - } - } + this.serviceState.changeStateStopped(); + logger.info("{} destroying completed.", this.getClass().getSimpleName()); + } - @Override - public boolean isConnected() { - return connected.get(); - } + @Override + public boolean isEnable() { + return config.isClusterEnable(); + } + + public SocketChannelStateChangeEventListener getChannelStateChangeEventListener() { + return profilerClusterManager; + } + + public ZookeeperProfilerClusterManager getProfilerClusterManager() { + return profilerClusterManager; + } + + public ZookeeperWebClusterManager getWebClusterManager() { + return webClusterManager; + } + + class ClusterManagerWatcher implements ZookeeperEventWatcher { + + private final AtomicBoolean connected = new AtomicBoolean(false); + + @Override + public void process(WatchedEvent event) { + logger.debug("Process Zookeeper Event({})", event); + + KeeperState state = event.getState(); + EventType eventType = event.getType(); + + // ephemeral node is removed on disconnect event (leave node management exclusively to zookeeper) + if (ZookeeperUtils.isDisconnectedEvent(state, eventType)) { + connected.compareAndSet(true, false); + return; + } + + // on connect/reconnect event + if (ZookeeperUtils.isConnectedEvent(state, eventType)) { + // could already be connected (failure to compareAndSet doesn't really matter) + boolean changed = connected.compareAndSet(false, true); + } + + if (serviceState.isStarted() && connected.get()) { + + // duplicate event possible - but the logic does not change + if (ZookeeperUtils.isConnectedEvent(state, eventType)) { + List currentChannelContextList = profilerClusterManager.getRegisteredChannelContextList(); + for (ChannelContext channelContext : currentChannelContextList) { + profilerClusterManager.eventPerformed(channelContext, channelContext.getCurrentStateCode()); + } + + webClusterManager.handleAndRegisterWatcher(PINPOINT_WEB_CLUSTER_PATH); + } else if (eventType == EventType.NodeChildrenChanged) { + String path = event.getPath(); + + if (PINPOINT_WEB_CLUSTER_PATH.equals(path)) { + webClusterManager.handleAndRegisterWatcher(path); + } else { + logger.warn("Unknown Path ChildrenChanged {}.", path); + } + + } + } + } + + @Override + public boolean isConnected() { + return connected.get(); + } + + } - } - } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperEventWatcher.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperEventWatcher.java index 0a6cc1cb4..35f222b71 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperEventWatcher.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperEventWatcher.java @@ -23,6 +23,6 @@ import org.apache.zookeeper.Watcher; */ public interface ZookeeperEventWatcher extends Watcher { - boolean isConnected(); + boolean isConnected(); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperLatestJobWorker.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperLatestJobWorker.java index cb506174a..65d3cf3e9 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperLatestJobWorker.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperLatestJobWorker.java @@ -51,397 +51,397 @@ import com.navercorp.pinpoint.rpc.util.MapUtils; */ public class ZookeeperLatestJobWorker implements Runnable { - private static final Charset charset = Charset.forName("UTF-8"); + private static final Charset charset = Charset.forName("UTF-8"); - private static final String PINPOINT_CLUSTER_PATH = "/pinpoint-cluster"; - private static final String PINPOINT_COLLECTOR_CLUSTER_PATH = PINPOINT_CLUSTER_PATH + "/collector"; + private static final String PINPOINT_CLUSTER_PATH = "/pinpoint-cluster"; + private static final String PINPOINT_COLLECTOR_CLUSTER_PATH = PINPOINT_CLUSTER_PATH + "/collector"; - private static final String PATH_SEPRATOR = "/"; - private static final String PROFILER_SEPERATOR = "\r\n"; + private static final String PATH_SEPRATOR = "/"; + private static final String PROFILER_SEPERATOR = "\r\n"; - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final Object lock = new Object(); + private final Object lock = new Object(); - private final WorkerStateContext workerState; - private final Thread workerThread; + private final WorkerStateContext workerState; + private final Thread workerThread; - private final String collectorUniqPath; - - private final ZookeeperClient zookeeperClient; + private final String collectorUniqPath; - private final ConcurrentHashMap latestJobRepository = new ConcurrentHashMap(); + private final ZookeeperClient zookeeperClient; - // Storage for managing ChannelContexts received by Worker - private final CopyOnWriteArrayList channelContextRepository = new CopyOnWriteArrayList(); + private final ConcurrentHashMap latestJobRepository = new ConcurrentHashMap(); - private final BlockingQueue leakJobQueue = new LinkedBlockingQueue(); + // Storage for managing ChannelContexts received by Worker + private final CopyOnWriteArrayList channelContextRepository = new CopyOnWriteArrayList(); - public ZookeeperLatestJobWorker(ZookeeperClient zookeeperClient, String serverIdentifier) { - this.zookeeperClient = zookeeperClient; + private final BlockingQueue leakJobQueue = new LinkedBlockingQueue(); - this.workerState = new WorkerStateContext(); + public ZookeeperLatestJobWorker(ZookeeperClient zookeeperClient, String serverIdentifier) { + this.zookeeperClient = zookeeperClient; - this.collectorUniqPath = bindingPathAndZnode(PINPOINT_COLLECTOR_CLUSTER_PATH, serverIdentifier); - - final ThreadFactory threadFactory = new PinpointThreadFactory(this.getClass().getSimpleName(), true); - this.workerThread = threadFactory.newThread(this); - } + this.workerState = new WorkerStateContext(); - public void start() { - switch (this.workerState.getCurrentState()) { - case NEW: - if (this.workerState.changeStateInitializing()) { - logger.info("{} initialization started.", this.getClass().getSimpleName()); - workerState.changeStateStarted(); + this.collectorUniqPath = bindingPathAndZnode(PINPOINT_COLLECTOR_CLUSTER_PATH, serverIdentifier); - this.workerThread.start(); - logger.info("{} initialization completed.", this.getClass().getSimpleName()); + final ThreadFactory threadFactory = new PinpointThreadFactory(this.getClass().getSimpleName(), true); + this.workerThread = threadFactory.newThread(this); + } - break; - } - case INITIALIZING: - logger.info("{} already initializing.", this.getClass().getSimpleName()); - break; - case STARTED: - logger.info("{} already started.", this.getClass().getSimpleName()); - break; - case DESTROYING: - throw new IllegalStateException("Already destroying."); - case STOPPED: - throw new IllegalStateException("Already stopped."); - case ILLEGAL_STATE: - throw new IllegalStateException("Invalid State."); - } - } + public void start() { + switch (this.workerState.getCurrentState()) { + case NEW: + if (this.workerState.changeStateInitializing()) { + logger.info("{} initialization started.", this.getClass().getSimpleName()); + workerState.changeStateStarted(); - public void stop() { - if (!(this.workerState.changeStateDestroying())) { - WorkerState state = this.workerState.getCurrentState(); + this.workerThread.start(); + logger.info("{} initialization completed.", this.getClass().getSimpleName()); - logger.info("{} already {}.", this.getClass().getSimpleName(), state.toString()); - return; - } + break; + } + case INITIALIZING: + logger.info("{} already initializing.", this.getClass().getSimpleName()); + break; + case STARTED: + logger.info("{} already started.", this.getClass().getSimpleName()); + break; + case DESTROYING: + throw new IllegalStateException("Already destroying."); + case STOPPED: + throw new IllegalStateException("Already stopped."); + case ILLEGAL_STATE: + throw new IllegalStateException("Invalid State."); + } + } - logger.info("{} destorying started.", this.getClass().getSimpleName()); - boolean interrupted = false; - while (this.workerThread.isAlive()) { - this.workerThread.interrupt(); - try { - this.workerThread.join(100L); - } catch (InterruptedException e) { - interrupted = true; - } - } + public void stop() { + if (!(this.workerState.changeStateDestroying())) { + WorkerState state = this.workerState.getCurrentState(); - this.workerState.changeStateStopped(); - logger.info("{} destorying completed.", this.getClass().getSimpleName()); - } + logger.info("{} already {}.", this.getClass().getSimpleName(), state.toString()); + return; + } - @Override - public void run() { + logger.info("{} destorying started.", this.getClass().getSimpleName()); + boolean interrupted = false; + while (this.workerThread.isAlive()) { + this.workerThread.interrupt(); + try { + this.workerThread.join(100L); + } catch (InterruptedException e) { + interrupted = true; + } + } - // Things to consider - // spinlock possible when events are not deleted - // may lead to ChannelContext leak when events are left unresolved - while (workerState.isStarted()) { - boolean eventCreated = await(60000, 200); - if (!workerState.isStarted()) { - break; - } + this.workerState.changeStateStopped(); + logger.info("{} destorying completed.", this.getClass().getSimpleName()); + } - // handle events - // check and handle ChannelContext leak if events are not triggered - if (eventCreated) { - // to avoid ConcurrentModificationException - Iterator keyIterator = getLatestJobRepositoryKeyIterator(); + @Override + public void run() { - while (keyIterator.hasNext()) { - ChannelContext channelContext = keyIterator.next(); - Job job = getJob(channelContext); - if (job == null) { - continue; - } - - logger.info("Worker execute job({}).", job); - - if (job instanceof UpdateJob) { - handleUpdate((UpdateJob) job); - } else if (job instanceof DeleteJob) { - handleDelete((DeleteJob) job); - } - } - } else { - // take care of leaked jobs - jobs may leak due to timing mismatch while deleting jobs - logger.debug("LeakDetector Start."); + // Things to consider + // spinlock possible when events are not deleted + // may lead to ChannelContext leak when events are left unresolved + while (workerState.isStarted()) { + boolean eventCreated = await(60000, 200); + if (!workerState.isStarted()) { + break; + } - while (true) { - Job job = leakJobQueue.poll(); - if (job == null) { - break; - } + // handle events + // check and handle ChannelContext leak if events are not triggered + if (eventCreated) { + // to avoid ConcurrentModificationException + Iterator keyIterator = getLatestJobRepositoryKeyIterator(); - if (job instanceof UpdateJob) { - putRetryJob(new UpdateJob(job.getChannelContext(), 1, ((UpdateJob) job).getContents())); - } - } + while (keyIterator.hasNext()) { + ChannelContext channelContext = keyIterator.next(); + Job job = getJob(channelContext); + if (job == null) { + continue; + } - for (ChannelContext channelContext : channelContextRepository) { - if (PinpointServerSocketStateCode.isFinished(channelContext.getCurrentStateCode())) { - logger.info("LeakDetector Find Leak ChannelContext={}.", channelContext); - putJob(new DeleteJob(channelContext)); - } - } + logger.info("Worker execute job({}).", job); - } - } + if (job instanceof UpdateJob) { + handleUpdate((UpdateJob) job); + } else if (job instanceof DeleteJob) { + handleDelete((DeleteJob) job); + } + } + } else { + // take care of leaked jobs - jobs may leak due to timing mismatch while deleting jobs + logger.debug("LeakDetector Start."); - logger.info("{} stopped", this.getClass().getSimpleName()); - } + while (true) { + Job job = leakJobQueue.poll(); + if (job == null) { + break; + } - public boolean handleUpdate(UpdateJob job) { - ChannelContext channelContext = job.getChannelContext(); + if (job instanceof UpdateJob) { + putRetryJob(new UpdateJob(job.getChannelContext(), 1, ((UpdateJob) job).getContents())); + } + } - PinpointServerSocketStateCode code = channelContext.getCurrentStateCode(); - if (PinpointServerSocketStateCode.isFinished(code)) { - putJob(new DeleteJob(channelContext)); - return false; - } + for (ChannelContext channelContext : channelContextRepository) { + if (PinpointServerSocketStateCode.isFinished(channelContext.getCurrentStateCode())) { + logger.info("LeakDetector Find Leak ChannelContext={}.", channelContext); + putJob(new DeleteJob(channelContext)); + } + } - try { - String addContents = createProfilerContents(channelContext); + } + } - if (zookeeperClient.exists(collectorUniqPath)) { - byte[] contents = zookeeperClient.getData(collectorUniqPath); - - String data = addIfAbsentContents(new String(contents, charset), addContents); - zookeeperClient.setData(collectorUniqPath, data.getBytes(charset)); - } else { - zookeeperClient.createPath(collectorUniqPath); - - // should return error even if NODE exists if the data is important - zookeeperClient.createNode(collectorUniqPath, addContents.getBytes(charset)); - } - return true; - } catch (Exception e) { - logger.warn(e.getMessage(), e); - if (e instanceof TimeoutException) { - putRetryJob(job); - } - } + logger.info("{} stopped", this.getClass().getSimpleName()); + } - return false; - } + public boolean handleUpdate(UpdateJob job) { + ChannelContext channelContext = job.getChannelContext(); - public boolean handleDelete(Job job) { - ChannelContext channelContext = job.getChannelContext(); + PinpointServerSocketStateCode code = channelContext.getCurrentStateCode(); + if (PinpointServerSocketStateCode.isFinished(code)) { + putJob(new DeleteJob(channelContext)); + return false; + } - try { - if (zookeeperClient.exists(collectorUniqPath)) { - byte[] contents = zookeeperClient.getData(collectorUniqPath); - - String removeContents = createProfilerContents(channelContext); - String data = removeIfExistContents(new String(contents, charset), removeContents); - - zookeeperClient.setData(collectorUniqPath, data.getBytes(charset)); - } - channelContextRepository.remove(channelContext); - return true; - } catch (Exception e) { - logger.warn(e.getMessage(), e); - if (e instanceof TimeoutException) { - putRetryJob(job); - } - } + try { + String addContents = createProfilerContents(channelContext); - return false; - } + if (zookeeperClient.exists(collectorUniqPath)) { + byte[] contents = zookeeperClient.getData(collectorUniqPath); - public byte[] getClusterData() { - try { - return zookeeperClient.getData(collectorUniqPath); - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } + String data = addIfAbsentContents(new String(contents, charset), addContents); + zookeeperClient.setData(collectorUniqPath, data.getBytes(charset)); + } else { + zookeeperClient.createPath(collectorUniqPath); - return null; - } + // should return error even if NODE exists if the data is important + zookeeperClient.createNode(collectorUniqPath, addContents.getBytes(charset)); + } + return true; + } catch (Exception e) { + logger.warn(e.getMessage(), e); + if (e instanceof TimeoutException) { + putRetryJob(job); + } + } - public List getRegisteredChannelContextList() { - return new ArrayList(channelContextRepository); - } - - /** - * Waits for events to trigger for a given time. - * - * @param waitTimeMillis total time to wait for events to trigger in milliseconds - * @param waitUnitTimeMillis time to wait for each wait attempt in milliseconds - * @return true if event triggered, false otherwise - */ - private boolean await(long waitTimeMillis, long waitUnitTimeMillis) { - synchronized (lock) { - long waitTime = waitTimeMillis; - long waitUnitTime = waitUnitTimeMillis; - if (waitTimeMillis < 1000) { - waitTime = 1000; - } - if (waitUnitTimeMillis < 100) { - waitUnitTime = 100; - } + return false; + } - long startTimeMillis = System.currentTimeMillis(); + public boolean handleDelete(Job job) { + ChannelContext channelContext = job.getChannelContext(); - while (latestJobRepository.size() == 0 && !isOverWaitTime(waitTime, startTimeMillis) && workerState.isStarted()) { - try { - lock.wait(waitUnitTime); - } catch (InterruptedException ignore) { + try { + if (zookeeperClient.exists(collectorUniqPath)) { + byte[] contents = zookeeperClient.getData(collectorUniqPath); + + String removeContents = createProfilerContents(channelContext); + String data = removeIfExistContents(new String(contents, charset), removeContents); + + zookeeperClient.setData(collectorUniqPath, data.getBytes(charset)); + } + channelContextRepository.remove(channelContext); + return true; + } catch (Exception e) { + logger.warn(e.getMessage(), e); + if (e instanceof TimeoutException) { + putRetryJob(job); + } + } + + return false; + } + + public byte[] getClusterData() { + try { + return zookeeperClient.getData(collectorUniqPath); + } catch (Exception e) { + logger.warn(e.getMessage(), e); + } + + return null; + } + + public List getRegisteredChannelContextList() { + return new ArrayList(channelContextRepository); + } + + /** + * Waits for events to trigger for a given time. + * + * @param waitTimeMillis total time to wait for events to trigger in milliseconds + * @param waitUnitTimeMillis time to wait for each wait attempt in milliseconds + * @return true if event triggered, false otherwise + */ + private boolean await(long waitTimeMillis, long waitUnitTimeMillis) { + synchronized (lock) { + long waitTime = waitTimeMillis; + long waitUnitTime = waitUnitTimeMillis; + if (waitTimeMillis < 1000) { + waitTime = 1000; + } + if (waitUnitTimeMillis < 100) { + waitUnitTime = 100; + } + + long startTimeMillis = System.currentTimeMillis(); + + while (latestJobRepository.size() == 0 && !isOverWaitTime(waitTime, startTimeMillis) && workerState.isStarted()) { + try { + lock.wait(waitUnitTime); + } catch (InterruptedException ignore) { // Thread.currentThread().interrupt(); // TODO check Interrupted state - } - } + } + } - if (isOverWaitTime(waitTime, startTimeMillis)) { - return false; - } + if (isOverWaitTime(waitTime, startTimeMillis)) { + return false; + } - return true; - } - } + return true; + } + } - private boolean isOverWaitTime(long waitTimeMillis, long startTimeMillis) { - return waitTimeMillis < (System.currentTimeMillis() - startTimeMillis); - } + private boolean isOverWaitTime(long waitTimeMillis, long startTimeMillis) { + return waitTimeMillis < (System.currentTimeMillis() - startTimeMillis); + } - private Iterator getLatestJobRepositoryKeyIterator() { - synchronized (lock) { - return latestJobRepository.keySet().iterator(); - } - } + private Iterator getLatestJobRepositoryKeyIterator() { + synchronized (lock) { + return latestJobRepository.keySet().iterator(); + } + } - // must be invoked within a Runnable only - private Job getJob(ChannelContext channelContext) { - synchronized (lock) { - Job job = latestJobRepository.remove(channelContext); - return job; - } - } + // must be invoked within a Runnable only + private Job getJob(ChannelContext channelContext) { + synchronized (lock) { + Job job = latestJobRepository.remove(channelContext); + return job; + } + } - public void putJob(Job job) { - ChannelContext channelContext = job.getChannelContext(); - if (!checkRequiredProperties(channelContext)) { - return; - } - - synchronized (lock) { - channelContextRepository.addIfAbsent(channelContext); - latestJobRepository.put(channelContext, job); - lock.notifyAll(); - } - } - - private void putRetryJob(Job job) { - job.incrementCurrentRetryCount(); + public void putJob(Job job) { + ChannelContext channelContext = job.getChannelContext(); + if (!checkRequiredProperties(channelContext)) { + return; + } - if (job.getMaxRetryCount() < job.getCurrentRetryCount()) { - if (logger.isInfoEnabled()) { - logger.warn("Leak Job Queue Register Job={}.", job); - } - leakJobQueue.add(job); - return; - } - - ChannelContext channelContext = job.getChannelContext(); + synchronized (lock) { + channelContextRepository.addIfAbsent(channelContext); + latestJobRepository.put(channelContext, job); + lock.notifyAll(); + } + } - synchronized (lock) { - latestJobRepository.putIfAbsent(channelContext, job); - lock.notifyAll(); - } - } + private void putRetryJob(Job job) { + job.incrementCurrentRetryCount(); - private String bindingPathAndZnode(String path, String znodeName) { - StringBuilder fullPath = new StringBuilder(); + if (job.getMaxRetryCount() < job.getCurrentRetryCount()) { + if (logger.isInfoEnabled()) { + logger.warn("Leak Job Queue Register Job={}.", job); + } + leakJobQueue.add(job); + return; + } - fullPath.append(path); - if (!path.endsWith(PATH_SEPRATOR)) { - fullPath.append(PATH_SEPRATOR); - } - fullPath.append(znodeName); + ChannelContext channelContext = job.getChannelContext(); - return fullPath.toString(); - } + synchronized (lock) { + latestJobRepository.putIfAbsent(channelContext, job); + lock.notifyAll(); + } + } - private boolean checkRequiredProperties(ChannelContext channelContext) { - Map agentProperties = channelContext.getChannelProperties(); - final String applicationName = MapUtils.getString(agentProperties, AgentHandshakePropertyType.APPLICATION_NAME.getName()); - final String agentId = MapUtils.getString(agentProperties, AgentHandshakePropertyType.AGENT_ID.getName()); - final Long startTimeStampe = MapUtils.getLong(agentProperties, AgentHandshakePropertyType.START_TIMESTAMP.getName()); - - if (StringUtils.isBlank(applicationName) || StringUtils.isBlank(agentId) || startTimeStampe == null || startTimeStampe <= 0) { - logger.warn("ApplicationName({}) and AgnetId({}) and startTimeStampe({}) may not be null.", applicationName, agentId); - return false; - } - - return true; - } - - private String createProfilerContents(ChannelContext channelContext) { - StringBuilder profilerContents = new StringBuilder(); - - Map agentProperties = channelContext.getChannelProperties(); - final String applicationName = MapUtils.getString(agentProperties, AgentHandshakePropertyType.APPLICATION_NAME.getName()); - final String agentId = MapUtils.getString(agentProperties, AgentHandshakePropertyType.AGENT_ID.getName()); - final Long startTimeStampe = MapUtils.getLong(agentProperties, AgentHandshakePropertyType.START_TIMESTAMP.getName()); - - if (StringUtils.isBlank(applicationName) || StringUtils.isBlank(agentId) || startTimeStampe == null || startTimeStampe <= 0) { - logger.warn("ApplicationName({}) and AgnetId({}) and startTimeStampe({}) may not be null.", applicationName, agentId); - return StringUtils.EMPTY; - } - - profilerContents.append(applicationName); - profilerContents.append(":"); - profilerContents.append(agentId); - profilerContents.append(":"); - profilerContents.append(startTimeStampe); - - return profilerContents.toString(); - } + private String bindingPathAndZnode(String path, String znodeName) { + StringBuilder fullPath = new StringBuilder(); - private String addIfAbsentContents(String contents, String addContents) { - String[] allContents = contents.split(PROFILER_SEPERATOR); - - for (String eachContent : allContents) { - if (StringUtils.equals(eachContent.trim(), addContents.trim())) { - return contents; - } - } - - return contents + PROFILER_SEPERATOR + addContents; - } - - private String removeIfExistContents(String contents, String removeContents) { - StringBuilder newContents = new StringBuilder(contents.length()); - - String[] allContents = contents.split(PROFILER_SEPERATOR); + fullPath.append(path); + if (!path.endsWith(PATH_SEPRATOR)) { + fullPath.append(PATH_SEPRATOR); + } + fullPath.append(znodeName); - Iterator stringIterator = Arrays.asList(allContents).iterator(); - - while (stringIterator.hasNext()) { - String eachContent = stringIterator.next(); - - if (StringUtils.isBlank(eachContent)) { - continue; - } - - if (!StringUtils.equals(eachContent.trim(), removeContents.trim())) { - newContents.append(eachContent); + return fullPath.toString(); + } - if (stringIterator.hasNext()) { - newContents.append(PROFILER_SEPERATOR); - } - } - } + private boolean checkRequiredProperties(ChannelContext channelContext) { + Map agentProperties = channelContext.getChannelProperties(); + final String applicationName = MapUtils.getString(agentProperties, AgentHandshakePropertyType.APPLICATION_NAME.getName()); + final String agentId = MapUtils.getString(agentProperties, AgentHandshakePropertyType.AGENT_ID.getName()); + final Long startTimeStampe = MapUtils.getLong(agentProperties, AgentHandshakePropertyType.START_TIMESTAMP.getName()); + + if (StringUtils.isBlank(applicationName) || StringUtils.isBlank(agentId) || startTimeStampe == null || startTimeStampe <= 0) { + logger.warn("ApplicationName({}) and AgnetId({}) and startTimeStampe({}) may not be null.", applicationName, agentId); + return false; + } + + return true; + } + + private String createProfilerContents(ChannelContext channelContext) { + StringBuilder profilerContents = new StringBuilder(); + + Map agentProperties = channelContext.getChannelProperties(); + final String applicationName = MapUtils.getString(agentProperties, AgentHandshakePropertyType.APPLICATION_NAME.getName()); + final String agentId = MapUtils.getString(agentProperties, AgentHandshakePropertyType.AGENT_ID.getName()); + final Long startTimeStampe = MapUtils.getLong(agentProperties, AgentHandshakePropertyType.START_TIMESTAMP.getName()); + + if (StringUtils.isBlank(applicationName) || StringUtils.isBlank(agentId) || startTimeStampe == null || startTimeStampe <= 0) { + logger.warn("ApplicationName({}) and AgnetId({}) and startTimeStampe({}) may not be null.", applicationName, agentId); + return StringUtils.EMPTY; + } + + profilerContents.append(applicationName); + profilerContents.append(":"); + profilerContents.append(agentId); + profilerContents.append(":"); + profilerContents.append(startTimeStampe); + + return profilerContents.toString(); + } + + private String addIfAbsentContents(String contents, String addContents) { + String[] allContents = contents.split(PROFILER_SEPERATOR); + + for (String eachContent : allContents) { + if (StringUtils.equals(eachContent.trim(), addContents.trim())) { + return contents; + } + } + + return contents + PROFILER_SEPERATOR + addContents; + } + + private String removeIfExistContents(String contents, String removeContents) { + StringBuilder newContents = new StringBuilder(contents.length()); + + String[] allContents = contents.split(PROFILER_SEPERATOR); + + Iterator stringIterator = Arrays.asList(allContents).iterator(); + + while (stringIterator.hasNext()) { + String eachContent = stringIterator.next(); + + if (StringUtils.isBlank(eachContent)) { + continue; + } + + if (!StringUtils.equals(eachContent.trim(), removeContents.trim())) { + newContents.append(eachContent); + + if (stringIterator.hasNext()) { + newContents.append(PROFILER_SEPERATOR); + } + } + } + + return newContents.toString(); + } - return newContents.toString(); - } - } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterManager.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterManager.java index 55666de8e..c7b27a877 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterManager.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperProfilerClusterManager.java @@ -43,137 +43,137 @@ import com.navercorp.pinpoint.rpc.util.MapUtils; */ public class ZookeeperProfilerClusterManager implements SocketChannelStateChangeEventListener { - private static final Charset charset = Charset.forName("UTF-8"); + private static final Charset charset = Charset.forName("UTF-8"); - private static final String PROFILER_SEPERATOR = "\r\n"; + private static final String PROFILER_SEPERATOR = "\r\n"; - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final ZookeeperLatestJobWorker worker; + private final ZookeeperLatestJobWorker worker; - private final WorkerStateContext workerState; + private final WorkerStateContext workerState; - private final ClusterPointRepository profileCluster; + private final ClusterPointRepository profileCluster; - // keep it simple - register on RUN, remove on FINISHED, skip otherwise - // should only be instantiated when cluster is enabled. - public ZookeeperProfilerClusterManager(ZookeeperClient client, String serverIdentifier, ClusterPointRepository profileCluster) { - this.workerState = new WorkerStateContext(); - this.profileCluster = profileCluster; - - this.worker = new ZookeeperLatestJobWorker(client, serverIdentifier); - } + // keep it simple - register on RUN, remove on FINISHED, skip otherwise + // should only be instantiated when cluster is enabled. + public ZookeeperProfilerClusterManager(ZookeeperClient client, String serverIdentifier, ClusterPointRepository profileCluster) { + this.workerState = new WorkerStateContext(); + this.profileCluster = profileCluster; - public void start() { - switch (this.workerState.getCurrentState()) { - case NEW: - if (this.workerState.changeStateInitializing()) { - logger.info("{} initialization started.", this.getClass().getSimpleName()); - - if (worker != null) { - worker.start(); - } - - workerState.changeStateStarted(); - logger.info("{} initialization completed.", this.getClass().getSimpleName()); - - break; - } - case INITIALIZING: - logger.info("{} already initializing.", this.getClass().getSimpleName()); - break; - case STARTED: - logger.info("{} already started.", this.getClass().getSimpleName()); - break; - case DESTROYING: - throw new IllegalStateException("Already destroying."); - case STOPPED: - throw new IllegalStateException("Already stopped."); - case ILLEGAL_STATE: - throw new IllegalStateException("Invalid State."); - } - } - - public void stop() { - if (!(this.workerState.changeStateDestroying())) { - WorkerState state = this.workerState.getCurrentState(); - - logger.info("{} already {}.", this.getClass().getSimpleName(), state.toString()); - return; - } + this.worker = new ZookeeperLatestJobWorker(client, serverIdentifier); + } - logger.info("{} destorying started.", this.getClass().getSimpleName()); + public void start() { + switch (this.workerState.getCurrentState()) { + case NEW: + if (this.workerState.changeStateInitializing()) { + logger.info("{} initialization started.", this.getClass().getSimpleName()); - if (worker != null) { - worker.stop(); - } + if (worker != null) { + worker.start(); + } - this.workerState.changeStateStopped(); - logger.info("{} destorying completed.", this.getClass().getSimpleName()); - } - - @Override - public void eventPerformed(ChannelContext channelContext, PinpointServerSocketStateCode stateCode) { - if (workerState.isStarted()) { - logger.info("eventPerformed ChannelContext={}, State={}", channelContext, stateCode); + workerState.changeStateStarted(); + logger.info("{} initialization completed.", this.getClass().getSimpleName()); - Map agentProperties = channelContext.getChannelProperties(); - - // skip when applicationName and agentId is unknown - if (skipAgent(agentProperties)) { - return; - } - - if (PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION == stateCode) { - UpdateJob job = new UpdateJob(channelContext, new byte[0]); - worker.putJob(job); - - profileCluster.addClusterPoint(new ChannelContextClusterPoint(channelContext)); - } else if (PinpointServerSocketStateCode.isFinished(stateCode)) { - DeleteJob job = new DeleteJob(channelContext); - worker.putJob(job); + break; + } + case INITIALIZING: + logger.info("{} already initializing.", this.getClass().getSimpleName()); + break; + case STARTED: + logger.info("{} already started.", this.getClass().getSimpleName()); + break; + case DESTROYING: + throw new IllegalStateException("Already destroying."); + case STOPPED: + throw new IllegalStateException("Already stopped."); + case ILLEGAL_STATE: + throw new IllegalStateException("Invalid State."); + } + } - profileCluster.removeClusterPoint(new ChannelContextClusterPoint(channelContext)); - } - } else { - WorkerState state = this.workerState.getCurrentState(); - logger.info("{} invalid state {}.", this.getClass().getSimpleName(), state.toString()); - return; - } - } - - public List getClusterData() { - byte[] contents = worker.getClusterData(); - if (contents == null) { - return Collections.emptyList(); - } + public void stop() { + if (!(this.workerState.changeStateDestroying())) { + WorkerState state = this.workerState.getCurrentState(); - List result = new ArrayList(); + logger.info("{} already {}.", this.getClass().getSimpleName(), state.toString()); + return; + } - String clusterData = new String(contents, charset); - String[] allClusterData = clusterData.split(PROFILER_SEPERATOR); - for (String eachClusterData : allClusterData) { - if (!StringUtils.isBlank(eachClusterData)) { - result.add(eachClusterData); - } - } - - return result; - } - - public List getRegisteredChannelContextList() { - return worker.getRegisteredChannelContextList(); - } + logger.info("{} destorying started.", this.getClass().getSimpleName()); - private boolean skipAgent(Map agentProperties) { - String applicationName = MapUtils.getString(agentProperties, AgentHandshakePropertyType.APPLICATION_NAME.getName()); - String agentId = MapUtils.getString(agentProperties, AgentHandshakePropertyType.AGENT_ID.getName()); + if (worker != null) { + worker.stop(); + } - if (StringUtils.isBlank(applicationName) || StringUtils.isBlank(agentId)) { - return true; - } + this.workerState.changeStateStopped(); + logger.info("{} destorying completed.", this.getClass().getSimpleName()); + } - return false; - } + @Override + public void eventPerformed(ChannelContext channelContext, PinpointServerSocketStateCode stateCode) { + if (workerState.isStarted()) { + logger.info("eventPerformed ChannelContext={}, State={}", channelContext, stateCode); + + Map agentProperties = channelContext.getChannelProperties(); + + // skip when applicationName and agentId is unknown + if (skipAgent(agentProperties)) { + return; + } + + if (PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION == stateCode) { + UpdateJob job = new UpdateJob(channelContext, new byte[0]); + worker.putJob(job); + + profileCluster.addClusterPoint(new ChannelContextClusterPoint(channelContext)); + } else if (PinpointServerSocketStateCode.isFinished(stateCode)) { + DeleteJob job = new DeleteJob(channelContext); + worker.putJob(job); + + profileCluster.removeClusterPoint(new ChannelContextClusterPoint(channelContext)); + } + } else { + WorkerState state = this.workerState.getCurrentState(); + logger.info("{} invalid state {}.", this.getClass().getSimpleName(), state.toString()); + return; + } + } + + public List getClusterData() { + byte[] contents = worker.getClusterData(); + if (contents == null) { + return Collections.emptyList(); + } + + List result = new ArrayList(); + + String clusterData = new String(contents, charset); + String[] allClusterData = clusterData.split(PROFILER_SEPERATOR); + for (String eachClusterData : allClusterData) { + if (!StringUtils.isBlank(eachClusterData)) { + result.add(eachClusterData); + } + } + + return result; + } + + public List getRegisteredChannelContextList() { + return worker.getRegisteredChannelContextList(); + } + + private boolean skipAgent(Map agentProperties) { + String applicationName = MapUtils.getString(agentProperties, AgentHandshakePropertyType.APPLICATION_NAME.getName()); + String agentId = MapUtils.getString(agentProperties, AgentHandshakePropertyType.AGENT_ID.getName()); + + if (StringUtils.isBlank(applicationName) || StringUtils.isBlank(agentId)) { + return true; + } + + return false; + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperUtils.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperUtils.java index cb0a177c7..5ee80d9de 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperUtils.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperUtils.java @@ -26,38 +26,38 @@ import org.apache.zookeeper.Watcher.Event.KeeperState; public final class ZookeeperUtils { // would be a good idea to move to commons-hbase (if implemented) in the future - private ZookeeperUtils() { - } + private ZookeeperUtils() { + } - public static boolean isConnectedEvent(WatchedEvent event) { - KeeperState state = event.getState(); - EventType eventType = event.getType(); + public static boolean isConnectedEvent(WatchedEvent event) { + KeeperState state = event.getState(); + EventType eventType = event.getType(); - return isConnectedEvent(state, eventType); - } + return isConnectedEvent(state, eventType); + } - public static boolean isConnectedEvent(KeeperState state, EventType eventType) { - if ((state == KeeperState.SyncConnected || state == KeeperState.NoSyncConnected) && eventType == EventType.None) { - return true; - } else { - return false; - } - } + public static boolean isConnectedEvent(KeeperState state, EventType eventType) { + if ((state == KeeperState.SyncConnected || state == KeeperState.NoSyncConnected) && eventType == EventType.None) { + return true; + } else { + return false; + } + } - - public static boolean isDisconnectedEvent(WatchedEvent event) { - KeeperState state = event.getState(); - EventType eventType = event.getType(); - return isDisconnectedEvent(state, eventType); - } + public static boolean isDisconnectedEvent(WatchedEvent event) { + KeeperState state = event.getState(); + EventType eventType = event.getType(); + + return isDisconnectedEvent(state, eventType); + } + + public static boolean isDisconnectedEvent(KeeperState state, EventType eventType) { + if ((state == KeeperState.Disconnected || state == KeeperState.Expired) && eventType == eventType.None) { + return true; + } else { + return false; + } + } - public static boolean isDisconnectedEvent(KeeperState state, EventType eventType) { - if ((state == KeeperState.Disconnected || state == KeeperState.Expired) && eventType == eventType.None) { - return true; - } else { - return false; - } - } - } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterManager.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterManager.java index 9061af7c0..d8fd2d3ae 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterManager.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/ZookeeperWebClusterManager.java @@ -40,76 +40,76 @@ import com.navercorp.pinpoint.common.util.PinpointThreadFactory; public class ZookeeperWebClusterManager implements Runnable { // it is okay for the collector to retry indefinitely, as long as RETRY_INTERVAL is set reasonably - private static final int DEFAULT_RETRY_INTERVAL = 60000; + private static final int DEFAULT_RETRY_INTERVAL = 60000; - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final GetAndRegisterTask getAndRegisterTask = new GetAndRegisterTask(); - private final StopTask stopTask = new StopTask(); + private final GetAndRegisterTask getAndRegisterTask = new GetAndRegisterTask(); + private final StopTask stopTask = new StopTask(); - private final ZookeeperClient client; - private final WebCluster webCluster; - private final String zNodePath; + private final ZookeeperClient client; + private final WebCluster webCluster; + private final String zNodePath; - private final AtomicBoolean retryMode = new AtomicBoolean(false); + private final AtomicBoolean retryMode = new AtomicBoolean(false); - private final BlockingQueue queue = new LinkedBlockingQueue(1); + private final BlockingQueue queue = new LinkedBlockingQueue(1); - private final WorkerStateContext workerState; - private final Thread workerThread; + private final WorkerStateContext workerState; + private final Thread workerThread; - // private final Timer timer; + // private final Timer timer; - // Register Worker + Job - // synchronize current status with Zookeeper when an event(job) is triggered. - // (the number of events does not matter as long as a single event is triggered - subsequent events may be ignored) - public ZookeeperWebClusterManager(ZookeeperClient client, String zookeeperClusterPath, String serverIdentifier, WebCluster webCluster) { - this.client = client; + // Register Worker + Job + // synchronize current status with Zookeeper when an event(job) is triggered. + // (the number of events does not matter as long as a single event is triggered - subsequent events may be ignored) + public ZookeeperWebClusterManager(ZookeeperClient client, String zookeeperClusterPath, String serverIdentifier, WebCluster webCluster) { + this.client = client; - this.webCluster = webCluster; - this.zNodePath = zookeeperClusterPath; + this.webCluster = webCluster; + this.zNodePath = zookeeperClusterPath; - this.workerState = new WorkerStateContext(); + this.workerState = new WorkerStateContext(); - final ThreadFactory threadFactory = new PinpointThreadFactory(this.getClass().getSimpleName(), true); - this.workerThread = threadFactory.newThread(this); - } + final ThreadFactory threadFactory = new PinpointThreadFactory(this.getClass().getSimpleName(), true); + this.workerThread = threadFactory.newThread(this); + } - public void start() { - switch (this.workerState.getCurrentState()) { - case NEW: - if (this.workerState.changeStateInitializing()) { - logger.info("{} initialization started.", this.getClass().getSimpleName()); - this.workerThread.start(); - - workerState.changeStateStarted(); - logger.info("{} initialization completed.", this.getClass().getSimpleName()); - break; - } - case INITIALIZING: - logger.info("{} already initializing.", this.getClass().getSimpleName()); - break; - case STARTED: - logger.info("{} already started.", this.getClass().getSimpleName()); - break; - case DESTROYING: - throw new IllegalStateException("Already destroying."); - case STOPPED: - throw new IllegalStateException("Already stopped."); - case ILLEGAL_STATE: - throw new IllegalStateException("Invalid State."); - } - } + public void start() { + switch (this.workerState.getCurrentState()) { + case NEW: + if (this.workerState.changeStateInitializing()) { + logger.info("{} initialization started.", this.getClass().getSimpleName()); + this.workerThread.start(); - public void stop() { - if (!(this.workerState.changeStateDestroying())) { - WorkerState state = this.workerState.getCurrentState(); - - logger.info("{} already {}.", this.getClass().getSimpleName(), state.toString()); - return; - } + workerState.changeStateStarted(); + logger.info("{} initialization completed.", this.getClass().getSimpleName()); + break; + } + case INITIALIZING: + logger.info("{} already initializing.", this.getClass().getSimpleName()); + break; + case STARTED: + logger.info("{} already started.", this.getClass().getSimpleName()); + break; + case DESTROYING: + throw new IllegalStateException("Already destroying."); + case STOPPED: + throw new IllegalStateException("Already stopped."); + case ILLEGAL_STATE: + throw new IllegalStateException("Invalid State."); + } + } - logger.info("{} destorying started.", this.getClass().getSimpleName()); + public void stop() { + if (!(this.workerState.changeStateDestroying())) { + WorkerState state = this.workerState.getCurrentState(); + + logger.info("{} already {}.", this.getClass().getSimpleName(), state.toString()); + return; + } + + logger.info("{} destorying started.", this.getClass().getSimpleName()); final boolean stopOffer = queue.offer(stopTask); if (!stopOffer) { @@ -117,119 +117,119 @@ public class ZookeeperWebClusterManager implements Runnable { } boolean interrupted = false; - while (this.workerThread.isAlive()) { - this.workerThread.interrupt(); - try { - this.workerThread.join(100L); - } catch (InterruptedException e) { - interrupted = true; - } - } + while (this.workerThread.isAlive()) { + this.workerThread.interrupt(); + try { + this.workerThread.join(100L); + } catch (InterruptedException e) { + interrupted = true; + } + } - this.workerState.changeStateStopped(); - logger.info("{} destorying completed.", this.getClass().getSimpleName()); - } + this.workerState.changeStateStopped(); + logger.info("{} destorying completed.", this.getClass().getSimpleName()); + } - public void handleAndRegisterWatcher(String path) { - if (workerState.isStarted()) { - if (zNodePath.equals(path)) { - final boolean offerSuccess = queue.offer(getAndRegisterTask); - if (!offerSuccess) { - logger.info("Message Queue is Full."); - } - } else { - logger.info("Invald Path {}.", path); - } - } else { - WorkerState state = this.workerState.getCurrentState(); - logger.info("{} invalid state {}.", this.getClass().getSimpleName(), state.toString()); - } - } + public void handleAndRegisterWatcher(String path) { + if (workerState.isStarted()) { + if (zNodePath.equals(path)) { + final boolean offerSuccess = queue.offer(getAndRegisterTask); + if (!offerSuccess) { + logger.info("Message Queue is Full."); + } + } else { + logger.info("Invald Path {}.", path); + } + } else { + WorkerState state = this.workerState.getCurrentState(); + logger.info("{} invalid state {}.", this.getClass().getSimpleName(), state.toString()); + } + } - @Override - public void run() { - // if the node does not exist, create a node and retry. - // retry on timeout as well. - while (workerState.isStarted()) { - Task task = null; + @Override + public void run() { + // if the node does not exist, create a node and retry. + // retry on timeout as well. + while (workerState.isStarted()) { + Task task = null; - try { - task = queue.poll(DEFAULT_RETRY_INTERVAL, TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - logger.debug(e.getMessage(), e); - } + try { + task = queue.poll(DEFAULT_RETRY_INTERVAL, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + logger.debug(e.getMessage(), e); + } - if (!workerState.isStarted()) { - break; - } + if (!workerState.isStarted()) { + break; + } - if (task == null) { - if (retryMode.get()) { - boolean success = getAndRegisterTask.handleAndRegisterWatcher0(); - if (success) { - retryMode.compareAndSet(true, false); - } - } - } else if (task instanceof GetAndRegisterTask) { - boolean success = ((GetAndRegisterTask) task).handleAndRegisterWatcher0(); - if (!success) { - retryMode.compareAndSet(false, true); - } - } else if (task instanceof StopTask) { - break; - } - } + if (task == null) { + if (retryMode.get()) { + boolean success = getAndRegisterTask.handleAndRegisterWatcher0(); + if (success) { + retryMode.compareAndSet(true, false); + } + } + } else if (task instanceof GetAndRegisterTask) { + boolean success = ((GetAndRegisterTask) task).handleAndRegisterWatcher0(); + if (!success) { + retryMode.compareAndSet(false, true); + } + } else if (task instanceof StopTask) { + break; + } + } - logger.info("{} stopped", this.getClass().getSimpleName()); - } + logger.info("{} stopped", this.getClass().getSimpleName()); + } - interface Task { + interface Task { - } + } - class GetAndRegisterTask implements Task { + class GetAndRegisterTask implements Task { - private boolean handleAndRegisterWatcher0() { - boolean needNotRetry = false; - try { + private boolean handleAndRegisterWatcher0() { + boolean needNotRetry = false; + try { - if (!client.exists(zNodePath)) { - client.createPath(zNodePath, true); - } + if (!client.exists(zNodePath)) { + client.createPath(zNodePath, true); + } - List childNodeList = client.getChildrenNode(zNodePath, true); - List clusterAddressList = NetUtils.toInetSocketAddressLIst(childNodeList); + List childNodeList = client.getChildrenNode(zNodePath, true); + List clusterAddressList = NetUtils.toInetSocketAddressLIst(childNodeList); - List addressList = webCluster.getWebClusterList(); + List addressList = webCluster.getWebClusterList(); - logger.info("Handle register and remove Task. Current Address List = {}, Cluster Address List = {}", addressList, clusterAddressList); - - for (InetSocketAddress clusterAddress : clusterAddressList) { - if (!addressList.contains(clusterAddress)) { - webCluster.connectPointIfAbsent(clusterAddress); - } - } + logger.info("Handle register and remove Task. Current Address List = {}, Cluster Address List = {}", addressList, clusterAddressList); - for (InetSocketAddress address : addressList) { - if (!clusterAddressList.contains(address)) { - webCluster.disconnectPoint(address); - } - } + for (InetSocketAddress clusterAddress : clusterAddressList) { + if (!addressList.contains(clusterAddress)) { + webCluster.connectPointIfAbsent(clusterAddress); + } + } - needNotRetry = true; - return needNotRetry; - } catch (Exception e) { - if (!(e instanceof ConnectionException)) { - needNotRetry = true; - } - } + for (InetSocketAddress address : addressList) { + if (!clusterAddressList.contains(address)) { + webCluster.disconnectPoint(address); + } + } - return needNotRetry; - } - } + needNotRetry = true; + return needNotRetry; + } catch (Exception e) { + if (!(e instanceof ConnectionException)) { + needNotRetry = true; + } + } - static class StopTask implements Task { + return needNotRetry; + } + } - } + static class StopTask implements Task { + + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/AuthException.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/AuthException.java index 561cf2fa1..2af5f3cea 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/AuthException.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/AuthException.java @@ -21,19 +21,19 @@ package com.navercorp.pinpoint.collector.cluster.zookeeper.exception; */ public class AuthException extends PinpointZookeeperException { - public AuthException() { - } + public AuthException() { + } - public AuthException(String message) { - super(message); - } + public AuthException(String message) { + super(message); + } - public AuthException(String message, Throwable cause) { - super(message, cause); - } + public AuthException(String message, Throwable cause) { + super(message, cause); + } - public AuthException(Throwable cause) { - super(cause); - } + public AuthException(Throwable cause) { + super(cause); + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/BadOperationException.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/BadOperationException.java index ca7daaa0b..53011447b 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/BadOperationException.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/BadOperationException.java @@ -21,19 +21,19 @@ package com.navercorp.pinpoint.collector.cluster.zookeeper.exception; */ public class BadOperationException extends PinpointZookeeperException { - public BadOperationException() { - } + public BadOperationException() { + } - public BadOperationException(String message) { - super(message); - } + public BadOperationException(String message) { + super(message); + } - public BadOperationException(String message, Throwable cause) { - super(message, cause); - } + public BadOperationException(String message, Throwable cause) { + super(message, cause); + } - public BadOperationException(Throwable cause) { - super(cause); - } + public BadOperationException(Throwable cause) { + super(cause); + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/ConnectionException.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/ConnectionException.java index e19675261..fea8ecf96 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/ConnectionException.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/ConnectionException.java @@ -21,19 +21,19 @@ package com.navercorp.pinpoint.collector.cluster.zookeeper.exception; */ public class ConnectionException extends PinpointZookeeperException { - public ConnectionException() { - } + public ConnectionException() { + } - public ConnectionException(String message) { - super(message); - } + public ConnectionException(String message) { + super(message); + } - public ConnectionException(String message, Throwable cause) { - super(message, cause); - } + public ConnectionException(String message, Throwable cause) { + super(message, cause); + } - public ConnectionException(Throwable cause) { - super(cause); - } + public ConnectionException(Throwable cause) { + super(cause); + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/PinpointZookeeperException.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/PinpointZookeeperException.java index c6f8a43a7..c8f9b7f03 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/PinpointZookeeperException.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/PinpointZookeeperException.java @@ -20,20 +20,20 @@ package com.navercorp.pinpoint.collector.cluster.zookeeper.exception; * @author koo.taejin */ public class PinpointZookeeperException extends Exception { - - public PinpointZookeeperException() { - } - public PinpointZookeeperException(String message) { - super(message); - } + public PinpointZookeeperException() { + } - public PinpointZookeeperException(String message, Throwable cause) { - super(message, cause); - } + public PinpointZookeeperException(String message) { + super(message); + } - public PinpointZookeeperException(Throwable cause) { - super(cause); - } + public PinpointZookeeperException(String message, Throwable cause) { + super(message, cause); + } + + public PinpointZookeeperException(Throwable cause) { + super(cause); + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/TimeoutException.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/TimeoutException.java index 44831e407..d49ccc38a 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/TimeoutException.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/TimeoutException.java @@ -21,19 +21,19 @@ package com.navercorp.pinpoint.collector.cluster.zookeeper.exception; */ public class TimeoutException extends PinpointZookeeperException { - public TimeoutException() { - } + public TimeoutException() { + } - public TimeoutException(String message) { - super(message); - } + public TimeoutException(String message) { + super(message); + } - public TimeoutException(String message, Throwable cause) { - super(message, cause); - } + public TimeoutException(String message, Throwable cause) { + super(message, cause); + } - public TimeoutException(Throwable cause) { - super(cause); - } + public TimeoutException(Throwable cause) { + super(cause); + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/UnknownException.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/UnknownException.java index 1b64c6826..d7eb02640 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/UnknownException.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/exception/UnknownException.java @@ -21,19 +21,19 @@ package com.navercorp.pinpoint.collector.cluster.zookeeper.exception; */ public class UnknownException extends PinpointZookeeperException { - public UnknownException() { - } + public UnknownException() { + } - public UnknownException(String message) { - super(message); - } + public UnknownException(String message) { + super(message); + } - public UnknownException(String message, Throwable cause) { - super(message, cause); - } + public UnknownException(String message, Throwable cause) { + super(message, cause); + } - public UnknownException(Throwable cause) { - super(cause); - } + public UnknownException(Throwable cause) { + super(cause); + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/job/AbstractJob.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/job/AbstractJob.java index 5a28caf6a..2f4177ba9 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/job/AbstractJob.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/job/AbstractJob.java @@ -22,50 +22,50 @@ import com.navercorp.pinpoint.rpc.server.ChannelContext; public class AbstractJob implements Job { - private final ChannelContext channelContext; - - private final int maxCount; - private final AtomicInteger currentCount; + private final ChannelContext channelContext; - public AbstractJob(ChannelContext channelContext) { - this(channelContext, 3); - } + private final int maxCount; + private final AtomicInteger currentCount; - public AbstractJob(ChannelContext channelContext, int maxCount) { - this.channelContext = channelContext; - - this.maxCount = maxCount; - this.currentCount = new AtomicInteger(0); - } - - @Override - public ChannelContext getChannelContext() { - return channelContext; - } - - @Override - public int getMaxRetryCount() { - return maxCount; - } + public AbstractJob(ChannelContext channelContext) { + this(channelContext, 3); + } - @Override - public int getCurrentRetryCount() { - return currentCount.get(); - } - - @Override - public void incrementCurrentRetryCount() { - currentCount.incrementAndGet(); - } - - @Override - public String toString() { - StringBuilder buffer = new StringBuilder(); - buffer.append(this.getClass().getSimpleName()); - buffer.append(", ChannelContext=").append(channelContext); - buffer.append(", Retry=").append(currentCount.get()).append("/").append(maxCount); - - return buffer.toString(); - } + public AbstractJob(ChannelContext channelContext, int maxCount) { + this.channelContext = channelContext; + + this.maxCount = maxCount; + this.currentCount = new AtomicInteger(0); + } + + @Override + public ChannelContext getChannelContext() { + return channelContext; + } + + @Override + public int getMaxRetryCount() { + return maxCount; + } + + @Override + public int getCurrentRetryCount() { + return currentCount.get(); + } + + @Override + public void incrementCurrentRetryCount() { + currentCount.incrementAndGet(); + } + + @Override + public String toString() { + StringBuilder buffer = new StringBuilder(); + buffer.append(this.getClass().getSimpleName()); + buffer.append(", ChannelContext=").append(channelContext); + buffer.append(", Retry=").append(currentCount.get()).append("/").append(maxCount); + + return buffer.toString(); + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/job/DeleteJob.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/job/DeleteJob.java index 7dcd00518..422b232ce 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/job/DeleteJob.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/job/DeleteJob.java @@ -23,8 +23,8 @@ import com.navercorp.pinpoint.rpc.server.ChannelContext; */ public class DeleteJob extends AbstractJob { - public DeleteJob(ChannelContext channelContext) { - super(channelContext); - } - + public DeleteJob(ChannelContext channelContext) { + super(channelContext); + } + } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/job/Job.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/job/Job.java index ff12dea51..68cb02406 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/job/Job.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/job/Job.java @@ -23,13 +23,13 @@ import com.navercorp.pinpoint.rpc.server.ChannelContext; */ public interface Job { - - ChannelContext getChannelContext(); - - int getMaxRetryCount(); - - int getCurrentRetryCount(); - - void incrementCurrentRetryCount(); - + + ChannelContext getChannelContext(); + + int getMaxRetryCount(); + + int getCurrentRetryCount(); + + void incrementCurrentRetryCount(); + } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/job/UpdateJob.java b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/job/UpdateJob.java index 2aca32e68..1c24a0522 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/job/UpdateJob.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/zookeeper/job/UpdateJob.java @@ -23,20 +23,20 @@ import com.navercorp.pinpoint.rpc.server.ChannelContext; */ public class UpdateJob extends AbstractJob { - private final byte[] contents; - - public UpdateJob(ChannelContext channelContext, byte[] contents) { - super(channelContext); - this.contents = contents; - } - - public UpdateJob(ChannelContext channelContext, int maxRetryCount, byte[] contents) { - super(channelContext, maxRetryCount); - this.contents = contents; - } + private final byte[] contents; - public byte[] getContents() { - return contents; - } + public UpdateJob(ChannelContext channelContext, byte[] contents) { + super(channelContext); + this.contents = contents; + } + + public UpdateJob(ChannelContext channelContext, int maxRetryCount, byte[] contents) { + super(channelContext, maxRetryCount); + this.contents = contents; + } + + public byte[] getContents() { + return contents; + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/config/CollectorConfiguration.java b/collector/src/main/java/com/navercorp/pinpoint/collector/config/CollectorConfiguration.java index 3a48b76be..b9b0449b9 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/config/CollectorConfiguration.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/config/CollectorConfiguration.java @@ -35,7 +35,7 @@ public class CollectorConfiguration implements InitializingBean { private final Logger logger = LoggerFactory.getLogger(this.getClass()); // cluster.zookeeper.address=dev.zk.pinpoint.navercorp.com -// cluster.zookeeper.sessiontimeout=3000 +// cluster.zookeeper.sessiontimeout=3000 private static final String CONFIG_FILE_NAME = "pinpoint-collector.properties"; private static final String DEFAULT_LISTEN_IP = "0.0.0.0"; @@ -103,11 +103,11 @@ public class CollectorConfiguration implements InitializingBean { } public int getUdpSpanListenPort() { - return udpSpanListenPort; - } + return udpSpanListenPort; + } - public int getUdpSpanWorkerThread() { + public int getUdpSpanWorkerThread() { return udpSpanWorkerThread; } @@ -131,29 +131,29 @@ public class CollectorConfiguration implements InitializingBean { this.udpSpanSocketReceiveBufferSize = udpSpanSocketReceiveBufferSize; } - public boolean isClusterEnable() { - return clusterEnable; - } + public boolean isClusterEnable() { + return clusterEnable; + } - public void setClusterEnable(boolean clusterEnable) { - this.clusterEnable = clusterEnable; - } + public void setClusterEnable(boolean clusterEnable) { + this.clusterEnable = clusterEnable; + } - public String getClusterAddress() { - return clusterAddress; - } + public String getClusterAddress() { + return clusterAddress; + } - public void setClusterAddress(String clusterAddress) { - this.clusterAddress = clusterAddress; - } - - public int getClusterSessionTimeout() { - return clusterSessionTimeout; - } + public void setClusterAddress(String clusterAddress) { + this.clusterAddress = clusterAddress; + } - public void setClusterSessionTimeout(int clusterSessionTimeout) { - this.clusterSessionTimeout = clusterSessionTimeout; - } + public int getClusterSessionTimeout() { + return clusterSessionTimeout; + } + + public void setClusterSessionTimeout(int clusterSessionTimeout) { + this.clusterSessionTimeout = clusterSessionTimeout; + } public void readConfigFile() { @@ -226,7 +226,7 @@ public class CollectorConfiguration implements InitializingBean { } private boolean readBoolen(Properties properties, String propertyName) { - final String value = properties.getProperty(propertyName); + final String value = properties.getProperty(propertyName); // if a default value will be needed afterwards, may match string value instead of Utils. // for now stay unmodified because of no need. diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/AgentIdApplicationIndexDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/AgentIdApplicationIndexDao.java index ede8cfc99..0bea27a57 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/AgentIdApplicationIndexDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/AgentIdApplicationIndexDao.java @@ -21,7 +21,7 @@ package com.navercorp.pinpoint.collector.dao; */ @Deprecated public interface AgentIdApplicationIndexDao { - void insert(String agentId, String applicationName); + void insert(String agentId, String applicationName); - String selectApplicationName(String agentId); + String selectApplicationName(String agentId); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/ApplicationTraceIndexDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/ApplicationTraceIndexDao.java index 67a3a1db9..9846ff0ec 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/ApplicationTraceIndexDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/ApplicationTraceIndexDao.java @@ -22,5 +22,5 @@ import com.navercorp.pinpoint.thrift.dto.TSpan; * @author emeroad */ public interface ApplicationTraceIndexDao { - void insert(TSpan span); + void insert(TSpan span); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/AutoFlusher.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/AutoFlusher.java index 66415c2c3..50daa8c3b 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/AutoFlusher.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/AutoFlusher.java @@ -35,14 +35,14 @@ import com.navercorp.pinpoint.common.util.PinpointThreadFactory; */ public class AutoFlusher { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private ScheduledExecutorService executor; + private ScheduledExecutorService executor; private long flushPeriod = 1000; - @Autowired - private List cachedStatisticsDaoList; + @Autowired + private List cachedStatisticsDaoList; public long getFlushPeriod() { return flushPeriod; @@ -53,54 +53,54 @@ public class AutoFlusher { } private static final class Worker implements Runnable { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final CachedStatisticsDao dao; + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final CachedStatisticsDao dao; - public Worker(CachedStatisticsDao dao) { - this.dao = dao; - } + public Worker(CachedStatisticsDao dao) { + this.dao = dao; + } - @Override - public void run() { - try { - dao.flushAll(); - } catch (Throwable th) { - logger.error("AutoFlusherWorker failed. Caused:{}", th.getMessage(), th); - } - } - } + @Override + public void run() { + try { + dao.flushAll(); + } catch (Throwable th) { + logger.error("AutoFlusherWorker failed. Caused:{}", th.getMessage(), th); + } + } + } - public void initialize() { - if (cachedStatisticsDaoList == null || cachedStatisticsDaoList.isEmpty()) { - return; - } + public void initialize() { + if (cachedStatisticsDaoList == null || cachedStatisticsDaoList.isEmpty()) { + return; + } - ThreadFactory threadFactory = PinpointThreadFactory.createThreadFactory(this.getClass().getSimpleName()); - executor = Executors.newScheduledThreadPool(cachedStatisticsDaoList.size(), threadFactory); - for (CachedStatisticsDao dao : cachedStatisticsDaoList) { - executor.scheduleAtFixedRate(new Worker(dao), 0L, flushPeriod, TimeUnit.MILLISECONDS); - } - logger.info("Auto flusher initialized."); - } + ThreadFactory threadFactory = PinpointThreadFactory.createThreadFactory(this.getClass().getSimpleName()); + executor = Executors.newScheduledThreadPool(cachedStatisticsDaoList.size(), threadFactory); + for (CachedStatisticsDao dao : cachedStatisticsDaoList) { + executor.scheduleAtFixedRate(new Worker(dao), 0L, flushPeriod, TimeUnit.MILLISECONDS); + } + logger.info("Auto flusher initialized."); + } - public void shutdown() { - logger.info("Shutdown auto flusher."); - shutdownExecutor(); - for (CachedStatisticsDao dao : cachedStatisticsDaoList) { - dao.flushAll(); - } - } + public void shutdown() { + logger.info("Shutdown auto flusher."); + shutdownExecutor(); + for (CachedStatisticsDao dao : cachedStatisticsDaoList) { + dao.flushAll(); + } + } - private void shutdownExecutor() { - executor.shutdown(); - try { - executor.awaitTermination(3000 + flushPeriod, TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } + private void shutdownExecutor() { + executor.shutdown(); + try { + executor.awaitTermination(3000 + flushPeriod, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } - public void setCachedStatisticsDaoList(List cachedStatisticsDaoList) { - this.cachedStatisticsDaoList = cachedStatisticsDaoList; - } + public void setCachedStatisticsDaoList(List cachedStatisticsDaoList) { + this.cachedStatisticsDaoList = cachedStatisticsDaoList; + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/CachedStatisticsDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/CachedStatisticsDao.java index 6cb122c25..c095d9b2c 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/CachedStatisticsDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/CachedStatisticsDao.java @@ -22,5 +22,5 @@ package com.navercorp.pinpoint.collector.dao; * */ public interface CachedStatisticsDao { - void flushAll(); + void flushAll(); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/HostApplicationMapDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/HostApplicationMapDao.java index 4b6240b36..3ec75e599 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/HostApplicationMapDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/HostApplicationMapDao.java @@ -22,5 +22,5 @@ package com.navercorp.pinpoint.collector.dao; * */ public interface HostApplicationMapDao { - void insert(String host, String bindApplicationName, short bindServiceType, String parentApplicationName, short parentServiceType); + void insert(String host, String bindApplicationName, short bindServiceType, String parentApplicationName, short parentServiceType); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/MapStatisticsCalleeDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/MapStatisticsCalleeDao.java index 371dad8f2..a6e7be1ff 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/MapStatisticsCalleeDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/MapStatisticsCalleeDao.java @@ -22,5 +22,5 @@ package com.navercorp.pinpoint.collector.dao; * @author emeroad */ public interface MapStatisticsCalleeDao extends CachedStatisticsDao { - void update(String calleeApplicationName, short calleeServiceType, String callerApplicationName, short callerServiceType, String callerHost, int elapsed, boolean isError); + void update(String calleeApplicationName, short calleeServiceType, String callerApplicationName, short callerServiceType, String callerHost, int elapsed, boolean isError); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/MapStatisticsCallerDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/MapStatisticsCallerDao.java index f452543f3..3ba4d37b0 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/MapStatisticsCallerDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/MapStatisticsCallerDao.java @@ -22,5 +22,5 @@ package com.navercorp.pinpoint.collector.dao; * @author emeroad */ public interface MapStatisticsCallerDao extends CachedStatisticsDao { - void update(String callerApplicationName, short callerServiceType, String callerAgentId, String calleeApplicationName, short calleeServiceType, String calleeHost, int elapsed, boolean isError); + void update(String callerApplicationName, short callerServiceType, String callerAgentId, String calleeApplicationName, short calleeServiceType, String calleeHost, int elapsed, boolean isError); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentIdApplicationIndexDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentIdApplicationIndexDao.java index 1892642b2..b873ace14 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentIdApplicationIndexDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentIdApplicationIndexDao.java @@ -40,15 +40,15 @@ import org.springframework.stereotype.Repository; @Deprecated public class HbaseAgentIdApplicationIndexDao implements AgentIdApplicationIndexDao { - @Autowired - private HbaseOperations2 hbaseTemplate; + @Autowired + private HbaseOperations2 hbaseTemplate; - @Autowired - @Qualifier("applicationNameMapper") - private RowMapper applicationNameMapper; + @Autowired + @Qualifier("applicationNameMapper") + private RowMapper applicationNameMapper; - @Override - public void insert(String agentId, String applicationName) { + @Override + public void insert(String agentId, String applicationName) { if (agentId == null) { throw new NullPointerException("agentId must not be null"); } @@ -57,23 +57,23 @@ public class HbaseAgentIdApplicationIndexDao implements AgentIdApplicationIndexD } byte[] agentIdByte = Bytes.toBytes(agentId); - byte[] appNameByte = Bytes.toBytes(applicationName); + byte[] appNameByte = Bytes.toBytes(applicationName); - Put put = new Put(agentIdByte); - put.add(AGENTID_APPLICATION_INDEX_CF_APPLICATION, appNameByte, appNameByte); + Put put = new Put(agentIdByte); + put.add(AGENTID_APPLICATION_INDEX_CF_APPLICATION, appNameByte, appNameByte); - hbaseTemplate.put(AGENTID_APPLICATION_INDEX, put); - } + hbaseTemplate.put(AGENTID_APPLICATION_INDEX, put); + } - @Override - public String selectApplicationName(String agentId) { + @Override + public String selectApplicationName(String agentId) { if (agentId == null) { throw new NullPointerException("agentId must not be null"); } byte[] rowKey = Bytes.toBytes(agentId); - Get get = new Get(rowKey); - get.addFamily(AGENTID_APPLICATION_INDEX_CF_APPLICATION); + Get get = new Get(rowKey); + get.addFamily(AGENTID_APPLICATION_INDEX_CF_APPLICATION); - return hbaseTemplate.get(AGENTID_APPLICATION_INDEX, get, applicationNameMapper); - } + return hbaseTemplate.get(AGENTID_APPLICATION_INDEX, get, applicationNameMapper); + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentInfoDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentInfoDao.java index 0645c9b6b..0b7f690c1 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentInfoDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentInfoDao.java @@ -41,45 +41,45 @@ import org.springframework.stereotype.Repository; @Repository public class HbaseAgentInfoDao implements AgentInfoDao { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private HbaseOperations2 hbaseTemplate; - - @Autowired - @Qualifier("agentInfoBoMapper") - private ThriftBoMapper agentInfoBoMapper; + @Autowired + private HbaseOperations2 hbaseTemplate; + + @Autowired + @Qualifier("agentInfoBoMapper") + private ThriftBoMapper agentInfoBoMapper; @Autowired @Qualifier("serverMetaDataBoMapper") private ThriftBoMapper serverMetaDataBoMapper; - @Override - public void insert(TAgentInfo agentInfo) { + @Override + public void insert(TAgentInfo agentInfo) { if (agentInfo == null) { throw new NullPointerException("agentInfo must not be null"); } if (logger.isDebugEnabled()) { - logger.debug("insert agent info. {}", agentInfo); - } + logger.debug("insert agent info. {}", agentInfo); + } - byte[] agentId = Bytes.toBytes(agentInfo.getAgentId()); - long reverseKey = TimeUtils.reverseTimeMillis(agentInfo.getStartTimestamp()); - byte[] rowKey = RowKeyUtils.concatFixedByteAndLong(agentId, HBaseTables.AGENT_NAME_MAX_LEN, reverseKey); - Put put = new Put(rowKey); + byte[] agentId = Bytes.toBytes(agentInfo.getAgentId()); + long reverseKey = TimeUtils.reverseTimeMillis(agentInfo.getStartTimestamp()); + byte[] rowKey = RowKeyUtils.concatFixedByteAndLong(agentId, HBaseTables.AGENT_NAME_MAX_LEN, reverseKey); + Put put = new Put(rowKey); - // should add additional agent informations. for now added only starttime for sqlMetaData - AgentInfoBo agentInfoBo = this.agentInfoBoMapper.map(agentInfo); - byte[] agentInfoBoValue = agentInfoBo.writeValue(); - put.add(HBaseTables.AGENTINFO_CF_INFO, HBaseTables.AGENTINFO_CF_INFO_IDENTIFIER, agentInfoBoValue); - - if (agentInfo.isSetServerMetaData()) { - ServerMetaDataBo serverMetaDataBo = this.serverMetaDataBoMapper.map(agentInfo.getServerMetaData()); - byte[] serverMetaDataBoValue = serverMetaDataBo.writeValue(); - put.add(HBaseTables.AGENTINFO_CF_INFO, HBaseTables.AGENTINFO_CF_INFO_SERVER_META_DATA, serverMetaDataBoValue); - } - - hbaseTemplate.put(HBaseTables.AGENTINFO, put); - } + // should add additional agent informations. for now added only starttime for sqlMetaData + AgentInfoBo agentInfoBo = this.agentInfoBoMapper.map(agentInfo); + byte[] agentInfoBoValue = agentInfoBo.writeValue(); + put.add(HBaseTables.AGENTINFO_CF_INFO, HBaseTables.AGENTINFO_CF_INFO_IDENTIFIER, agentInfoBoValue); + + if (agentInfo.isSetServerMetaData()) { + ServerMetaDataBo serverMetaDataBo = this.serverMetaDataBoMapper.map(agentInfo.getServerMetaData()); + byte[] serverMetaDataBoValue = serverMetaDataBo.writeValue(); + put.add(HBaseTables.AGENTINFO_CF_INFO, HBaseTables.AGENTINFO_CF_INFO_SERVER_META_DATA, serverMetaDataBoValue); + } + + hbaseTemplate.put(HBaseTables.AGENTINFO, put); + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationTraceIndexDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationTraceIndexDao.java index eb95626fc..7b9028c9f 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationTraceIndexDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationTraceIndexDao.java @@ -41,8 +41,8 @@ import org.springframework.stereotype.Repository; @Repository public class HbaseApplicationTraceIndexDao implements ApplicationTraceIndexDao { - @Autowired - private HbaseOperations2 hbaseTemplate; + @Autowired + private HbaseOperations2 hbaseTemplate; @Autowired private AcceptedTimeService acceptedTimeService; @@ -51,8 +51,8 @@ public class HbaseApplicationTraceIndexDao implements ApplicationTraceIndexDao { @Qualifier("applicationTraceIndexDistributor") private AbstractRowKeyDistributor rowKeyDistributor; - @Override - public void insert(final TSpan span) { + @Override + public void insert(final TSpan span) { if (span == null) { throw new NullPointerException("span must not be null"); } @@ -69,27 +69,27 @@ public class HbaseApplicationTraceIndexDao implements ApplicationTraceIndexDao { put.add(APPLICATION_TRACE_INDEX_CF_TRACE, makeQualifier(span) , acceptedTime, value); - hbaseTemplate.put(APPLICATION_TRACE_INDEX, put); - } + hbaseTemplate.put(APPLICATION_TRACE_INDEX, put); + } - private byte[] makeQualifier(final TSpan span) { - boolean useIndexedQualifier = false; - byte[] qualifier; + private byte[] makeQualifier(final TSpan span) { + boolean useIndexedQualifier = false; + byte[] qualifier; + + if (useIndexedQualifier) { + final Buffer columnName = new AutomaticBuffer(16); + // FIXME putVar not used in order to utilize hbase column prefix filter + columnName.put(span.getElapsed()); + columnName.put(SpanUtils.getVarTransactionId(span)); + qualifier = columnName.getBuffer(); + } else { + // OLD + // byte[] transactionId = SpanUtils.getTransactionId(span); + qualifier = SpanUtils.getVarTransactionId(span); + } + return qualifier; + } - if (useIndexedQualifier) { - final Buffer columnName = new AutomaticBuffer(16); - // FIXME putVar not used in order to utilize hbase column prefix filter - columnName.put(span.getElapsed()); - columnName.put(SpanUtils.getVarTransactionId(span)); - qualifier = columnName.getBuffer(); - } else { - // OLD - // byte[] transactionId = SpanUtils.getTransactionId(span); - qualifier = SpanUtils.getVarTransactionId(span); - } - return qualifier; - } - private byte[] crateRowKey(TSpan span, long acceptedTime) { // distribute key evenly byte[] applicationTraceIndexRowKey = SpanUtils.getApplicationTraceIndexRowKey(span.getApplicationName(), acceptedTime); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseHostApplicationMapDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseHostApplicationMapDao.java index 4fbcc72cd..83e505e15 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseHostApplicationMapDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseHostApplicationMapDao.java @@ -41,13 +41,13 @@ import org.springframework.stereotype.Repository; @Repository public class HbaseHostApplicationMapDao implements HostApplicationMapDao { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private HbaseOperations2 hbaseTemplate; + @Autowired + private HbaseOperations2 hbaseTemplate; - @Autowired - private AcceptedTimeService acceptedTimeService; + @Autowired + private AcceptedTimeService acceptedTimeService; @Autowired private TimeSlot timeSlot; @@ -60,8 +60,8 @@ public class HbaseHostApplicationMapDao implements HostApplicationMapDao { private final AtomicLongUpdateMap updater = new AtomicLongUpdateMap(); - @Override - public void insert(String host, String bindApplicationName, short bindServiceType, String parentApplicationName, short parentServiceType) { + @Override + public void insert(String host, String bindApplicationName, short bindServiceType, String parentApplicationName, short parentServiceType) { if (host == null) { throw new NullPointerException("host must not be null"); } @@ -76,7 +76,7 @@ public class HbaseHostApplicationMapDao implements HostApplicationMapDao { if (needUpdate) { insertHostVer2(host, bindApplicationName, bindServiceType, statisticsRowSlot, parentApplicationName, parentServiceType); } - } + } private long getSlotTime() { @@ -95,7 +95,7 @@ public class HbaseHostApplicationMapDao implements HostApplicationMapDao { // TODO should consider to add bellow codes again later. //String parentAgentId = null; //final byte[] rowKey = createRowKey(parentApplicationName, parentServiceType, statisticsRowSlot, parentAgentId); - final byte[] rowKey = createRowKey(parentApplicationName, parentServiceType, statisticsRowSlot, null); + final byte[] rowKey = createRowKey(parentApplicationName, parentServiceType, statisticsRowSlot, null); byte[] columnName = createColumnName(host, bindApplicationName, bindServiceType); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapResponseTimeDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapResponseTimeDao.java index d3fcc107f..5bc9b59f2 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapResponseTimeDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapResponseTimeDao.java @@ -46,13 +46,13 @@ import static com.navercorp.pinpoint.common.hbase.HBaseTables.*; @Repository public class HbaseMapResponseTimeDao implements MapResponseTimeDao { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private HbaseOperations2 hbaseTemplate; + @Autowired + private HbaseOperations2 hbaseTemplate; - @Autowired - private AcceptedTimeService acceptedTimeService; + @Autowired + private AcceptedTimeService acceptedTimeService; @Autowired private TimeSlot timeSlot; @@ -61,17 +61,17 @@ public class HbaseMapResponseTimeDao implements MapResponseTimeDao { @Qualifier("selfMerge") private RowKeyMerge rowKeyMerge; - private final boolean useBulk; + private final boolean useBulk; private final ConcurrentCounterMap counter = new ConcurrentCounterMap(); - public HbaseMapResponseTimeDao() { + public HbaseMapResponseTimeDao() { this(true); - } + } - public HbaseMapResponseTimeDao(boolean useBulk) { - this.useBulk = useBulk; - } + public HbaseMapResponseTimeDao(boolean useBulk) { + this.useBulk = useBulk; + } @Override public void received(String applicationName, short applicationServiceType, String agentId, int elapsed, boolean isError) { @@ -82,29 +82,29 @@ public class HbaseMapResponseTimeDao implements MapResponseTimeDao { throw new NullPointerException("agentId must not be null"); } - if (logger.isDebugEnabled()) { - logger.debug("[Received] {} ({})[{}]", + if (logger.isDebugEnabled()) { + logger.debug("[Received] {} ({})[{}]", applicationName, ServiceType.findServiceType(applicationServiceType), agentId); - } + } // make row key. rowkey is me - final long acceptedTime = acceptedTimeService.getAcceptedTime(); - final long rowTimeSlot = timeSlot.getTimeSlot(acceptedTime); + final long acceptedTime = acceptedTimeService.getAcceptedTime(); + final long rowTimeSlot = timeSlot.getTimeSlot(acceptedTime); final RowKey selfRowKey = new CallRowKey(applicationName, applicationServiceType, rowTimeSlot); final short slotNumber = ApplicationMapStatisticsUtils.getSlotNumber(applicationServiceType, elapsed, isError); final ColumnName selfColumnName = new ResponseColumnName(agentId, slotNumber); - if (useBulk) { + if (useBulk) { RowInfo rowInfo = new DefaultRowInfo(selfRowKey, selfColumnName); this.counter.increment(rowInfo, 1L); - } else { + } else { final byte[] rowKey = selfRowKey.getRowKey(); // column name is the name of caller app. byte[] columnName = selfColumnName.getColumnName(); increment(rowKey, columnName, 1L); } - } + } private void increment(byte[] rowKey, byte[] columnName, long increment) { if (rowKey == null) { @@ -117,11 +117,11 @@ public class HbaseMapResponseTimeDao implements MapResponseTimeDao { } - @Override - public void flushAll() { - if (!useBulk) { - throw new IllegalStateException("useBulk is " + useBulk); - } + @Override + public void flushAll() { + if (!useBulk) { + throw new IllegalStateException("useBulk is " + useBulk); + } // update statistics by rowkey and column for now. need to update it by rowkey later. Map remove = this.counter.remove(); @@ -133,5 +133,5 @@ public class HbaseMapResponseTimeDao implements MapResponseTimeDao { hbaseTemplate.increment(MAP_STATISTICS_SELF, merge); } - } + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapStatisticsCalleeDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapStatisticsCalleeDao.java index c0d2cf3da..5ec3d9155 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapStatisticsCalleeDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapStatisticsCalleeDao.java @@ -47,13 +47,13 @@ import java.util.Map; @Repository public class HbaseMapStatisticsCalleeDao implements MapStatisticsCalleeDao { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private HbaseOperations2 hbaseTemplate; + @Autowired + private HbaseOperations2 hbaseTemplate; - @Autowired - private AcceptedTimeService acceptedTimeService; + @Autowired + private AcceptedTimeService acceptedTimeService; @Autowired private TimeSlot timeSlot; @@ -62,21 +62,21 @@ public class HbaseMapStatisticsCalleeDao implements MapStatisticsCalleeDao { @Qualifier("calleeMerge") private RowKeyMerge rowKeyMerge; - private final boolean useBulk; + private final boolean useBulk; private final ConcurrentCounterMap counter = new ConcurrentCounterMap(); - public HbaseMapStatisticsCalleeDao() { + public HbaseMapStatisticsCalleeDao() { this(true); - } + } - public HbaseMapStatisticsCalleeDao(boolean useBulk) { - this.useBulk = useBulk; - } + public HbaseMapStatisticsCalleeDao(boolean useBulk) { + this.useBulk = useBulk; + } @Override - public void update(String calleeApplicationName, short calleeServiceType, String callerApplicationName, short callerServiceType, String callerHost, int elapsed, boolean isError) { + public void update(String calleeApplicationName, short calleeServiceType, String callerApplicationName, short callerServiceType, String callerHost, int elapsed, boolean isError) { if (callerApplicationName == null) { throw new NullPointerException("callerApplicationName must not be null"); } @@ -88,31 +88,31 @@ public class HbaseMapStatisticsCalleeDao implements MapStatisticsCalleeDao { logger.debug("[Callee] {} ({}) <- {} ({})[{}]", calleeApplicationName, ServiceType.findServiceType(calleeServiceType), callerApplicationName, ServiceType.findServiceType(callerServiceType), callerHost); - } + } // there may be no endpoint in case of httpclient - callerHost = StringUtils.defaultString(callerHost); + callerHost = StringUtils.defaultString(callerHost); - // make row key. rowkey is me - final long acceptedTime = acceptedTimeService.getAcceptedTime(); - final long rowTimeSlot = timeSlot.getTimeSlot(acceptedTime); + // make row key. rowkey is me + final long acceptedTime = acceptedTimeService.getAcceptedTime(); + final long rowTimeSlot = timeSlot.getTimeSlot(acceptedTime); final RowKey calleeRowKey = new CallRowKey(calleeApplicationName, calleeServiceType, rowTimeSlot); final short callerSlotNumber = ApplicationMapStatisticsUtils.getSlotNumber(callerServiceType, elapsed, isError); final ColumnName callerColumnName = new CallerColumnName(callerServiceType, callerApplicationName, callerHost, callerSlotNumber); - if (useBulk) { + if (useBulk) { RowInfo rowInfo = new DefaultRowInfo(calleeRowKey, callerColumnName); counter.increment(rowInfo, 1L); - } else { + } else { final byte[] rowKey = calleeRowKey.getRowKey(); // column name is the name of caller app. byte[] columnName = callerColumnName.getColumnName(); increment(rowKey, columnName, 1L); } - } + } @@ -127,10 +127,10 @@ public class HbaseMapStatisticsCalleeDao implements MapStatisticsCalleeDao { } @Override - public void flushAll() { - if (!useBulk) { - throw new IllegalStateException(); - } + public void flushAll() { + if (!useBulk) { + throw new IllegalStateException(); + } Map remove = this.counter.remove(); List merge = rowKeyMerge.createBulkIncrement(remove); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapStatisticsCallerDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapStatisticsCallerDao.java index 1ce95b83a..cbf8cbf4e 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapStatisticsCallerDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapStatisticsCallerDao.java @@ -47,13 +47,13 @@ import java.util.Map; @Repository public class HbaseMapStatisticsCallerDao implements MapStatisticsCallerDao { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private HbaseOperations2 hbaseTemplate; + @Autowired + private HbaseOperations2 hbaseTemplate; - @Autowired - private AcceptedTimeService acceptedTimeService; + @Autowired + private AcceptedTimeService acceptedTimeService; @Autowired @Qualifier("callerMerge") @@ -62,20 +62,20 @@ public class HbaseMapStatisticsCallerDao implements MapStatisticsCallerDao { @Autowired private TimeSlot timeSlot; - private final boolean useBulk; + private final boolean useBulk; private final ConcurrentCounterMap counter = new ConcurrentCounterMap(); - public HbaseMapStatisticsCallerDao() { + public HbaseMapStatisticsCallerDao() { this(true); - } + } - public HbaseMapStatisticsCallerDao(boolean useBulk) { - this.useBulk = useBulk; - } + public HbaseMapStatisticsCallerDao(boolean useBulk) { + this.useBulk = useBulk; + } @Override - public void update(String callerApplicationName, short callerServiceType, String callerAgentid, String calleeApplicationName, short calleeServiceType, String calleeHost, int elapsed, boolean isError) { + public void update(String callerApplicationName, short callerServiceType, String callerAgentid, String calleeApplicationName, short calleeServiceType, String calleeHost, int elapsed, boolean isError) { if (callerApplicationName == null) { throw new NullPointerException("callerApplicationName must not be null"); } @@ -83,32 +83,32 @@ public class HbaseMapStatisticsCallerDao implements MapStatisticsCallerDao { throw new NullPointerException("calleeApplicationName must not be null"); } - if (logger.isDebugEnabled()) { - logger.debug("[Caller] {} ({}) {} -> {} ({})[{}]", + if (logger.isDebugEnabled()) { + logger.debug("[Caller] {} ({}) {} -> {} ({})[{}]", callerApplicationName, ServiceType.findServiceType(callerServiceType), callerAgentid, calleeApplicationName, ServiceType.findServiceType(calleeServiceType), calleeHost); - } + } // there may be no endpoint in case of httpclient calleeHost = StringUtils.defaultString(calleeHost); // make row key. rowkey is me - final long acceptedTime = acceptedTimeService.getAcceptedTime(); - final long rowTimeSlot = timeSlot.getTimeSlot(acceptedTime); + final long acceptedTime = acceptedTimeService.getAcceptedTime(); + final long rowTimeSlot = timeSlot.getTimeSlot(acceptedTime); final RowKey callerRowKey = new CallRowKey(callerApplicationName, callerServiceType, rowTimeSlot); final short calleeSlotNumber = ApplicationMapStatisticsUtils.getSlotNumber(calleeServiceType, elapsed, isError); final ColumnName calleeColumnName = new CalleeColumnName(callerAgentid, calleeServiceType, calleeApplicationName, calleeHost, calleeSlotNumber); - if (useBulk) { + if (useBulk) { RowInfo rowInfo = new DefaultRowInfo(callerRowKey, calleeColumnName); this.counter.increment(rowInfo, 1L); - } else { + } else { final byte[] rowKey = callerRowKey.getRowKey(); // column name is the name of caller app. byte[] columnName = calleeColumnName.getColumnName(); increment(rowKey, columnName, 1L); } - } + } private void increment(byte[] rowKey, byte[] columnName, long increment) { if (rowKey == null) { @@ -121,11 +121,11 @@ public class HbaseMapStatisticsCallerDao implements MapStatisticsCallerDao { } - @Override - public void flushAll() { - if (!useBulk) { - throw new IllegalStateException(); - } + @Override + public void flushAll() { + if (!useBulk) { + throw new IllegalStateException(); + } // update statistics by rowkey and column for now. need to update it by rowkey later. Map remove = this.counter.remove(); List merge = rowKeyMerge.createBulkIncrement(remove); @@ -136,5 +136,5 @@ public class HbaseMapStatisticsCallerDao implements MapStatisticsCallerDao { hbaseTemplate.increment(MAP_STATISTICS_CALLEE, merge); } - } + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/AgentInfoHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/AgentInfoHandler.java index 53abd0ba1..c23f37612 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/AgentInfoHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/AgentInfoHandler.java @@ -34,48 +34,48 @@ import com.navercorp.pinpoint.thrift.dto.TResult; @Service("agentInfoHandler") public class AgentInfoHandler implements SimpleHandler, RequestResponseHandler { - private final Logger logger = LoggerFactory.getLogger(AgentInfoHandler.class.getName()); + private final Logger logger = LoggerFactory.getLogger(AgentInfoHandler.class.getName()); - @Autowired - private AgentInfoDao agentInfoDao; + @Autowired + private AgentInfoDao agentInfoDao; - @Autowired - private ApplicationIndexDao applicationIndexDao; + @Autowired + private ApplicationIndexDao applicationIndexDao; - public void handleSimple(TBase tbase) { - handleRequest(tbase); - } - - @Override - public TBase handleRequest(TBase tbase) { - if (!(tbase instanceof TAgentInfo)) { - logger.warn("invalid tbase:{}", tbase); - // it happens to return null not only at this BO(Business Object) but also at other BOs. + public void handleSimple(TBase tbase) { + handleRequest(tbase); + } - return null; - } + @Override + public TBase handleRequest(TBase tbase) { + if (!(tbase instanceof TAgentInfo)) { + logger.warn("invalid tbase:{}", tbase); + // it happens to return null not only at this BO(Business Object) but also at other BOs. - try { - TAgentInfo agentInfo = (TAgentInfo) tbase; + return null; + } - logger.debug("Received AgentInfo={}", agentInfo); + try { + TAgentInfo agentInfo = (TAgentInfo) tbase; - // agent info - agentInfoDao.insert(agentInfo); + logger.debug("Received AgentInfo={}", agentInfo); - // for querying agentid using applicationname - applicationIndexDao.insert(agentInfo); - - return new TResult(true); + // agent info + agentInfoDao.insert(agentInfo); + + // for querying agentid using applicationname + applicationIndexDao.insert(agentInfo); + + return new TResult(true); + + // for querying applicationname using agentid +// agentIdApplicationIndexDao.insert(agentInfo.getAgentId(), agentInfo.getApplicationName()); + } catch (Exception e) { + logger.warn("AgentInfo handle error. Caused:{}", e.getMessage(), e); + TResult result = new TResult(false); + result.setMessage(e.getMessage()); + return result; + } + } - // for querying applicationname using agentid -// agentIdApplicationIndexDao.insert(agentInfo.getAgentId(), agentInfo.getApplicationName()); - } catch (Exception e) { - logger.warn("AgentInfo handle error. Caused:{}", e.getMessage(), e); - TResult result = new TResult(false); - result.setMessage(e.getMessage()); - return result; - } - } - } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/ApiMetaDataHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/ApiMetaDataHandler.java index 8938a28cf..328f09414 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/ApiMetaDataHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/ApiMetaDataHandler.java @@ -32,24 +32,24 @@ import org.springframework.stereotype.Service; @Service public class ApiMetaDataHandler implements RequestResponseHandler { - private final Logger logger = LoggerFactory.getLogger(getClass()); + private final Logger logger = LoggerFactory.getLogger(getClass()); - @Autowired - private ApiMetaDataDao sqlMetaDataDao; + @Autowired + private ApiMetaDataDao sqlMetaDataDao; - @Override - public TBase handleRequest(TBase tbase) { - if (!(tbase instanceof TApiMetaData)) { - logger.error("invalid tbase:{}", tbase); - return null; - } - - TApiMetaData apiMetaData = (TApiMetaData) tbase; + @Override + public TBase handleRequest(TBase tbase) { + if (!(tbase instanceof TApiMetaData)) { + logger.error("invalid tbase:{}", tbase); + return null; + } - // Because api meta data is important , logging it at info level. - if (logger.isInfoEnabled()) { - logger.info("Received ApiMetaData={}", apiMetaData); - } + TApiMetaData apiMetaData = (TApiMetaData) tbase; + + // Because api meta data is important , logging it at info level. + if (logger.isInfoEnabled()) { + logger.info("Received ApiMetaData={}", apiMetaData); + } try { sqlMetaDataDao.insert(apiMetaData); @@ -60,5 +60,5 @@ public class ApiMetaDataHandler implements RequestResponseHandler { return result; } return new TResult(true); - } + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/Handler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/Handler.java index b7f20db6b..02b1496d7 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/Handler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/Handler.java @@ -23,7 +23,7 @@ import org.apache.thrift.TBase; * @author koo.taejin */ public interface Handler { - + void handle(TBase tbase, byte[] packet, int offset, int length); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/RequestResponseHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/RequestResponseHandler.java index bb1f54427..2ffb5b666 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/RequestResponseHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/RequestResponseHandler.java @@ -25,7 +25,7 @@ import org.springframework.stereotype.Service; */ @Service public interface RequestResponseHandler { - + TBase handleRequest(TBase tbase); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/SimpleHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/SimpleHandler.java index 5126ab8bb..c87da5eaa 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/SimpleHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/SimpleHandler.java @@ -23,7 +23,7 @@ import org.apache.thrift.TBase; * @author koo.taejin */ public interface SimpleHandler { - + void handleSimple(TBase tbase); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/SpanChunkHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/SpanChunkHandler.java index 58d5e8627..0f95aba3e 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/SpanChunkHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/SpanChunkHandler.java @@ -37,57 +37,57 @@ import org.springframework.stereotype.Service; @Service public class SpanChunkHandler implements SimpleHandler { - private final Logger logger = LoggerFactory.getLogger(getClass()); + private final Logger logger = LoggerFactory.getLogger(getClass()); - @Autowired - private TracesDao traceDao; + @Autowired + private TracesDao traceDao; - @Autowired - private StatisticsHandler statisticsHandler; + @Autowired + private StatisticsHandler statisticsHandler; - @Override - public void handleSimple(TBase tbase) { + @Override + public void handleSimple(TBase tbase) { - if (!(tbase instanceof TSpanChunk)) { - throw new IllegalArgumentException("unexpected tbase:" + tbase + " expected:" + this.getClass().getName()); - } + if (!(tbase instanceof TSpanChunk)) { + throw new IllegalArgumentException("unexpected tbase:" + tbase + " expected:" + this.getClass().getName()); + } - try { - TSpanChunk spanChunk = (TSpanChunk) tbase; + try { + TSpanChunk spanChunk = (TSpanChunk) tbase; - if (logger.isDebugEnabled()) { - logger.debug("Received SpanChunk={}", spanChunk); - } + if (logger.isDebugEnabled()) { + logger.debug("Received SpanChunk={}", spanChunk); + } - traceDao.insertSpanChunk(spanChunk); + traceDao.insertSpanChunk(spanChunk); - List spanEventList = spanChunk.getSpanEventList(); - if (spanEventList != null) { - logger.debug("SpanChunk Size:{}", spanEventList.size()); - // TODO need to batch update later. - for (TSpanEvent spanEvent : spanEventList) { - final ServiceType serviceType = ServiceType.findServiceType(spanEvent.getServiceType()); + List spanEventList = spanChunk.getSpanEventList(); + if (spanEventList != null) { + logger.debug("SpanChunk Size:{}", spanEventList.size()); + // TODO need to batch update later. + for (TSpanEvent spanEvent : spanEventList) { + final ServiceType serviceType = ServiceType.findServiceType(spanEvent.getServiceType()); - if (!serviceType.isRecordStatistics()) { - continue; - } + if (!serviceType.isRecordStatistics()) { + continue; + } - // if terminal update statistics - final int elapsed = spanEvent.getEndElapsed(); - final boolean hasException = SpanEventUtils.hasException(spanEvent); + // if terminal update statistics + final int elapsed = spanEvent.getEndElapsed(); + final boolean hasException = SpanEventUtils.hasException(spanEvent); - /** - * save information to draw a server map based on statistics - */ - // save the information of caller (the spanevent that span called) - statisticsHandler.updateCaller(spanChunk.getApplicationName(), spanChunk.getServiceType(), spanChunk.getAgentId(), spanEvent.getDestinationId(), serviceType.getCode(), spanEvent.getEndPoint(), elapsed, hasException); + /** + * save information to draw a server map based on statistics + */ + // save the information of caller (the spanevent that span called) + statisticsHandler.updateCaller(spanChunk.getApplicationName(), spanChunk.getServiceType(), spanChunk.getAgentId(), spanEvent.getDestinationId(), serviceType.getCode(), spanEvent.getEndPoint(), elapsed, hasException); - // save the information of callee (the span that called spanevent) - statisticsHandler.updateCallee(spanEvent.getDestinationId(), spanEvent.getServiceType(), spanChunk.getApplicationName(), spanChunk.getServiceType(), spanChunk.getEndPoint(), elapsed, hasException); - } - } - } catch (Exception e) { - logger.warn("SpanChunk handle error Caused:{}", e.getMessage(), e); - } - } + // save the information of callee (the span that called spanevent) + statisticsHandler.updateCallee(spanEvent.getDestinationId(), spanEvent.getServiceType(), spanChunk.getApplicationName(), spanChunk.getServiceType(), spanChunk.getEndPoint(), elapsed, hasException); + } + } + } catch (Exception e) { + logger.warn("SpanChunk handle error Caused:{}", e.getMessage(), e); + } + } } \ No newline at end of file diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/SpanHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/SpanHandler.java index bb75422c3..b855c1552 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/SpanHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/SpanHandler.java @@ -41,43 +41,43 @@ import org.springframework.stereotype.Service; @Service public class SpanHandler implements SimpleHandler { - private final Logger logger = LoggerFactory.getLogger(getClass()); + private final Logger logger = LoggerFactory.getLogger(getClass()); - @Autowired - private TracesDao traceDao; + @Autowired + private TracesDao traceDao; - @Autowired - private ApplicationTraceIndexDao applicationTraceIndexDao; + @Autowired + private ApplicationTraceIndexDao applicationTraceIndexDao; - @Autowired - private StatisticsHandler statisticsHandler; + @Autowired + private StatisticsHandler statisticsHandler; - @Autowired - private HostApplicationMapDao hostApplicationMapDao; + @Autowired + private HostApplicationMapDao hostApplicationMapDao; - public void handleSimple(TBase tbase) { + public void handleSimple(TBase tbase) { - if (!(tbase instanceof TSpan)) { - throw new IllegalArgumentException("unexpected tbase:" + tbase + " expected:" + this.getClass().getName()); - } + if (!(tbase instanceof TSpan)) { + throw new IllegalArgumentException("unexpected tbase:" + tbase + " expected:" + this.getClass().getName()); + } - try { - final TSpan span = (TSpan) tbase; - if (logger.isDebugEnabled()) { - logger.debug("Received SPAN={}", span); - } + try { + final TSpan span = (TSpan) tbase; + if (logger.isDebugEnabled()) { + logger.debug("Received SPAN={}", span); + } traceDao.insert(span); - applicationTraceIndexDao.insert(span); + applicationTraceIndexDao.insert(span); // insert statistics info for server map insertAcceptorHost(span); insertSpanStat(span); insertSpanEventStat(span); - } catch (Exception e) { - logger.warn("Span handle error. Caused:{}. Span:{}",e.getMessage(), tbase, e); - } - } + } catch (Exception e) { + logger.warn("Span handle error. Caused:{}. Span:{}",e.getMessage(), tbase, e); + } + } private void insertSpanStat(TSpan span) { // TODO consider to change span.isSetErr(); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/SqlMetaDataHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/SqlMetaDataHandler.java index 4ec60b9ba..256dfa50a 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/SqlMetaDataHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/SqlMetaDataHandler.java @@ -31,24 +31,24 @@ import org.springframework.stereotype.Service; */ @Service public class SqlMetaDataHandler implements RequestResponseHandler { - private final Logger logger = LoggerFactory.getLogger(getClass()); + private final Logger logger = LoggerFactory.getLogger(getClass()); - @Autowired - private SqlMetaDataDao sqlMetaDataDao; + @Autowired + private SqlMetaDataDao sqlMetaDataDao; + + @Override + public TBase handleRequest(TBase tbase) { + if (!(tbase instanceof TSqlMetaData)) { + logger.error("invalid tbase:{}", tbase); + return null; + } + + TSqlMetaData sqlMetaData = (TSqlMetaData) tbase; + + if (logger.isInfoEnabled()) { + logger.info("Received SqlMetaData:{}", sqlMetaData); + } - @Override - public TBase handleRequest(TBase tbase) { - if (!(tbase instanceof TSqlMetaData)) { - logger.error("invalid tbase:{}", tbase); - return null; - } - - TSqlMetaData sqlMetaData = (TSqlMetaData) tbase; - - if (logger.isInfoEnabled()) { - logger.info("Received SqlMetaData:{}", sqlMetaData); - } - try { sqlMetaDataDao.insert(sqlMetaData); @@ -59,5 +59,5 @@ public class SqlMetaDataHandler implements RequestResponseHandler { return result; } return new TResult(true); - } + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/StatisticsHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/StatisticsHandler.java index db5f86b48..036bb8ef9 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/StatisticsHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/StatisticsHandler.java @@ -31,11 +31,11 @@ import org.springframework.stereotype.Service; @Service public class StatisticsHandler { - @Autowired - private MapStatisticsCalleeDao mapStatisticsCalleeDao; + @Autowired + private MapStatisticsCalleeDao mapStatisticsCalleeDao; - @Autowired - private MapStatisticsCallerDao mapStatisticsCallerDao; + @Autowired + private MapStatisticsCallerDao mapStatisticsCallerDao; @Autowired private MapResponseTimeDao mapResponseTimeDao; @@ -54,9 +54,9 @@ public class StatisticsHandler { * @param elapsed * @param isError */ - public void updateCaller(String callerApplicationName, short callerServiceType, String callerAgentId, String calleeApplicationName, short calleeServiceType, String calleeHost, int elapsed, boolean isError) { - mapStatisticsCallerDao.update(callerApplicationName, callerServiceType, callerAgentId, calleeApplicationName, calleeServiceType, calleeHost, elapsed, isError); - } + public void updateCaller(String callerApplicationName, short callerServiceType, String callerAgentId, String calleeApplicationName, short calleeServiceType, String calleeHost, int elapsed, boolean isError) { + mapStatisticsCallerDao.update(callerApplicationName, callerServiceType, callerAgentId, calleeApplicationName, calleeServiceType, calleeHost, elapsed, isError); + } /** * Calling MySQL from Tomcat generates the following message for the callee(MySQL) :
@@ -72,9 +72,9 @@ public class StatisticsHandler { * @param elapsed * @param isError */ - public void updateCallee(String calleeApplicationName, short calleeServiceType, String callerApplicationName, short callerServiceType, String callerHost, int elapsed, boolean isError) { - mapStatisticsCalleeDao.update(calleeApplicationName, calleeServiceType, callerApplicationName, callerServiceType, callerHost, elapsed, isError); - } + public void updateCallee(String calleeApplicationName, short calleeServiceType, String callerApplicationName, short callerServiceType, String callerHost, int elapsed, boolean isError) { + mapStatisticsCalleeDao.update(calleeApplicationName, calleeServiceType, callerApplicationName, callerServiceType, callerHost, elapsed, isError); + } public void updateResponseTime(String applicationName, short serviceType, String agentId, int elapsed, boolean isError) { mapResponseTimeDao.received(applicationName, serviceType, agentId, elapsed, isError); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/StringMetaDataHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/StringMetaDataHandler.java index d2257f5f6..08372496d 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/StringMetaDataHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/StringMetaDataHandler.java @@ -32,23 +32,23 @@ import org.springframework.stereotype.Service; @Service public class StringMetaDataHandler implements RequestResponseHandler { - private final Logger logger = LoggerFactory.getLogger(getClass()); + private final Logger logger = LoggerFactory.getLogger(getClass()); - @Autowired - private StringMetaDataDao stringMetaDataDao; + @Autowired + private StringMetaDataDao stringMetaDataDao; - @Override - public TBase handleRequest(TBase tbase) { - if (!(tbase instanceof TStringMetaData)) { - logger.error("invalid tbase:{}", tbase); - return null; - } - - TStringMetaData stringMetaData = (TStringMetaData) tbase; - // because api data is important, logging it at info level - if (logger.isInfoEnabled()) { - logger.info("Received StringMetaData={}", stringMetaData); - } + @Override + public TBase handleRequest(TBase tbase) { + if (!(tbase instanceof TStringMetaData)) { + logger.error("invalid tbase:{}", tbase); + return null; + } + + TStringMetaData stringMetaData = (TStringMetaData) tbase; + // because api data is important, logging it at info level + if (logger.isInfoEnabled()) { + logger.info("Received StringMetaData={}", stringMetaData); + } try { stringMetaDataDao.insert(stringMetaData); @@ -59,5 +59,5 @@ public class StringMetaDataHandler implements RequestResponseHandler { return result; } return new TResult(true); - } + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/ApplicationNameMapper.java b/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/ApplicationNameMapper.java index 26aaafbfd..cab39c982 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/ApplicationNameMapper.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/ApplicationNameMapper.java @@ -26,24 +26,24 @@ import org.springframework.stereotype.Component; @Component @Deprecated public class ApplicationNameMapper implements RowMapper { - @Override - public String mapRow(Result result, int rowNum) throws Exception { + @Override + public String mapRow(Result result, int rowNum) throws Exception { if (result.isEmpty()) { return null; } - KeyValue[] raw = result.raw(); + KeyValue[] raw = result.raw(); - if (raw.length == 0) { - return null; - } + if (raw.length == 0) { + return null; + } - String[] ret = new String[raw.length]; - int index = 0; + String[] ret = new String[raw.length]; + int index = 0; - for (KeyValue kv : raw) { - ret[index++] = BytesUtils.toString(kv.getQualifier()); - } + for (KeyValue kv : raw) { + ret[index++] = BytesUtils.toString(kv.getQualifier()); + } - return ret[0]; - } + return ret[0]; + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/DataReceiver.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/DataReceiver.java index a6e8b3b7b..85bfbd62a 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/DataReceiver.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/DataReceiver.java @@ -20,7 +20,7 @@ package com.navercorp.pinpoint.collector.receiver; * @author emeroad */ public interface DataReceiver { - void start(); + void start(); - void shutdown(); + void shutdown(); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/DispatchHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/DispatchHandler.java index 360b08f39..574e3c05b 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/DispatchHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/DispatchHandler.java @@ -24,10 +24,10 @@ import org.apache.thrift.TBase; */ public interface DispatchHandler { - // Separating Send and Request. That dose not be satisfied but try to change that later. - - void dispatchSendMessage(TBase tBase, byte[] packet, int offset, int length); + // Separating Send and Request. That dose not be satisfied but try to change that later. + + void dispatchSendMessage(TBase tBase, byte[] packet, int offset, int length); + + TBase dispatchRequestMessage(TBase tBase, byte[] packet, int offset, int length); - TBase dispatchRequestMessage(TBase tBase, byte[] packet, int offset, int length); - } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/TcpDispatchHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/TcpDispatchHandler.java index 34d97e714..d1b490917 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/TcpDispatchHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/TcpDispatchHandler.java @@ -67,7 +67,7 @@ public class TcpDispatchHandler extends AbstractDispatchHandler { return stringMetaDataHandler; } if (tBase instanceof TAgentInfo) { - return agentInfoHandler; + return agentInfoHandler; } return null; } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/tcp/AgentHandshakePropertyType.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/tcp/AgentHandshakePropertyType.java index 09a51141c..c59376575 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/tcp/AgentHandshakePropertyType.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/tcp/AgentHandshakePropertyType.java @@ -25,52 +25,52 @@ import com.navercorp.pinpoint.rpc.util.ClassUtils; */ public enum AgentHandshakePropertyType { - SUPPORT_SERVER("supportServer", Boolean.class), + SUPPORT_SERVER("supportServer", Boolean.class), - HOSTNAME("hostName", String.class), - IP("ip", String.class), - AGENT_ID("agentId", String.class), - APPLICATION_NAME("applicationName", String.class), - SERVICE_TYPE("serviceType", Integer.class), - PID("pid", Integer.class), - VERSION("version", String.class), - START_TIMESTAMP("startTimestamp", Long.class); - + HOSTNAME("hostName", String.class), + IP("ip", String.class), + AGENT_ID("agentId", String.class), + APPLICATION_NAME("applicationName", String.class), + SERVICE_TYPE("serviceType", Integer.class), + PID("pid", Integer.class), + VERSION("version", String.class), + START_TIMESTAMP("startTimestamp", Long.class); - private final String name; - private final Class clazzType; - - private AgentHandshakePropertyType(String name, Class clazzType) { - this.name = name; - this.clazzType = clazzType; - } - public String getName() { - return name; - } - - public Class getClazzType() { - return clazzType; - } - - public static boolean hasAllType(Map properties) { - for (AgentHandshakePropertyType type : AgentHandshakePropertyType.values()) { - Object value = properties.get(type.getName()); - - if (type == SUPPORT_SERVER) { - continue; - } + private final String name; + private final Class clazzType; - if (value == null) { - return false; - } - - if (!ClassUtils.isAssignable(value.getClass(), type.getClazzType())) { - return false; - } - } - - return true; - } + private AgentHandshakePropertyType(String name, Class clazzType) { + this.name = name; + this.clazzType = clazzType; + } + + public String getName() { + return name; + } + + public Class getClazzType() { + return clazzType; + } + + public static boolean hasAllType(Map properties) { + for (AgentHandshakePropertyType type : AgentHandshakePropertyType.values()) { + Object value = properties.get(type.getName()); + + if (type == SUPPORT_SERVER) { + continue; + } + + if (value == null) { + return false; + } + + if (!ClassUtils.isAssignable(value.getClass(), type.getClazzType())) { + return false; + } + } + + return true; + } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/tcp/TCPReceiver.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/tcp/TCPReceiver.java index 540031a20..bdc6ecfcb 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/tcp/TCPReceiver.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/tcp/TCPReceiver.java @@ -68,10 +68,10 @@ import com.navercorp.pinpoint.thrift.util.SerializationUtils; */ public class TCPReceiver { - private final Logger logger = LoggerFactory.getLogger(TCPReceiver.class); + private final Logger logger = LoggerFactory.getLogger(TCPReceiver.class); private final ThreadFactory THREAD_FACTORY = new PinpointThreadFactory("Pinpoint-TCP-Worker"); - private final PinpointServerSocket pinpointServerSocket; + private final PinpointServerSocket pinpointServerSocket; private final DispatchHandler dispatchHandler; private final String bindAddress; private final int port; @@ -90,7 +90,7 @@ public class TCPReceiver { public TCPReceiver(DispatchHandler dispatchHandler, String bindAddress, int port) { - this(dispatchHandler, bindAddress, port, null); + this(dispatchHandler, bindAddress, port, null); } public TCPReceiver(DispatchHandler dispatchHandler, String bindAddress, int port, ZookeeperClusterService service) { @@ -102,43 +102,43 @@ public class TCPReceiver { } if (service == null || !service.isEnable()) { - this.pinpointServerSocket = new PinpointServerSocket(); + this.pinpointServerSocket = new PinpointServerSocket(); } else { - this.pinpointServerSocket = new PinpointServerSocket(service.getChannelStateChangeEventListener()); + this.pinpointServerSocket = new PinpointServerSocket(service.getChannelStateChangeEventListener()); } this.dispatchHandler = dispatchHandler; this.bindAddress = bindAddress; this.port = port; - } + } private void setL4TcpChannel(PinpointServerSocket pinpointServerSocket) { if (l4ipList == null) { return; } try { - List inetAddressList = new ArrayList(); - for (int i = 0; i < l4ipList.size(); i++) { - String l4Ip = l4ipList.get(i); - if (StringUtils.isBlank(l4Ip)) { - continue; - } - - InetAddress address = InetAddress.getByName(l4Ip); - if (address != null) { - inetAddressList.add(address); - } + List inetAddressList = new ArrayList(); + for (int i = 0; i < l4ipList.size(); i++) { + String l4Ip = l4ipList.get(i); + if (StringUtils.isBlank(l4Ip)) { + continue; + } + + InetAddress address = InetAddress.getByName(l4Ip); + if (address != null) { + inetAddressList.add(address); + } } - InetAddress[] inetAddressArray = new InetAddress[inetAddressList.size()]; - pinpointServerSocket.setIgnoreAddressList(inetAddressList.toArray(inetAddressArray)); + InetAddress[] inetAddressArray = new InetAddress[inetAddressList.size()]; + pinpointServerSocket.setIgnoreAddressList(inetAddressList.toArray(inetAddressArray)); } catch (UnknownHostException e) { logger.warn("l4ipList error {}", l4ipList, e); } } @PostConstruct - public void start() { + public void start() { setL4TcpChannel(pinpointServerSocket); // take care when attaching message handlers as events are generated from the IO thread. // pass them to a separate queue and handle them in a different thread. @@ -155,27 +155,27 @@ public class TCPReceiver { @Override public HandshakeResponseCode handleHandshake(Map properties) { - if (properties == null) { - return HandshakeResponseType.ProtocolError.PROTOCOL_ERROR; - } - - boolean hasAllType = AgentHandshakePropertyType.hasAllType(properties); - if (!hasAllType) { - return HandshakeResponseType.PropertyError.PROPERTY_ERROR; - } - - boolean supportServer = MapUtils.getBoolean(properties, AgentHandshakePropertyType.SUPPORT_SERVER.getName(), true); - if (supportServer) { - return HandshakeResponseType.Success.DUPLEX_COMMUNICATION; - } else { + if (properties == null) { + return HandshakeResponseType.ProtocolError.PROTOCOL_ERROR; + } + + boolean hasAllType = AgentHandshakePropertyType.hasAllType(properties); + if (!hasAllType) { + return HandshakeResponseType.PropertyError.PROPERTY_ERROR; + } + + boolean supportServer = MapUtils.getBoolean(properties, AgentHandshakePropertyType.SUPPORT_SERVER.getName(), true); + if (supportServer) { + return HandshakeResponseType.Success.DUPLEX_COMMUNICATION; + } else { return HandshakeResponseType.Success.SIMPLEX_COMMUNICATION; - } + } } }); this.pinpointServerSocket.bind(bindAddress, port); - } + } private void receive(SendPacket sendPacket, SocketChannel channel) { try { @@ -211,7 +211,7 @@ public class TCPReceiver { @Override public void run() { try { - TBase tBase = SerializationUtils.deserialize(bytes, deserializerFactory); + TBase tBase = SerializationUtils.deserialize(bytes, deserializerFactory); dispatchHandler.dispatchSendMessage(tBase, bytes, Header.HEADER_SIZE, bytes.length); } catch (TException e) { if (logger.isWarnEnabled()) { @@ -251,7 +251,7 @@ public class TCPReceiver { byte[] bytes = requestPacket.getPayload(); SocketAddress remoteAddress = socketChannel.getRemoteAddress(); try { - TBase tBase = SerializationUtils.deserialize(bytes, deserializerFactory); + TBase tBase = SerializationUtils.deserialize(bytes, deserializerFactory); if (tBase instanceof L4Packet) { if (logger.isDebugEnabled()) { L4Packet packet = (L4Packet) tBase; @@ -261,7 +261,7 @@ public class TCPReceiver { } TBase result = dispatchHandler.dispatchRequestMessage(tBase, bytes, Header.HEADER_SIZE, bytes.length); if (result != null) { - byte[] resultBytes = SerializationUtils.serialize(result, serializerFactory); + byte[] resultBytes = SerializationUtils.serialize(result, serializerFactory); socketChannel.sendResponseMessage(requestPacket, resultBytes); } } catch (TException e) { diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/AbstractUDPReceiver.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/AbstractUDPReceiver.java index fcea9f3f6..37abc3b5a 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/AbstractUDPReceiver.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/udp/AbstractUDPReceiver.java @@ -152,7 +152,7 @@ public abstract class AbstractUDPReceiver implements DataReceiver { try { worker.execute(getPacketDispatcher(this, packet)); } catch (RejectedExecutionException ree) { - rejectedCounter.inc(); + rejectedCounter.inc(); final int error = rejectedExecutionCount.incrementAndGet(); final int mod = 100; if ((error % mod) == 0) { diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/util/CollectorUtils.java b/collector/src/main/java/com/navercorp/pinpoint/collector/util/CollectorUtils.java index 7fe51787c..ea4e85725 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/util/CollectorUtils.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/util/CollectorUtils.java @@ -23,14 +23,14 @@ import java.lang.management.ManagementFactory; */ public final class CollectorUtils { - private CollectorUtils() { - } + private CollectorUtils() { + } - public static String getServerIdentifier() { + public static String getServerIdentifier() { + + // if the return value is not unique, it will be changed to MAC address or IP address. + // It means that the return value has format of "pid@hostname" (it is possible to be duplicate for "localhost") + return ManagementFactory.getRuntimeMXBean().getName(); + } - // if the return value is not unique, it will be changed to MAC address or IP address. - // It means that the return value has format of "pid@hostname" (it is possible to be duplicate for "localhost") - return ManagementFactory.getRuntimeMXBean().getName(); - } - } diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationTrraceIndexColumnTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationTrraceIndexColumnTest.java index ebcaf0b3f..35ee36025 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationTrraceIndexColumnTest.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationTrraceIndexColumnTest.java @@ -31,42 +31,42 @@ import com.navercorp.pinpoint.common.buffer.OffsetFixedBuffer; */ public class HbaseApplicationTrraceIndexColumnTest { - @Test - public void indexedColumnName() { - final int elapsed = 1234; - final String agentId = "agentId"; - final long agentStartTime = 1234567890L; - final long transactionSequence = 1234567890L; + @Test + public void indexedColumnName() { + final int elapsed = 1234; + final String agentId = "agentId"; + final long agentStartTime = 1234567890L; + final long transactionSequence = 1234567890L; - // final Buffer buffer= new AutomaticBuffer(32); - // buffer.putPrefixedString(agentId); - // buffer.putSVar(transactionId.getAgentStartTime()); - // buffer.putVar(transactionId.getTransactionSequence()); - // return buffer.getBuffer(); + // final Buffer buffer= new AutomaticBuffer(32); + // buffer.putPrefixedString(agentId); + // buffer.putSVar(transactionId.getAgentStartTime()); + // buffer.putVar(transactionId.getTransactionSequence()); + // return buffer.getBuffer(); - final Buffer originalBuffer = new AutomaticBuffer(16); - originalBuffer.putVar(elapsed); - originalBuffer.putPrefixedString(agentId); - originalBuffer.putSVar(agentStartTime); - originalBuffer.putVar(transactionSequence); + final Buffer originalBuffer = new AutomaticBuffer(16); + originalBuffer.putVar(elapsed); + originalBuffer.putPrefixedString(agentId); + originalBuffer.putSVar(agentStartTime); + originalBuffer.putVar(transactionSequence); - byte[] source = originalBuffer.getBuffer(); + byte[] source = originalBuffer.getBuffer(); - final Buffer fetched = new OffsetFixedBuffer(source, 0); + final Buffer fetched = new OffsetFixedBuffer(source, 0); - Assert.assertEquals(elapsed, fetched.readVarInt()); - Assert.assertEquals(agentId, fetched.readPrefixedString()); - Assert.assertEquals(agentStartTime, fetched.readSVarLong()); - Assert.assertEquals(transactionSequence, fetched.readVarLong()); - } + Assert.assertEquals(elapsed, fetched.readVarInt()); + Assert.assertEquals(agentId, fetched.readPrefixedString()); + Assert.assertEquals(agentStartTime, fetched.readSVarLong()); + Assert.assertEquals(transactionSequence, fetched.readVarLong()); + } - @Test - public void indexColumnName2() { - final int elapsed = 1234; - final byte[] bytes = "thisisbytes".getBytes(); + @Test + public void indexColumnName2() { + final int elapsed = 1234; + final byte[] bytes = "thisisbytes".getBytes(); - final Buffer columnName = new AutomaticBuffer(16); - columnName.put(elapsed); - columnName.putPrefixedBytes(bytes); - } + final Buffer columnName = new AutomaticBuffer(16); + columnName.put(elapsed); + columnName.putPrefixedBytes(bytes); + } } diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/NettyUdpReceiverTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/NettyUdpReceiverTest.java index bc7b70e16..afbf7322e 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/NettyUdpReceiverTest.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/NettyUdpReceiverTest.java @@ -59,8 +59,8 @@ public class NettyUdpReceiverTest { latch.await(); } catch (InterruptedException e) { } - logger.debug("server-shutdown"); - udpServer.shutdown(); + logger.debug("server-shutdown"); + udpServer.shutdown(); } }); thread.start(); @@ -96,7 +96,7 @@ public class NettyUdpReceiverTest { so.send(datagramPacket); Thread.sleep(10); } - so.close(); + so.close(); } private ConnectionlessBootstrap createUdpServer() { diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/UDPReceiverTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/UDPReceiverTest.java index 43f1ef557..d28469afe 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/UDPReceiverTest.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/udp/UDPReceiverTest.java @@ -39,26 +39,26 @@ public class UDPReceiverTest { @Test @Ignore - public void startStop() { - try { - DataReceiver receiver = new BaseUDPReceiver("test", new DispatchHandler() { + public void startStop() { + try { + DataReceiver receiver = new BaseUDPReceiver("test", new DispatchHandler() { @Override public void dispatchSendMessage(TBase tBase, byte[] packet, int offset, int length) { } - @Override - public TBase dispatchRequestMessage(TBase tBase, byte[] packet, int offset, int length) { - // TODO Auto-generated method stub - return null; - } - + @Override + public TBase dispatchRequestMessage(TBase tBase, byte[] packet, int offset, int length) { + // TODO Auto-generated method stub + return null; + } + }, "127.0.0.1", 10999, 1024, 1, 10); - - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(e.getMessage()); - } - } + + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(e.getMessage()); + } + } @Test public void hostNullCheck() { diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/HistogramSchema.java b/commons/src/main/java/com/navercorp/pinpoint/common/HistogramSchema.java index be0107959..7c6c18d4f 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/HistogramSchema.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/HistogramSchema.java @@ -44,7 +44,7 @@ public class HistogramSchema { // Should use the reference of FAST_SCHEMA, NORMAL created internally private HistogramSchema(int typeCode, short fast, String fastName, short normal, String normalName, short slow, String slowName, String verySlowName, String errorName) { - this.typeCode = typeCode; + this.typeCode = typeCode; this.fastSlot = new HistogramSlot(fast, SlotType.FAST, fastName); this.normalSlot = new HistogramSlot(normal, SlotType.NORMAL, normalName); this.slowSlot = new HistogramSlot(slow, SlotType.SLOW, slowName); @@ -117,26 +117,26 @@ public class HistogramSchema { } @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + typeCode; - return result; - } + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + typeCode; + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - HistogramSchema other = (HistogramSchema) obj; - if (typeCode != other.typeCode) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + HistogramSchema other = (HistogramSchema) obj; + if (typeCode != other.typeCode) + return false; + return true; + } @Override public String toString() { diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/ServiceType.java b/commons/src/main/java/com/navercorp/pinpoint/common/ServiceType.java index 50fe203c3..2fc81fd1c 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/ServiceType.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/ServiceType.java @@ -36,8 +36,8 @@ public enum ServiceType { // Undefined Service Code - UNDEFINED((short) -1, "UNDEFINED", TERMINAL, !RECORD_STATISTICS, !INCLUDE_DESTINATION, NORMAL_SCHEMA), - + UNDEFINED((short) -1, "UNDEFINED", TERMINAL, !RECORD_STATISTICS, !INCLUDE_DESTINATION, NORMAL_SCHEMA), + // Callee node that agent hasn't been installed UNKNOWN((short) 1, "UNKNOWN", !TERMINAL, RECORD_STATISTICS, !INCLUDE_DESTINATION, NORMAL_SCHEMA), @@ -111,8 +111,8 @@ public enum ServiceType { HTTP_CLIENT((short) 9050, "HTTP_CLIENT", !TERMINAL, RECORD_STATISTICS, !INCLUDE_DESTINATION, NORMAL_SCHEMA), HTTP_CLIENT_INTERNAL((short) 9051, "HTTP_CLIENT", !TERMINAL, !RECORD_STATISTICS, !INCLUDE_DESTINATION, NORMAL_SCHEMA), JDK_HTTPURLCONNECTOR((short) 9055, "JDK_HTTPCONNECTOR", !TERMINAL, RECORD_STATISTICS, !INCLUDE_DESTINATION, NORMAL_SCHEMA), - NPC_CLIENT((short) 9060, "NPC_CLIENT", !TERMINAL, RECORD_STATISTICS, !INCLUDE_DESTINATION, NORMAL_SCHEMA), - NIMM_CLIENT((short) 9070, "NIMM_CLIENT", !TERMINAL, RECORD_STATISTICS, !INCLUDE_DESTINATION, NORMAL_SCHEMA); + NPC_CLIENT((short) 9060, "NPC_CLIENT", !TERMINAL, RECORD_STATISTICS, !INCLUDE_DESTINATION, NORMAL_SCHEMA), + NIMM_CLIENT((short) 9070, "NIMM_CLIENT", !TERMINAL, RECORD_STATISTICS, !INCLUDE_DESTINATION, NORMAL_SCHEMA); public static final short WAS_START_INDEX = 1000; public static final short WAS_END_INDEX = 2000; @@ -146,7 +146,7 @@ public enum ServiceType { } public boolean isInternalMethod() { - return this == INTERNAL_METHOD; + return this == INTERNAL_METHOD; } public boolean isRpcClient() { @@ -162,14 +162,14 @@ public enum ServiceType { return recordStatistics; } - public boolean isUnknown() { - return this == ServiceType.UNKNOWN; // || this == ServiceType.UNKNOWN_CLOUD; - } + public boolean isUnknown() { + return this == ServiceType.UNKNOWN; // || this == ServiceType.UNKNOWN_CLOUD; + } // return true when the service type is USER or can not be identified public boolean isUser() { - return this == ServiceType.USER; + return this == ServiceType.USER; } public short getCode() { @@ -192,9 +192,9 @@ public enum ServiceType { return histogramSchema; } - public boolean isWas() { - return isWas(this.code); - } + public boolean isWas() { + return isWas(this.code); + } public static boolean isWas(final short code) { return code >= WAS_START_INDEX && code < WAS_END_INDEX; @@ -209,7 +209,7 @@ public enum ServiceType { ServiceType serviceType = CODE_LOOKUP_TABLE.get(code); if (serviceType == null) { return UNDEFINED; - //return UNKNOWN; + //return UNKNOWN; } return serviceType; } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/ServiceTypeConstants.java b/commons/src/main/java/com/navercorp/pinpoint/common/ServiceTypeConstants.java index 1d0872323..7df144d16 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/ServiceTypeConstants.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/ServiceTypeConstants.java @@ -22,7 +22,7 @@ package com.navercorp.pinpoint.common; * */ public class ServiceTypeConstants { - public static final boolean TERMINAL = true; - public static final boolean RECORD_STATISTICS = true; - public static final boolean INCLUDE_DESTINATION = true; + public static final boolean TERMINAL = true; + public static final boolean RECORD_STATISTICS = true; + public static final boolean INCLUDE_DESTINATION = true; } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/SlotType.java b/commons/src/main/java/com/navercorp/pinpoint/common/SlotType.java index eccc2013d..8100cd811 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/SlotType.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/SlotType.java @@ -18,5 +18,5 @@ package com.navercorp.pinpoint.common; public enum SlotType { - FAST, NORMAL, SLOW, VERY_SLOW, ERROR + FAST, NORMAL, SLOW, VERY_SLOW, ERROR } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/bo/Span.java b/commons/src/main/java/com/navercorp/pinpoint/common/bo/Span.java index 89faa407a..45b5ba2ca 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/bo/Span.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/bo/Span.java @@ -24,11 +24,11 @@ import com.navercorp.pinpoint.common.ServiceType; * @author emeroad */ public interface Span { - ServiceType getServiceType(); + ServiceType getServiceType(); - String getRpc(); + String getRpc(); - String getEndPoint(); - - List getAnnotationBoList(); + String getEndPoint(); + + List getAnnotationBoList(); } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/bo/SpanBo.java b/commons/src/main/java/com/navercorp/pinpoint/common/bo/SpanBo.java index 424f9f8d1..fcbd64f96 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/bo/SpanBo.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/bo/SpanBo.java @@ -149,9 +149,9 @@ public class SpanBo implements com.navercorp.pinpoint.common.bo.Span { this.version = (byte) (version & 0xFF); } - public String getTransactionId() { + public String getTransactionId() { return TransactionIdUtils.formatString(traceAgentId, traceAgentStartTime, traceTransactionSequence); - } + } public String getAgentId() { return agentId; @@ -312,22 +312,22 @@ public class SpanBo implements com.navercorp.pinpoint.common.bo.Span { } public int getErrCode() { - return errCode; - } + return errCode; + } - public void setErrCode(int errCode) { - this.errCode = errCode; - } + public void setErrCode(int errCode) { + this.errCode = errCode; + } public String getRemoteAddr() { - return remoteAddr; - } + return remoteAddr; + } - public void setRemoteAddr(String remoteAddr) { - this.remoteAddr = remoteAddr; - } + public void setRemoteAddr(String remoteAddr) { + this.remoteAddr = remoteAddr; + } - public long getCollectorAcceptTime() { + public long getCollectorAcceptTime() { return collectorAcceptTime; } @@ -336,7 +336,7 @@ public class SpanBo implements com.navercorp.pinpoint.common.bo.Span { } public boolean isRoot() { - return -1L == parentSpanId; + return -1L == parentSpanId; } public boolean hasException() { diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/bo/SpanEventBo.java b/commons/src/main/java/com/navercorp/pinpoint/common/bo/SpanEventBo.java index 97923c4b9..8cfd246ff 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/bo/SpanEventBo.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/bo/SpanEventBo.java @@ -31,36 +31,36 @@ import com.navercorp.pinpoint.thrift.dto.*; * @author emeroad */ public class SpanEventBo implements Span { - private static final int VERSION_SIZE = 1; + private static final int VERSION_SIZE = 1; // version 0 means that the type of prefix's size is int - private byte version = 0; + private byte version = 0; - private String agentId; + private String agentId; private String applicationId; private long agentStartTime; private String traceAgentId; - private long traceAgentStartTime; - private long traceTransactionSequence; + private long traceAgentStartTime; + private long traceTransactionSequence; - private long spanId; - private short sequence; + private long spanId; + private short sequence; - private int startElapsed; - private int endElapsed; + private int startElapsed; + private int endElapsed; - private String rpc; - private ServiceType serviceType; + private String rpc; + private ServiceType serviceType; private String destinationId; - private String endPoint; + private String endPoint; private int apiId; - private List annotationBoList; + private List annotationBoList; - private int depth = -1; - private long nextSpanId = -1; + private int depth = -1; + private long nextSpanId = -1; private boolean hasException; private int exceptionId; @@ -70,10 +70,10 @@ public class SpanEventBo implements Span { private String exceptionClass; - public SpanEventBo() { - } + public SpanEventBo() { + } - public SpanEventBo(TSpan tSpan, TSpanEvent tSpanEvent) { + public SpanEventBo(TSpan tSpan, TSpanEvent tSpanEvent) { if (tSpan == null) { throw new NullPointerException("tSpan must not be null"); } @@ -93,30 +93,30 @@ public class SpanEventBo implements Span { this.traceAgentStartTime = transactionId.getAgentStartTime(); this.traceTransactionSequence = transactionId.getTransactionSequence(); - this.spanId = tSpan.getSpanId(); - this.sequence = tSpanEvent.getSequence(); + this.spanId = tSpan.getSpanId(); + this.sequence = tSpanEvent.getSequence(); - this.startElapsed = tSpanEvent.getStartElapsed(); - this.endElapsed = tSpanEvent.getEndElapsed(); + this.startElapsed = tSpanEvent.getStartElapsed(); + this.endElapsed = tSpanEvent.getEndElapsed(); - this.rpc = tSpanEvent.getRpc(); - this.serviceType = ServiceType.findServiceType(tSpanEvent.getServiceType()); + this.rpc = tSpanEvent.getRpc(); + this.serviceType = ServiceType.findServiceType(tSpanEvent.getServiceType()); this.destinationId = tSpanEvent.getDestinationId(); this.endPoint = tSpanEvent.getEndPoint(); this.apiId = tSpanEvent.getApiId(); - - if (tSpanEvent.isSetDepth()) { - this.depth = tSpanEvent.getDepth(); - } + + if (tSpanEvent.isSetDepth()) { + this.depth = tSpanEvent.getDepth(); + } - if (tSpanEvent.isSetNextSpanId()) { - this.nextSpanId = tSpanEvent.getNextSpanId(); - } + if (tSpanEvent.isSetNextSpanId()) { + this.nextSpanId = tSpanEvent.getNextSpanId(); + } - setAnnotationBoList(tSpanEvent.getAnnotations()); + setAnnotationBoList(tSpanEvent.getAnnotations()); final TIntStringValue exceptionInfo = tSpanEvent.getExceptionInfo(); if (exceptionInfo != null) { @@ -124,9 +124,9 @@ public class SpanEventBo implements Span { this.exceptionId = exceptionInfo.getIntValue(); this.exceptionMessage = exceptionInfo.getStringValue(); } - } + } - public SpanEventBo(TSpanChunk spanChunk, TSpanEvent spanEvent) { + public SpanEventBo(TSpanChunk spanChunk, TSpanEvent spanEvent) { if (spanChunk == null) { throw new NullPointerException("spanChunk must not be null"); } @@ -146,29 +146,29 @@ public class SpanEventBo implements Span { this.traceAgentStartTime = transactionId.getAgentStartTime(); this.traceTransactionSequence = transactionId.getTransactionSequence(); - this.spanId = spanChunk.getSpanId(); - this.sequence = spanEvent.getSequence(); + this.spanId = spanChunk.getSpanId(); + this.sequence = spanEvent.getSequence(); - this.startElapsed = spanEvent.getStartElapsed(); - this.endElapsed = spanEvent.getEndElapsed(); + this.startElapsed = spanEvent.getStartElapsed(); + this.endElapsed = spanEvent.getEndElapsed(); - this.rpc = spanEvent.getRpc(); - this.serviceType = ServiceType.findServiceType(spanEvent.getServiceType()); + this.rpc = spanEvent.getRpc(); + this.serviceType = ServiceType.findServiceType(spanEvent.getServiceType()); this.destinationId = spanEvent.getDestinationId(); - this.endPoint = spanEvent.getEndPoint(); + this.endPoint = spanEvent.getEndPoint(); this.apiId = spanEvent.getApiId(); - - if (spanEvent.isSetDepth()) { - this.depth = spanEvent.getDepth(); - } - if (spanEvent.isSetNextSpanId()) { - this.nextSpanId = spanEvent.getNextSpanId(); - } - - setAnnotationBoList(spanEvent.getAnnotations()); + if (spanEvent.isSetDepth()) { + this.depth = spanEvent.getDepth(); + } + + if (spanEvent.isSetNextSpanId()) { + this.nextSpanId = spanEvent.getNextSpanId(); + } + + setAnnotationBoList(spanEvent.getAnnotations()); final TIntStringValue exceptionInfo = spanEvent.getExceptionInfo(); if (exceptionInfo != null) { @@ -176,25 +176,25 @@ public class SpanEventBo implements Span { this.exceptionId = exceptionInfo.getIntValue(); this.exceptionMessage = exceptionInfo.getStringValue(); } - } + } - public byte getVersion() { - return version; - } + public byte getVersion() { + return version; + } - public void setVersion(byte version) { - this.version = version; - } + public void setVersion(byte version) { + this.version = version; + } - public String getAgentId() { - return agentId; - } + public String getAgentId() { + return agentId; + } - public void setAgentId(String agentId) { - this.agentId = agentId; - } + public void setAgentId(String agentId) { + this.agentId = agentId; + } public long getAgentStartTime() { return this.agentStartTime; @@ -213,76 +213,76 @@ public class SpanEventBo implements Span { } public long getTraceAgentStartTime() { - return traceAgentStartTime; - } + return traceAgentStartTime; + } - public void setTraceAgentStartTime(long traceAgentStartTime) { - this.traceAgentStartTime = traceAgentStartTime; - } + public void setTraceAgentStartTime(long traceAgentStartTime) { + this.traceAgentStartTime = traceAgentStartTime; + } - public long getTraceTransactionSequence() { - return traceTransactionSequence; - } + public long getTraceTransactionSequence() { + return traceTransactionSequence; + } - public void setTraceTransactionSequence(long traceTransactionSequence) { - this.traceTransactionSequence = traceTransactionSequence; - } + public void setTraceTransactionSequence(long traceTransactionSequence) { + this.traceTransactionSequence = traceTransactionSequence; + } - public void setSpanId(long spanId) { - this.spanId = spanId; - } + public void setSpanId(long spanId) { + this.spanId = spanId; + } - public long getSpanId() { - return this.spanId; - } + public long getSpanId() { + return this.spanId; + } - public short getSequence() { - return sequence; - } + public short getSequence() { + return sequence; + } - public void setSequence(short sequence) { - this.sequence = sequence; - } + public void setSequence(short sequence) { + this.sequence = sequence; + } - public int getStartElapsed() { - return startElapsed; - } + public int getStartElapsed() { + return startElapsed; + } - public void setStartElapsed(int startElapsed) { - this.startElapsed = startElapsed; - } + public void setStartElapsed(int startElapsed) { + this.startElapsed = startElapsed; + } - public int getEndElapsed() { - return endElapsed; - } + public int getEndElapsed() { + return endElapsed; + } - public void setEndElapsed(int endElapsed) { - this.endElapsed = endElapsed; - } + public void setEndElapsed(int endElapsed) { + this.endElapsed = endElapsed; + } - public String getRpc() { - return rpc; - } + public String getRpc() { + return rpc; + } - public void setRpc(String rpc) { - this.rpc = rpc; - } + public void setRpc(String rpc) { + this.rpc = rpc; + } - public ServiceType getServiceType() { - return serviceType; - } + public ServiceType getServiceType() { + return serviceType; + } - public void setServiceType(ServiceType serviceType) { - this.serviceType = serviceType; - } + public void setServiceType(ServiceType serviceType) { + this.serviceType = serviceType; + } - public String getEndPoint() { - return endPoint; - } + public String getEndPoint() { + return endPoint; + } - public void setEndPoint(String endPoint) { - this.endPoint = endPoint; - } + public void setEndPoint(String endPoint) { + this.endPoint = endPoint; + } public int getApiId() { return apiId; @@ -302,35 +302,35 @@ public class SpanEventBo implements Span { public List getAnnotationBoList() { - return annotationBoList; - } + return annotationBoList; + } - public int getDepth() { - return depth; - } + public int getDepth() { + return depth; + } - public void setDepth(int depth) { - this.depth = depth; - } + public void setDepth(int depth) { + this.depth = depth; + } - public long getNextSpanId() { - return nextSpanId; - } + public long getNextSpanId() { + return nextSpanId; + } - public void setNextSpanId(long nextSpanId) { - this.nextSpanId = nextSpanId; - } + public void setNextSpanId(long nextSpanId) { + this.nextSpanId = nextSpanId; + } - private void setAnnotationBoList(List annotations) { + private void setAnnotationBoList(List annotations) { if (annotations == null) { return; } - List boList = new ArrayList(annotations.size()); - for (TAnnotation ano : annotations) { - boList.add(new AnnotationBo(ano)); - } - this.annotationBoList = boList; - } + List boList = new ArrayList(annotations.size()); + for (TAnnotation ano : annotations) { + boList.add(new AnnotationBo(ano)); + } + this.annotationBoList = boList; + } public boolean hasException() { return hasException; @@ -400,52 +400,52 @@ public class SpanEventBo implements Span { private void writeAnnotation(Buffer buffer) { AnnotationBoList annotationBo = new AnnotationBoList(this.annotationBoList); annotationBo.writeValue(buffer); - } + } - public int readValue(byte[] bytes, int offset) { + public int readValue(byte[] bytes, int offset) { final Buffer buffer = new OffsetFixedBuffer(bytes, offset); - this.version = buffer.readByte(); + this.version = buffer.readByte(); - // this.mostTraceID = buffer.readLong(); - // this.leastTraceID = buffer.readLong(); + // this.mostTraceID = buffer.readLong(); + // this.leastTraceID = buffer.readLong(); - this.agentId = buffer.readPrefixedString(); + this.agentId = buffer.readPrefixedString(); this.applicationId = buffer.readPrefixedString(); this.agentStartTime = buffer.readVarLong(); - this.startElapsed = buffer.readVarInt(); - this.endElapsed = buffer.readVarInt(); + this.startElapsed = buffer.readVarInt(); + this.endElapsed = buffer.readVarInt(); // don't need to get sequence because it can be got at Qualifier - // this.sequence = buffer.readShort(); + // this.sequence = buffer.readShort(); - this.rpc = buffer.readPrefixedString(); - this.serviceType = ServiceType.findServiceType(buffer.readShort()); - this.endPoint = buffer.readPrefixedString(); + this.rpc = buffer.readPrefixedString(); + this.serviceType = ServiceType.findServiceType(buffer.readShort()); + this.endPoint = buffer.readPrefixedString(); this.destinationId = buffer.readPrefixedString(); this.apiId = buffer.readSVarInt(); - this.depth = buffer.readSVarInt(); - this.nextSpanId = buffer.readLong(); + this.depth = buffer.readSVarInt(); + this.nextSpanId = buffer.readLong(); this.hasException = buffer.readBoolean(); if (hasException) { this.exceptionId = buffer.readSVarInt(); this.exceptionMessage = buffer.readPrefixedString(); } - - this.annotationBoList = readAnnotation(buffer); - return buffer.getOffset(); - } - private List readAnnotation(Buffer buffer) { + this.annotationBoList = readAnnotation(buffer); + return buffer.getOffset(); + } + + private List readAnnotation(Buffer buffer) { AnnotationBoList annotationBoList = new AnnotationBoList(); annotationBoList.readValue(buffer); - return annotationBoList.getAnnotationBoList(); - } + return annotationBoList.getAnnotationBoList(); + } @Override public String toString() { diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2.java b/commons/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2.java index 1ef4e9094..9f8693111 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2.java @@ -436,20 +436,20 @@ public class HbaseTemplate2 extends HbaseTemplate implements HbaseOperations2, I }); } - public List find(String tableName, final Scan scan, final AbstractRowKeyDistributor rowKeyDistributor, int limit, final RowMapper action, final LimitEventHandler limitEventHandler) { - final LimitRowMapperResultsExtractor resultsExtractor = new LimitRowMapperResultsExtractor(action, limit, limitEventHandler); - return execute(tableName, new TableCallback>() { - @Override - public List doInTable(HTableInterface htable) throws Throwable { - final ResultScanner scanner = createDistributeScanner(htable, scan, rowKeyDistributor); - try { - return resultsExtractor.extractData(scanner); - } finally { - scanner.close(); - } - } - }); - } + public List find(String tableName, final Scan scan, final AbstractRowKeyDistributor rowKeyDistributor, int limit, final RowMapper action, final LimitEventHandler limitEventHandler) { + final LimitRowMapperResultsExtractor resultsExtractor = new LimitRowMapperResultsExtractor(action, limit, limitEventHandler); + return execute(tableName, new TableCallback>() { + @Override + public List doInTable(HTableInterface htable) throws Throwable { + final ResultScanner scanner = createDistributeScanner(htable, scan, rowKeyDistributor); + try { + return resultsExtractor.extractData(scanner); + } finally { + scanner.close(); + } + } + }); + } @Override diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/hbase/LimitRowMapperResultsExtractor.java b/commons/src/main/java/com/navercorp/pinpoint/common/hbase/LimitRowMapperResultsExtractor.java index bf586841e..0b16d4c91 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/hbase/LimitRowMapperResultsExtractor.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/hbase/LimitRowMapperResultsExtractor.java @@ -47,7 +47,7 @@ public class LimitRowMapperResultsExtractor implements ResultsExtractor implements ResultsExtractor extractData(ResultScanner results) throws Exception { - final List rs = new ArrayList(); - int rowNum = 0; + final List rs = new ArrayList(); + int rowNum = 0; Result lastResult = null; - - for (Result result : results) { + + for (Result result : results) { final T t = this.rowMapper.mapRow(result, rowNum); lastResult = result; - if (t instanceof Collection) { - rowNum += ((Collection) t).size(); - } else if (t instanceof Map) { - rowNum += ((Map) t).size(); - } else if (t == null) { - // empty - } else if (t.getClass().isArray()) { - rowNum += Array.getLength(t); - } else { - rowNum++; - } - rs.add(t); - if (rowNum >= limit) { - break; - } - } + if (t instanceof Collection) { + rowNum += ((Collection) t).size(); + } else if (t instanceof Map) { + rowNum += ((Map) t).size(); + } else if (t == null) { + // empty + } else if (t.getClass().isArray()) { + rowNum += Array.getLength(t); + } else { + rowNum++; + } + rs.add(t); + if (rowNum >= limit) { + break; + } + } eventHandler.handleLastResult(lastResult); - return rs; - } + return rs; + } } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/hbase/filter/ApplicationTraceIndexResponseTimeFilter.java b/commons/src/main/java/com/navercorp/pinpoint/common/hbase/filter/ApplicationTraceIndexResponseTimeFilter.java index fe2d7f805..83f30bd69 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/hbase/filter/ApplicationTraceIndexResponseTimeFilter.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/hbase/filter/ApplicationTraceIndexResponseTimeFilter.java @@ -36,54 +36,54 @@ import com.navercorp.pinpoint.common.buffer.OffsetFixedBuffer; @Deprecated public class ApplicationTraceIndexResponseTimeFilter extends FilterBase { - private byte[] value = null; - private boolean filterRow = true; + private byte[] value = null; + private boolean filterRow = true; - private final int responseTimeFrom; - private final int responseTimeTo; + private final int responseTimeFrom; + private final int responseTimeTo; - public ApplicationTraceIndexResponseTimeFilter(int responseTimeFrom, int responseTimeTo) { - super(); - this.responseTimeFrom = responseTimeFrom; - this.responseTimeTo = responseTimeTo; - } + public ApplicationTraceIndexResponseTimeFilter(int responseTimeFrom, int responseTimeTo) { + super(); + this.responseTimeFrom = responseTimeFrom; + this.responseTimeTo = responseTimeTo; + } - @Override - public void reset() { - // reset flag when comparing with a new value - this.filterRow = true; - } + @Override + public void reset() { + // reset flag when comparing with a new value + this.filterRow = true; + } - @Override - public ReturnCode filterKeyValue(KeyValue kv) { - final byte[] buffer = kv.getBuffer(); + @Override + public ReturnCode filterKeyValue(KeyValue kv) { + final byte[] buffer = kv.getBuffer(); - final int valueOffset = kv.getValueOffset(); - final Buffer valueBuffer = new OffsetFixedBuffer(buffer, valueOffset); - int elapsed = valueBuffer.readVarInt(); + final int valueOffset = kv.getValueOffset(); + final Buffer valueBuffer = new OffsetFixedBuffer(buffer, valueOffset); + int elapsed = valueBuffer.readVarInt(); - if (elapsed < responseTimeFrom || elapsed > responseTimeTo) { - // skip row if conditions are not met - filterRow = false; - } + if (elapsed < responseTimeFrom || elapsed > responseTimeTo) { + // skip row if conditions are not met + filterRow = false; + } - // always return this value as the actual decision for filtering happens later - return ReturnCode.INCLUDE; - } + // always return this value as the actual decision for filtering happens later + return ReturnCode.INCLUDE; + } - @Override - public boolean filterRow() { - // the actual decision for filtering happens here depending on the flag - return filterRow; - } + @Override + public boolean filterRow() { + // the actual decision for filtering happens here depending on the flag + return filterRow; + } - @Override - public void readFields(DataInput dataInput) throws IOException { - this.value = Bytes.readByteArray(dataInput); - } + @Override + public void readFields(DataInput dataInput) throws IOException { + this.value = Bytes.readByteArray(dataInput); + } - @Override - public void write(DataOutput dataOutput) throws IOException { - Bytes.writeByteArray(dataOutput, this.value); - } + @Override + public void write(DataOutput dataOutput) throws IOException { + Bytes.writeByteArray(dataOutput, this.value); + } } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/AnnotationUtils.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/AnnotationUtils.java index 037ceed30..2674ba5d1 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/AnnotationUtils.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/AnnotationUtils.java @@ -102,11 +102,11 @@ public final class AnnotationUtils { } if (serviceType == ServiceType.IBATIS || serviceType == ServiceType.MYBATIS) { - return findAnnotationBo(list, AnnotationKey.ARGS0); + return findAnnotationBo(list, AnnotationKey.ARGS0); } if (serviceType == ServiceType.SPRING_ORM_IBATIS) { - return findAnnotationBo(list, AnnotationKey.ARGS0); + return findAnnotationBo(list, AnnotationKey.ARGS0); } return null; diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/BytesUtils.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/BytesUtils.java index 781cf269e..7d7c1be8a 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/BytesUtils.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/BytesUtils.java @@ -377,24 +377,24 @@ public final class BytesUtils { return (n >>> 1) ^ -(n & 1); } - public static byte[] concat(final byte[]... arrays) { - int totalLength = 0; + public static byte[] concat(final byte[]... arrays) { + int totalLength = 0; final int length = arrays.length; for (int i = 0; i < length; i++) { - totalLength += arrays[i].length; - } + totalLength += arrays[i].length; + } - byte[] result = new byte[totalLength]; + byte[] result = new byte[totalLength]; - int currentIndex = 0; - for (int i = 0; i < length; i++) { - System.arraycopy(arrays[i], 0, result, currentIndex, arrays[i].length); - currentIndex += arrays[i].length; - } + int currentIndex = 0; + for (int i = 0; i < length; i++) { + System.arraycopy(arrays[i], 0, result, currentIndex, arrays[i].length); + currentIndex += arrays[i].length; + } - return result; - } + return result; + } public static String safeTrim(final String string) { if (string == null) { 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 df74f5e55..df2b45376 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 @@ -22,99 +22,99 @@ import java.util.Enumeration; * @author emeroad */ public class DelegateEnumeration implements Enumeration { - private static final Object NULL_OBJECT = new Object(); + private static final Object NULL_OBJECT = new Object(); - private final Enumeration delegate; - private final Filter filter; + private final Enumeration delegate; + private final Filter filter; - private boolean hasMoreElements; - private E nextElement; - private Exception nextException; + private boolean hasMoreElements; + private E nextElement; + private Exception nextException; - private static final Filter SKIP_FILTER = new Filter() { - @Override - public boolean filter(Object o) { - return false; - } - }; + private static final Filter SKIP_FILTER = new Filter() { + @Override + public boolean filter(Object o) { + return false; + } + }; - @SuppressWarnings("unchecked") - public DelegateEnumeration(Enumeration delegate) { - this(delegate, SKIP_FILTER); - } + @SuppressWarnings("unchecked") + public DelegateEnumeration(Enumeration delegate) { + this(delegate, SKIP_FILTER); + } - public DelegateEnumeration(Enumeration delegate, Filter filter) { - this.delegate = delegate; - this.filter = filter; - } + public DelegateEnumeration(Enumeration delegate, Filter filter) { + this.delegate = delegate; + this.filter = filter; + } - @Override - public boolean hasMoreElements() { - next(); - return hasMoreElements; - } + @Override + public boolean hasMoreElements() { + next(); + return hasMoreElements; + } - @Override - public E nextElement() { - next(); - if (nextException != null) { - Exception exception = this.nextException; - this.nextException = null; - this.throwException(exception); - } - final E result = getNextElement(); - this.nextElement = null; - return result; - } + @Override + public E nextElement() { + next(); + if (nextException != null) { + Exception exception = this.nextException; + this.nextException = null; + this.throwException(exception); + } + final E result = getNextElement(); + this.nextElement = null; + return result; + } - private E getNextElement() { - if (nextElement == NULL_OBJECT) { - return null; - } - return nextElement; - } + private E getNextElement() { + if (nextElement == NULL_OBJECT) { + return null; + } + return nextElement; + } - @SuppressWarnings("unchecked") - private void throwException(Exception exception) throws T { - throw (T) exception; - } + @SuppressWarnings("unchecked") + private void throwException(Exception exception) throws T { + throw (T) exception; + } - private void next() { - if (nextElement != null || nextException != null) { - return; - } + private void next() { + if (nextElement != null || nextException != null) { + return; + } - while (true) { - final boolean hasMoreElements = delegate.hasMoreElements(); - E nextElement; - try { - nextElement = delegate.nextElement(); - } catch (Exception e) { - this.hasMoreElements = hasMoreElements; - this.nextException = e; - break; - } + while (true) { + final boolean hasMoreElements = delegate.hasMoreElements(); + E nextElement; + try { + nextElement = delegate.nextElement(); + } catch (Exception e) { + this.hasMoreElements = hasMoreElements; + this.nextException = e; + break; + } - if (filter.filter(nextElement)) { - continue; - } + if (filter.filter(nextElement)) { + continue; + } - this.hasMoreElements = hasMoreElements; - if (nextElement == null) { - this.nextElement = (E) NULL_OBJECT; - } else { - this.nextElement = nextElement; - } - break; + this.hasMoreElements = hasMoreElements; + if (nextElement == null) { + this.nextElement = (E) NULL_OBJECT; + } else { + this.nextElement = nextElement; + } + break; - } + } - } + } - public static interface Filter { - boolean filter(E e); - } + public static interface Filter { + boolean filter(E e); + } } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/EmptyEnumeration.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/EmptyEnumeration.java index 2d205da0d..ac230178f 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/EmptyEnumeration.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/EmptyEnumeration.java @@ -22,26 +22,26 @@ import java.util.Enumeration; * @author emeroad */ public class EmptyEnumeration implements Enumeration { - private static final NullNextElementAction NULL_NEXT_ELEMENT_ACTION = new NullNextElementAction(); + private static final NullNextElementAction NULL_NEXT_ELEMENT_ACTION = new NullNextElementAction(); - private final NextElementAction nextElementAction; + private final NextElementAction nextElementAction; - @SuppressWarnings("unchecked") - public EmptyEnumeration() { - this(NULL_NEXT_ELEMENT_ACTION); - } + @SuppressWarnings("unchecked") + public EmptyEnumeration() { + this(NULL_NEXT_ELEMENT_ACTION); + } - public EmptyEnumeration(NextElementAction nextElementAction) { - this.nextElementAction = nextElementAction; - } + public EmptyEnumeration(NextElementAction nextElementAction) { + this.nextElementAction = nextElementAction; + } - @Override - public boolean hasMoreElements() { - return false; - } + @Override + public boolean hasMoreElements() { + return false; + } - @Override - public E nextElement() { - return nextElementAction.nextElement(); - } + @Override + public E nextElement() { + return nextElementAction.nextElement(); + } } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmUtils.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmUtils.java index a78ebd61d..8403accac 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmUtils.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmUtils.java @@ -24,32 +24,32 @@ import java.util.Map; * @author hyungil.jeong */ public final class JvmUtils { - private static final RuntimeMXBean RUNTIME_MX_BEAN = ManagementFactory.getRuntimeMXBean(); - private static final Map SYSTEM_PROPERTIES = RUNTIME_MX_BEAN.getSystemProperties(); - - private static final JvmVersion JVM_VERSION = _getVersion(); - - private JvmUtils() { - } - - public static JvmVersion getVersion() { - return JVM_VERSION; - } - - public static boolean supportsVersion(JvmVersion other) { - return JVM_VERSION.onOrAfter(other); - } - - public static String getSystemProperty(SystemPropertyKey systemPropertyKey) { - String key = systemPropertyKey.getKey(); - if (SYSTEM_PROPERTIES.containsKey(key)) { - return SYSTEM_PROPERTIES.get(key); - } - return ""; - } - - private static JvmVersion _getVersion() { - String javaVersion = getSystemProperty(SystemPropertyKey.JAVA_SPECIFICATION_VERSION); - return JvmVersion.getFromVersion(javaVersion); - } + private static final RuntimeMXBean RUNTIME_MX_BEAN = ManagementFactory.getRuntimeMXBean(); + private static final Map SYSTEM_PROPERTIES = RUNTIME_MX_BEAN.getSystemProperties(); + + private static final JvmVersion JVM_VERSION = _getVersion(); + + private JvmUtils() { + } + + public static JvmVersion getVersion() { + return JVM_VERSION; + } + + public static boolean supportsVersion(JvmVersion other) { + return JVM_VERSION.onOrAfter(other); + } + + public static String getSystemProperty(SystemPropertyKey systemPropertyKey) { + String key = systemPropertyKey.getKey(); + if (SYSTEM_PROPERTIES.containsKey(key)) { + return SYSTEM_PROPERTIES.get(key); + } + return ""; + } + + private static JvmVersion _getVersion() { + String javaVersion = getSystemProperty(SystemPropertyKey.JAVA_SPECIFICATION_VERSION); + return JvmVersion.getFromVersion(javaVersion); + } } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmVersion.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmVersion.java index 022717ee0..019e40d5e 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmVersion.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/JvmVersion.java @@ -20,51 +20,51 @@ package com.navercorp.pinpoint.common.util; * @author hyungil.jeong */ public enum JvmVersion { - JAVA_5(1.5, 49), - JAVA_6(1.6, 50), - JAVA_7(1.7, 51), - JAVA_8(1.8, 52), - UNSUPPORTED(-1, -1); - - private final double version; - private final int classVersion; - - private JvmVersion(double version, int classVersion) { - this.version = version; - this.classVersion = classVersion; - } - - public boolean onOrAfter(JvmVersion other) { - if (this == UNSUPPORTED || other == UNSUPPORTED) { - return false; - } - return this == other || this.version > other.version; - } - - public static JvmVersion getFromVersion(String javaVersion) { - try { - double version = Double.parseDouble(javaVersion); - return getFromVersion(version); - } catch (NumberFormatException e) { - return UNSUPPORTED; - } - } - - public static JvmVersion getFromVersion(double javaVersion) { - for (JvmVersion version : JvmVersion.values()) { - if (Double.compare(version.version, javaVersion) == 0) { - return version; - } - } - return JvmVersion.UNSUPPORTED; - } - - public static JvmVersion getFromClassVersion(int classVersion) { - for (JvmVersion version : JvmVersion.values()) { - if (version.classVersion == classVersion) { - return version; - } - } - return JvmVersion.UNSUPPORTED; - } + JAVA_5(1.5, 49), + JAVA_6(1.6, 50), + JAVA_7(1.7, 51), + JAVA_8(1.8, 52), + UNSUPPORTED(-1, -1); + + private final double version; + private final int classVersion; + + private JvmVersion(double version, int classVersion) { + this.version = version; + this.classVersion = classVersion; + } + + public boolean onOrAfter(JvmVersion other) { + if (this == UNSUPPORTED || other == UNSUPPORTED) { + return false; + } + return this == other || this.version > other.version; + } + + public static JvmVersion getFromVersion(String javaVersion) { + try { + double version = Double.parseDouble(javaVersion); + return getFromVersion(version); + } catch (NumberFormatException e) { + return UNSUPPORTED; + } + } + + public static JvmVersion getFromVersion(double javaVersion) { + for (JvmVersion version : JvmVersion.values()) { + if (Double.compare(version.version, javaVersion) == 0) { + return version; + } + } + return JvmVersion.UNSUPPORTED; + } + + public static JvmVersion getFromClassVersion(int classVersion) { + for (JvmVersion version : JvmVersion.values()) { + if (version.classVersion == classVersion) { + return version; + } + } + return JvmVersion.UNSUPPORTED; + } } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/NetUtils.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/NetUtils.java index 67659d756..393dfba8d 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/NetUtils.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/NetUtils.java @@ -34,147 +34,147 @@ import java.util.List; */ public final class NetUtils { - public static final String LOOPBACK_ADDRESS_V4 = "127.0.0.1"; - - private NetUtils() { - } + public static final String LOOPBACK_ADDRESS_V4 = "127.0.0.1"; - public static List toInetSocketAddressLIst(List addressList) { - List inetSocketAddressList = new ArrayList(); + private NetUtils() { + } - for (String address : addressList) { - InetSocketAddress inetSocketAddress = toInetSocketAddress(address); - if (inetSocketAddress != null) { - inetSocketAddressList.add(inetSocketAddress); - } - } + public static List toInetSocketAddressLIst(List addressList) { + List inetSocketAddressList = new ArrayList(); - return inetSocketAddressList; - } + for (String address : addressList) { + InetSocketAddress inetSocketAddress = toInetSocketAddress(address); + if (inetSocketAddress != null) { + inetSocketAddressList.add(inetSocketAddress); + } + } - public static InetSocketAddress toInetSocketAddress(String address) { - try { - URI uri = new URI("pinpoint://" + address); + return inetSocketAddressList; + } - return new InetSocketAddress(uri.getHost(), uri.getPort()); - } catch (URISyntaxException ignore) { + public static InetSocketAddress toInetSocketAddress(String address) { + try { + URI uri = new URI("pinpoint://" + address); + + return new InetSocketAddress(uri.getHost(), uri.getPort()); + } catch (URISyntaxException ignore) { // skip - } + } - return null; - } + return null; + } - public static String getLocalV4Ip() { - try { - InetAddress localHost = InetAddress.getLocalHost(); - String localIp = localHost.getHostAddress(); - if (validationIpV4FormatAddress(localIp)) { - return localIp; - } - } catch (UnknownHostException ignore) { + public static String getLocalV4Ip() { + try { + InetAddress localHost = InetAddress.getLocalHost(); + String localIp = localHost.getHostAddress(); + if (validationIpV4FormatAddress(localIp)) { + return localIp; + } + } catch (UnknownHostException ignore) { // skip - } - return LOOPBACK_ADDRESS_V4; - } - - /** - * Returns a list of ip addreses on this machine that is accessible from a remote source. - * If no network interfaces can be found on this machine, returns an empty List. - */ - public static List getLocalV4IpList() { - List result = new ArrayList(); - - Enumeration interfaces = null; - try { - interfaces = NetworkInterface.getNetworkInterfaces(); - } catch (SocketException ignore) { + } + return LOOPBACK_ADDRESS_V4; + } + + /** + * Returns a list of ip addreses on this machine that is accessible from a remote source. + * If no network interfaces can be found on this machine, returns an empty List. + */ + public static List getLocalV4IpList() { + List result = new ArrayList(); + + Enumeration interfaces = null; + try { + interfaces = NetworkInterface.getNetworkInterfaces(); + } catch (SocketException ignore) { // skip - } + } - if (interfaces == null) { - return Collections.EMPTY_LIST; - } - - while (interfaces.hasMoreElements()) { - NetworkInterface current = interfaces.nextElement(); - if (isSkipIp(current)) { - continue; - } + if (interfaces == null) { + return Collections.EMPTY_LIST; + } - Enumeration addresses = current.getInetAddresses(); - while (addresses.hasMoreElements()) { - InetAddress address = addresses.nextElement(); - if (address.isLoopbackAddress() || !(address instanceof Inet4Address)) { - continue; - } - - if (validationIpV4FormatAddress(address.getHostAddress())) { - result.add(address.getHostAddress()); - } - } - } + while (interfaces.hasMoreElements()) { + NetworkInterface current = interfaces.nextElement(); + if (isSkipIp(current)) { + continue; + } - return result; - } - - private static boolean isSkipIp(NetworkInterface networkInterface) { - try { - if (!networkInterface.isUp() || networkInterface.isLoopback() || networkInterface.isVirtual()) { - return true; - } - return false; - } catch (Exception ignore) { + Enumeration addresses = current.getInetAddresses(); + while (addresses.hasMoreElements()) { + InetAddress address = addresses.nextElement(); + if (address.isLoopbackAddress() || !(address instanceof Inet4Address)) { + continue; + } + + if (validationIpV4FormatAddress(address.getHostAddress())) { + result.add(address.getHostAddress()); + } + } + } + + return result; + } + + private static boolean isSkipIp(NetworkInterface networkInterface) { + try { + if (!networkInterface.isUp() || networkInterface.isLoopback() || networkInterface.isVirtual()) { + return true; + } + return false; + } catch (Exception ignore) { // skip - } - return true; - } - + } + return true; + } - public static boolean validationIpPortV4FormatAddress(String address) { - try { - int splitIndex = address.indexOf(':'); - if (splitIndex == -1 || splitIndex + 1 >= address.length()) { - return false; - } + public static boolean validationIpPortV4FormatAddress(String address) { + try { + int splitIndex = address.indexOf(':'); - String ip = address.substring(0, splitIndex); - - if (!validationIpV4FormatAddress(ip)) { - return false; - } + if (splitIndex == -1 || splitIndex + 1 >= address.length()) { + return false; + } - String port = address.substring(splitIndex + 1, address.length()); - if (Integer.parseInt(port) > 65535) { - return false; - } + String ip = address.substring(0, splitIndex); - return true; - } catch (Exception ignore) { + if (!validationIpV4FormatAddress(ip)) { + return false; + } + + String port = address.substring(splitIndex + 1, address.length()); + if (Integer.parseInt(port) > 65535) { + return false; + } + + return true; + } catch (Exception ignore) { //skip - } + } - return false; - } - - public static boolean validationIpV4FormatAddress(String address) { - try { - String[] eachDotAddress = address.split("\\."); - if (eachDotAddress.length != 4) { - return false; - } + return false; + } - for (String eachAddress : eachDotAddress) { - if (Integer.parseInt(eachAddress) > 255) { - return false; - } - } - return true; - } catch (NumberFormatException ignore) { + public static boolean validationIpV4FormatAddress(String address) { + try { + String[] eachDotAddress = address.split("\\."); + if (eachDotAddress.length != 4) { + return false; + } + + for (String eachAddress : eachDotAddress) { + if (Integer.parseInt(eachAddress) > 255) { + return false; + } + } + return true; + } catch (NumberFormatException ignore) { // skip - } + } - return false; - } + return false; + } } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/NextElementAction.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/NextElementAction.java index 522afa5e6..01157a54a 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/NextElementAction.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/NextElementAction.java @@ -20,5 +20,5 @@ package com.navercorp.pinpoint.common.util; * @author emeroad */ public interface NextElementAction { - E nextElement(); + E nextElement(); } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/NoSuchElementExceptionAction.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/NoSuchElementExceptionAction.java index a6d6588a9..7f5bd3616 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/NoSuchElementExceptionAction.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/NoSuchElementExceptionAction.java @@ -23,8 +23,8 @@ import java.util.NoSuchElementException; */ public class NoSuchElementExceptionAction implements NextElementAction { - @Override - public E nextElement() { - throw new NoSuchElementException(); - } + @Override + public E nextElement() { + throw new NoSuchElementException(); + } } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/NullNextElementAction.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/NullNextElementAction.java index fecb0df09..e0cc77773 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/NullNextElementAction.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/NullNextElementAction.java @@ -21,8 +21,8 @@ package com.navercorp.pinpoint.common.util; */ public class NullNextElementAction implements NextElementAction { - @Override - public E nextElement() { - return null; - } + @Override + public E nextElement() { + return null; + } } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/SpanUtils.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/SpanUtils.java index d5d7aa46b..760bddabf 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/SpanUtils.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/SpanUtils.java @@ -31,28 +31,28 @@ public final class SpanUtils { } @Deprecated - public static byte[] getAgentIdTraceIndexRowKey(String agentId, long timestamp) { - if (agentId == null) { - throw new IllegalArgumentException("agentId must not null"); - } - final byte[] bAgentId = BytesUtils.toBytes(agentId); - return RowKeyUtils.concatFixedByteAndLong(bAgentId, AGENT_NAME_MAX_LEN, TimeUtils.reverseTimeMillis(timestamp)); - } + public static byte[] getAgentIdTraceIndexRowKey(String agentId, long timestamp) { + if (agentId == null) { + throw new IllegalArgumentException("agentId must not null"); + } + final byte[] bAgentId = BytesUtils.toBytes(agentId); + return RowKeyUtils.concatFixedByteAndLong(bAgentId, AGENT_NAME_MAX_LEN, TimeUtils.reverseTimeMillis(timestamp)); + } - public static byte[] getApplicationTraceIndexRowKey(String applicationName, long timestamp) { - if (applicationName == null) { - throw new IllegalArgumentException("agentId must not null"); - } - final byte[] bApplicationName = BytesUtils.toBytes(applicationName); - return RowKeyUtils.concatFixedByteAndLong(bApplicationName, AGENT_NAME_MAX_LEN, TimeUtils.reverseTimeMillis(timestamp)); - } - - public static byte[] getTraceIndexRowKey(byte[] agentId, long timestamp) { + public static byte[] getApplicationTraceIndexRowKey(String applicationName, long timestamp) { + if (applicationName == null) { + throw new IllegalArgumentException("agentId must not null"); + } + final byte[] bApplicationName = BytesUtils.toBytes(applicationName); + return RowKeyUtils.concatFixedByteAndLong(bApplicationName, AGENT_NAME_MAX_LEN, TimeUtils.reverseTimeMillis(timestamp)); + } + + public static byte[] getTraceIndexRowKey(byte[] agentId, long timestamp) { if (agentId == null) { throw new NullPointerException("agentId must not be null"); } return RowKeyUtils.concatFixedByteAndLong(agentId, AGENT_NAME_MAX_LEN, TimeUtils.reverseTimeMillis(timestamp)); - } + } public static byte[] getVarTransactionId(TSpan span) { if (span == null) { @@ -72,7 +72,7 @@ public final class SpanUtils { return buffer.getBuffer(); } - public static byte[] getTransactionId(TSpan span) { + public static byte[] getTransactionId(TSpan span) { if (span == null) { throw new NullPointerException("span must not be null"); } @@ -84,9 +84,9 @@ public final class SpanUtils { } return BytesUtils.stringLongLongToBytes(agentId, AGENT_NAME_MAX_LEN, transactionId.getAgentStartTime(), transactionId.getTransactionSequence()); - } + } - public static byte[] getTransactionId(TSpanChunk spanChunk) { + public static byte[] getTransactionId(TSpanChunk spanChunk) { if (spanChunk == null) { throw new NullPointerException("spanChunk must not be null"); } @@ -97,5 +97,5 @@ public final class SpanUtils { agentId = spanChunk.getAgentId(); } return BytesUtils.stringLongLongToBytes(agentId, AGENT_NAME_MAX_LEN, transactionId.getAgentStartTime(), transactionId.getTransactionSequence()); - } + } } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/SystemPropertyKey.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/SystemPropertyKey.java index 3a3ab3685..785b3ca84 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/SystemPropertyKey.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/SystemPropertyKey.java @@ -20,24 +20,24 @@ package com.navercorp.pinpoint.common.util; * @author hyungil.jeong */ public enum SystemPropertyKey { - - JAVA_VERSION("java.version"), - JAVA_RUNTIME_VERSION("java.runtime.version"), - JAVA_RUNTIME_NAME("java.runtime.name"), - JAVA_SPECIFICATION_VERSION("java.specification.version"), - JAVA_CLASS_VERSION("java.class.version"), - JAVA_VM_NAME("java.vm.name"), - JAVA_VM_VERSION("java.vm.version"), - JAVA_VM_INFO("java.vm.info"), - JAVA_VM_SPECIFICATION_VERSION("java.vm.specification.version"); - - private final String key; - - private SystemPropertyKey(String key) { - this.key = key; - } - - public String getKey() { - return this.key; - } + + JAVA_VERSION("java.version"), + JAVA_RUNTIME_VERSION("java.runtime.version"), + JAVA_RUNTIME_NAME("java.runtime.name"), + JAVA_SPECIFICATION_VERSION("java.specification.version"), + JAVA_CLASS_VERSION("java.class.version"), + JAVA_VM_NAME("java.vm.name"), + JAVA_VM_VERSION("java.vm.version"), + JAVA_VM_INFO("java.vm.info"), + JAVA_VM_SPECIFICATION_VERSION("java.vm.specification.version"); + + private final String key; + + private SystemPropertyKey(String key) { + this.key = key; + } + + public String getKey() { + return this.key; + } } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/TransactionIdUtils.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/TransactionIdUtils.java index 04c1e467c..9c97f1b24 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/TransactionIdUtils.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/TransactionIdUtils.java @@ -102,14 +102,14 @@ public final class TransactionIdUtils { return new TransactionId(agentId, agentStartTime, transactionSequence); } - private static int nextIndex(String transactionId, int fromIndex) { - return transactionId.indexOf(TRANSACTION_ID_DELIMITER, fromIndex); - } + private static int nextIndex(String transactionId, int fromIndex) { + return transactionId.indexOf(TRANSACTION_ID_DELIMITER, fromIndex); + } - private static long parseLong(String transactionId, int beginIndex, int endIndex) { - final String longString = transactionId.substring(beginIndex, endIndex); + private static long parseLong(String transactionId, int beginIndex, int endIndex) { + final String longString = transactionId.substring(beginIndex, endIndex); try { - return Long.parseLong(longString); + return Long.parseLong(longString); } catch (NumberFormatException e) { throw new IllegalArgumentException("parseLong Error. " + longString + " transactionId:" + transactionId); } diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/ServiceTypeTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/ServiceTypeTest.java index ad50e18f5..5106315b0 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/ServiceTypeTest.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/ServiceTypeTest.java @@ -31,11 +31,11 @@ public class ServiceTypeTest { @Test - public void testIndexable() { - logger.debug("{}", ServiceType.TOMCAT.isIndexable()); + public void testIndexable() { + logger.debug("{}", ServiceType.TOMCAT.isIndexable()); logger.debug("{}", ServiceType.BLOC.isIndexable()); logger.debug("{}", ServiceType.ARCUS.isIndexable()); - } + } @Test public void findDesc() { diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/bo/AgentStatCpuLoadBoTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/bo/AgentStatCpuLoadBoTest.java index 0ffadcd1c..8c87bbe37 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/bo/AgentStatCpuLoadBoTest.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/bo/AgentStatCpuLoadBoTest.java @@ -26,75 +26,75 @@ import com.navercorp.pinpoint.common.bo.AgentStatCpuLoadBo; * @author hyungil.jeong */ public class AgentStatCpuLoadBoTest { - - // for comparing CPU Usage up to 2 decimal places - private static final double DELTA = 1e-4; - @Test - public void testByteArrayConversion() { - // Given - final AgentStatCpuLoadBo testBo = createTestBo(0.22871734201908112D, 0.23790152370929718D); - // When - final byte[] serializedBo = testBo.writeValue(); - final AgentStatCpuLoadBo deserializedBo = new AgentStatCpuLoadBo.Builder(serializedBo).build(); - // Then - assertEquals(testBo.getAgentId(), deserializedBo.getAgentId()); - assertEquals(testBo.getStartTimestamp(), deserializedBo.getStartTimestamp()); - assertEquals(testBo.getTimestamp(), deserializedBo.getTimestamp()); - assertEquals(testBo.getJvmCpuLoad(), deserializedBo.getJvmCpuLoad(), DELTA); - assertEquals(testBo.getSystemCpuLoad(), deserializedBo.getSystemCpuLoad(), DELTA); - } + // for comparing CPU Usage up to 2 decimal places + private static final double DELTA = 1e-4; - @Test - public void testByteArrayConversionEdges() { - // Given - final AgentStatCpuLoadBo testBo = createTestBo(Double.MIN_VALUE, Double.MAX_VALUE); - // When - final byte[] serializedBo = testBo.writeValue(); - final AgentStatCpuLoadBo deserializedBo = new AgentStatCpuLoadBo.Builder(serializedBo).build(); - // Then - assertEquals(testBo.getAgentId(), deserializedBo.getAgentId()); - assertEquals(testBo.getStartTimestamp(), deserializedBo.getStartTimestamp()); - assertEquals(testBo.getTimestamp(), deserializedBo.getTimestamp()); - assertEquals(testBo.getJvmCpuLoad(), deserializedBo.getJvmCpuLoad(), DELTA); - assertEquals(testBo.getSystemCpuLoad(), deserializedBo.getSystemCpuLoad(), DELTA); - } + @Test + public void testByteArrayConversion() { + // Given + final AgentStatCpuLoadBo testBo = createTestBo(0.22871734201908112D, 0.23790152370929718D); + // When + final byte[] serializedBo = testBo.writeValue(); + final AgentStatCpuLoadBo deserializedBo = new AgentStatCpuLoadBo.Builder(serializedBo).build(); + // Then + assertEquals(testBo.getAgentId(), deserializedBo.getAgentId()); + assertEquals(testBo.getStartTimestamp(), deserializedBo.getStartTimestamp()); + assertEquals(testBo.getTimestamp(), deserializedBo.getTimestamp()); + assertEquals(testBo.getJvmCpuLoad(), deserializedBo.getJvmCpuLoad(), DELTA); + assertEquals(testBo.getSystemCpuLoad(), deserializedBo.getSystemCpuLoad(), DELTA); + } - @Test - public void testByteArrayConversionNanValues() { - // Given - final AgentStatCpuLoadBo testBo = createTestBo(Double.NaN, Double.NaN); - // When - final byte[] serializedBo = testBo.writeValue(); - final AgentStatCpuLoadBo deserializedBo = new AgentStatCpuLoadBo.Builder(serializedBo).build(); - // Then - assertEquals(testBo.getAgentId(), deserializedBo.getAgentId()); - assertEquals(testBo.getStartTimestamp(), deserializedBo.getStartTimestamp()); - assertEquals(testBo.getTimestamp(), deserializedBo.getTimestamp()); - assertEquals(testBo.getJvmCpuLoad(), deserializedBo.getJvmCpuLoad(), DELTA); - assertEquals(testBo.getSystemCpuLoad(), deserializedBo.getSystemCpuLoad(), DELTA); - } + @Test + public void testByteArrayConversionEdges() { + // Given + final AgentStatCpuLoadBo testBo = createTestBo(Double.MIN_VALUE, Double.MAX_VALUE); + // When + final byte[] serializedBo = testBo.writeValue(); + final AgentStatCpuLoadBo deserializedBo = new AgentStatCpuLoadBo.Builder(serializedBo).build(); + // Then + assertEquals(testBo.getAgentId(), deserializedBo.getAgentId()); + assertEquals(testBo.getStartTimestamp(), deserializedBo.getStartTimestamp()); + assertEquals(testBo.getTimestamp(), deserializedBo.getTimestamp()); + assertEquals(testBo.getJvmCpuLoad(), deserializedBo.getJvmCpuLoad(), DELTA); + assertEquals(testBo.getSystemCpuLoad(), deserializedBo.getSystemCpuLoad(), DELTA); + } - @Test - public void testByteArrayConversionInfiniteValues() { - // Given - final AgentStatCpuLoadBo testBo = createTestBo(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY); - // When - final byte[] serializedBo = testBo.writeValue(); - final AgentStatCpuLoadBo deserializedBo = new AgentStatCpuLoadBo.Builder(serializedBo).build(); - // Then - assertEquals(testBo.getAgentId(), deserializedBo.getAgentId()); - assertEquals(testBo.getStartTimestamp(), deserializedBo.getStartTimestamp()); - assertEquals(testBo.getTimestamp(), deserializedBo.getTimestamp()); - assertEquals(testBo.getJvmCpuLoad(), deserializedBo.getJvmCpuLoad(), DELTA); - assertEquals(testBo.getSystemCpuLoad(), deserializedBo.getSystemCpuLoad(), DELTA); - } - - private AgentStatCpuLoadBo createTestBo(double jvmCpuLoad, double systemCpuLoad) { - final AgentStatCpuLoadBo.Builder builder = new AgentStatCpuLoadBo.Builder("agentId", 0L, 0L); - builder.jvmCpuLoad(jvmCpuLoad); - builder.systemCpuLoad(systemCpuLoad); - return builder.build(); - } + @Test + public void testByteArrayConversionNanValues() { + // Given + final AgentStatCpuLoadBo testBo = createTestBo(Double.NaN, Double.NaN); + // When + final byte[] serializedBo = testBo.writeValue(); + final AgentStatCpuLoadBo deserializedBo = new AgentStatCpuLoadBo.Builder(serializedBo).build(); + // Then + assertEquals(testBo.getAgentId(), deserializedBo.getAgentId()); + assertEquals(testBo.getStartTimestamp(), deserializedBo.getStartTimestamp()); + assertEquals(testBo.getTimestamp(), deserializedBo.getTimestamp()); + assertEquals(testBo.getJvmCpuLoad(), deserializedBo.getJvmCpuLoad(), DELTA); + assertEquals(testBo.getSystemCpuLoad(), deserializedBo.getSystemCpuLoad(), DELTA); + } + + @Test + public void testByteArrayConversionInfiniteValues() { + // Given + final AgentStatCpuLoadBo testBo = createTestBo(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY); + // When + final byte[] serializedBo = testBo.writeValue(); + final AgentStatCpuLoadBo deserializedBo = new AgentStatCpuLoadBo.Builder(serializedBo).build(); + // Then + assertEquals(testBo.getAgentId(), deserializedBo.getAgentId()); + assertEquals(testBo.getStartTimestamp(), deserializedBo.getStartTimestamp()); + assertEquals(testBo.getTimestamp(), deserializedBo.getTimestamp()); + assertEquals(testBo.getJvmCpuLoad(), deserializedBo.getJvmCpuLoad(), DELTA); + assertEquals(testBo.getSystemCpuLoad(), deserializedBo.getSystemCpuLoad(), DELTA); + } + + private AgentStatCpuLoadBo createTestBo(double jvmCpuLoad, double systemCpuLoad) { + final AgentStatCpuLoadBo.Builder builder = new AgentStatCpuLoadBo.Builder("agentId", 0L, 0L); + builder.jvmCpuLoad(jvmCpuLoad); + builder.systemCpuLoad(systemCpuLoad); + return builder.build(); + } } diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/bo/AgentStatMemoryGcBoTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/bo/AgentStatMemoryGcBoTest.java index 30e5e30a3..9043befb1 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/bo/AgentStatMemoryGcBoTest.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/bo/AgentStatMemoryGcBoTest.java @@ -28,32 +28,32 @@ import com.navercorp.pinpoint.thrift.dto.TJvmGcType; */ public class AgentStatMemoryGcBoTest { - @Test - public void testByteArrayConversion() { - // Given - final AgentStatMemoryGcBo.Builder builder = new AgentStatMemoryGcBo.Builder("agentId", 0L, 1L); - builder.gcType(TJvmGcType.G1.name()); - builder.jvmMemoryHeapUsed(Long.MIN_VALUE); - builder.jvmMemoryHeapMax(Long.MAX_VALUE); - builder.jvmMemoryNonHeapUsed(Long.MIN_VALUE); - builder.jvmMemoryNonHeapMax(Long.MAX_VALUE); - builder.jvmGcOldCount(1L); - builder.jvmGcOldTime(2L); - final AgentStatMemoryGcBo testBo = builder.build(); - // When - final byte[] serializedBo = testBo.writeValue(); - final AgentStatMemoryGcBo deserializedBo = new AgentStatMemoryGcBo.Builder(serializedBo).build(); - // Then - assertEquals(testBo.getAgentId(), deserializedBo.getAgentId()); - assertEquals(testBo.getStartTimestamp(), deserializedBo.getStartTimestamp()); - assertEquals(testBo.getTimestamp(), deserializedBo.getTimestamp()); - assertEquals(testBo.getGcType(), deserializedBo.getGcType()); - assertEquals(testBo.getJvmMemoryHeapUsed(), deserializedBo.getJvmMemoryHeapUsed()); - assertEquals(testBo.getJvmMemoryHeapMax(), deserializedBo.getJvmMemoryHeapMax()); - assertEquals(testBo.getJvmMemoryNonHeapUsed(), deserializedBo.getJvmMemoryNonHeapUsed()); - assertEquals(testBo.getJvmMemoryNonHeapMax(), deserializedBo.getJvmMemoryNonHeapMax()); - assertEquals(testBo.getJvmGcOldCount(), deserializedBo.getJvmGcOldCount()); - assertEquals(testBo.getJvmGcOldTime(), deserializedBo.getJvmGcOldTime()); - } + @Test + public void testByteArrayConversion() { + // Given + final AgentStatMemoryGcBo.Builder builder = new AgentStatMemoryGcBo.Builder("agentId", 0L, 1L); + builder.gcType(TJvmGcType.G1.name()); + builder.jvmMemoryHeapUsed(Long.MIN_VALUE); + builder.jvmMemoryHeapMax(Long.MAX_VALUE); + builder.jvmMemoryNonHeapUsed(Long.MIN_VALUE); + builder.jvmMemoryNonHeapMax(Long.MAX_VALUE); + builder.jvmGcOldCount(1L); + builder.jvmGcOldTime(2L); + final AgentStatMemoryGcBo testBo = builder.build(); + // When + final byte[] serializedBo = testBo.writeValue(); + final AgentStatMemoryGcBo deserializedBo = new AgentStatMemoryGcBo.Builder(serializedBo).build(); + // Then + assertEquals(testBo.getAgentId(), deserializedBo.getAgentId()); + assertEquals(testBo.getStartTimestamp(), deserializedBo.getStartTimestamp()); + assertEquals(testBo.getTimestamp(), deserializedBo.getTimestamp()); + assertEquals(testBo.getGcType(), deserializedBo.getGcType()); + assertEquals(testBo.getJvmMemoryHeapUsed(), deserializedBo.getJvmMemoryHeapUsed()); + assertEquals(testBo.getJvmMemoryHeapMax(), deserializedBo.getJvmMemoryHeapMax()); + assertEquals(testBo.getJvmMemoryNonHeapUsed(), deserializedBo.getJvmMemoryNonHeapUsed()); + assertEquals(testBo.getJvmMemoryNonHeapMax(), deserializedBo.getJvmMemoryNonHeapMax()); + assertEquals(testBo.getJvmGcOldCount(), deserializedBo.getJvmGcOldCount()); + assertEquals(testBo.getJvmGcOldTime(), deserializedBo.getJvmGcOldTime()); + } } diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/buffer/AutomaticBufferTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/buffer/AutomaticBufferTest.java index 568dfee5c..4ce0e0c47 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/buffer/AutomaticBufferTest.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/buffer/AutomaticBufferTest.java @@ -296,7 +296,7 @@ public class AutomaticBufferTest { public void testUdp() throws Exception { // Signature:Header{signature=85, version=100, type=28704} Buffer buffer = new AutomaticBuffer(10); - // l4 Udp check payload + // l4 Udp check payload buffer.put((byte)85); buffer.put((byte) 100); buffer.put((short)28704); diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/util/DelegateEnumerationTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/util/DelegateEnumerationTest.java index eaf532f3e..1de9cfeb9 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/util/DelegateEnumerationTest.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/util/DelegateEnumerationTest.java @@ -27,189 +27,189 @@ import java.util.*; public class DelegateEnumerationTest { - @Test - public void testNormal() throws Exception { - Hashtable hashTable = new Hashtable(); - hashTable.put("a", "aa"); - hashTable.put("b", "bb"); - hashTable.put("c", "cc"); + @Test + public void testNormal() throws Exception { + Hashtable hashTable = new Hashtable(); + hashTable.put("a", "aa"); + hashTable.put("b", "bb"); + hashTable.put("c", "cc"); - List valueList = new ArrayList(hashTable.values()); + List valueList = new ArrayList(hashTable.values()); - Enumeration enumeration = hashTable.elements(); - DelegateEnumeration delegateEnumeration = new DelegateEnumeration(enumeration); + Enumeration enumeration = hashTable.elements(); + DelegateEnumeration delegateEnumeration = new DelegateEnumeration(enumeration); - Assert.assertTrue(delegateEnumeration.hasMoreElements()); - Assert.assertTrue(valueList.remove(delegateEnumeration.nextElement())); + Assert.assertTrue(delegateEnumeration.hasMoreElements()); + Assert.assertTrue(valueList.remove(delegateEnumeration.nextElement())); - Assert.assertTrue(delegateEnumeration.hasMoreElements()); - Assert.assertTrue(valueList.remove(delegateEnumeration.nextElement())); + Assert.assertTrue(delegateEnumeration.hasMoreElements()); + Assert.assertTrue(valueList.remove(delegateEnumeration.nextElement())); - Assert.assertTrue(delegateEnumeration.hasMoreElements()); - Assert.assertTrue(valueList.remove(delegateEnumeration.nextElement())); + Assert.assertTrue(delegateEnumeration.hasMoreElements()); + Assert.assertTrue(valueList.remove(delegateEnumeration.nextElement())); - Assert.assertTrue(valueList.isEmpty()); + Assert.assertTrue(valueList.isEmpty()); - Assert.assertFalse(delegateEnumeration.hasMoreElements()); - assertNextElements_Expected_ExceptionEmulation(enumeration, delegateEnumeration); - } + Assert.assertFalse(delegateEnumeration.hasMoreElements()); + assertNextElements_Expected_ExceptionEmulation(enumeration, delegateEnumeration); + } - @Test - public void testSkip() throws Exception { - Hashtable hashTable = new Hashtable(); - hashTable.put("a", "aa"); - hashTable.put("b", "bb"); - hashTable.put("c", "cc"); + @Test + public void testSkip() throws Exception { + Hashtable hashTable = new Hashtable(); + hashTable.put("a", "aa"); + hashTable.put("b", "bb"); + hashTable.put("c", "cc"); - List valueList = new ArrayList(hashTable.values()); + List valueList = new ArrayList(hashTable.values()); - Enumeration enumeration = hashTable.elements(); - DelegateEnumeration delegateEnumeration = new DelegateEnumeration(enumeration, new DelegateEnumeration.Filter() { - @Override - public boolean filter(String s) { - if ("bb".equals(s)) { - return true; - } - return false; - } - }); + Enumeration enumeration = hashTable.elements(); + DelegateEnumeration delegateEnumeration = new DelegateEnumeration(enumeration, new DelegateEnumeration.Filter() { + @Override + public boolean filter(String s) { + if ("bb".equals(s)) { + return true; + } + return false; + } + }); - Assert.assertTrue(delegateEnumeration.hasMoreElements()); - Assert.assertTrue(valueList.remove(delegateEnumeration.nextElement())); + Assert.assertTrue(delegateEnumeration.hasMoreElements()); + Assert.assertTrue(valueList.remove(delegateEnumeration.nextElement())); - Assert.assertTrue(delegateEnumeration.hasMoreElements()); - Assert.assertTrue(valueList.remove(delegateEnumeration.nextElement())); + Assert.assertTrue(delegateEnumeration.hasMoreElements()); + Assert.assertTrue(valueList.remove(delegateEnumeration.nextElement())); - Assert.assertEquals(valueList.size(), 1); + Assert.assertEquals(valueList.size(), 1); - Assert.assertFalse(delegateEnumeration.hasMoreElements()); - assertNextElements_Expected_ExceptionEmulation(enumeration, delegateEnumeration); - Assert.assertEquals(valueList.size(), 1); + Assert.assertFalse(delegateEnumeration.hasMoreElements()); + assertNextElements_Expected_ExceptionEmulation(enumeration, delegateEnumeration); + Assert.assertEquals(valueList.size(), 1); - Assert.assertEquals(valueList.get(0), "bb"); - } + Assert.assertEquals(valueList.get(0), "bb"); + } - @Test - public void testExceptionTest_Exception() throws Exception { - Hashtable hashTable = new Hashtable(); + @Test + public void testExceptionTest_Exception() throws Exception { + Hashtable hashTable = new Hashtable(); - Enumeration enumeration = hashTable.elements(); - DelegateEnumeration delegateEnumeration = new DelegateEnumeration(enumeration); + Enumeration enumeration = hashTable.elements(); + DelegateEnumeration delegateEnumeration = new DelegateEnumeration(enumeration); - Assert.assertFalse(delegateEnumeration.hasMoreElements()); - Assert.assertFalse(delegateEnumeration.hasMoreElements()); - Assert.assertFalse(delegateEnumeration.hasMoreElements()); + Assert.assertFalse(delegateEnumeration.hasMoreElements()); + Assert.assertFalse(delegateEnumeration.hasMoreElements()); + Assert.assertFalse(delegateEnumeration.hasMoreElements()); - assertNextElements_Expected_ExceptionEmulation(enumeration, delegateEnumeration); - Assert.assertFalse(delegateEnumeration.hasMoreElements()); + assertNextElements_Expected_ExceptionEmulation(enumeration, delegateEnumeration); + Assert.assertFalse(delegateEnumeration.hasMoreElements()); - assertNextElements_Expected_ExceptionEmulation(enumeration, delegateEnumeration); - assertNextElements_Expected_ExceptionEmulation(enumeration, delegateEnumeration); - Assert.assertFalse(delegateEnumeration.hasMoreElements()); - } + assertNextElements_Expected_ExceptionEmulation(enumeration, delegateEnumeration); + assertNextElements_Expected_ExceptionEmulation(enumeration, delegateEnumeration); + Assert.assertFalse(delegateEnumeration.hasMoreElements()); + } - @Test - public void testExceptionTest_Exception2() throws Exception { + @Test + public void testExceptionTest_Exception2() throws Exception { - Enumeration enumeration = mock(Enumeration.class); + Enumeration enumeration = mock(Enumeration.class); - when(enumeration.hasMoreElements()).thenReturn(false); - when(enumeration.nextElement()).thenThrow(new NoSuchElementException()); + when(enumeration.hasMoreElements()).thenReturn(false); + when(enumeration.nextElement()).thenThrow(new NoSuchElementException()); - DelegateEnumeration delegateEnumeration = new DelegateEnumeration(enumeration); + DelegateEnumeration delegateEnumeration = new DelegateEnumeration(enumeration); - Assert.assertEquals(enumeration.hasMoreElements(), delegateEnumeration.hasMoreElements()); - Assert.assertEquals(enumeration.hasMoreElements(), delegateEnumeration.hasMoreElements()); + Assert.assertEquals(enumeration.hasMoreElements(), delegateEnumeration.hasMoreElements()); + Assert.assertEquals(enumeration.hasMoreElements(), delegateEnumeration.hasMoreElements()); - assertNextElements_Expected_ExceptionEmulation(enumeration, delegateEnumeration); - Assert.assertEquals(enumeration.hasMoreElements(), delegateEnumeration.hasMoreElements()); + assertNextElements_Expected_ExceptionEmulation(enumeration, delegateEnumeration); + Assert.assertEquals(enumeration.hasMoreElements(), delegateEnumeration.hasMoreElements()); - assertNextElements_Expected_ExceptionEmulation(enumeration, delegateEnumeration); - assertNextElements_Expected_ExceptionEmulation(enumeration, delegateEnumeration); - Assert.assertEquals(enumeration.hasMoreElements(), delegateEnumeration.hasMoreElements()); - } + assertNextElements_Expected_ExceptionEmulation(enumeration, delegateEnumeration); + assertNextElements_Expected_ExceptionEmulation(enumeration, delegateEnumeration); + Assert.assertEquals(enumeration.hasMoreElements(), delegateEnumeration.hasMoreElements()); + } - @Test - public void testExceptionTest_Null() throws Exception { - Enumeration enumeration = mock(Enumeration.class); + @Test + public void testExceptionTest_Null() throws Exception { + Enumeration enumeration = mock(Enumeration.class); - when(enumeration.hasMoreElements()).thenReturn(false); - when(enumeration.nextElement()).thenReturn(null); + when(enumeration.hasMoreElements()).thenReturn(false); + when(enumeration.nextElement()).thenReturn(null); - DelegateEnumeration delegateEnumeration = new DelegateEnumeration(enumeration); + DelegateEnumeration delegateEnumeration = new DelegateEnumeration(enumeration); - Assert.assertFalse(delegateEnumeration.hasMoreElements()); - Assert.assertFalse(delegateEnumeration.hasMoreElements()); + Assert.assertFalse(delegateEnumeration.hasMoreElements()); + Assert.assertFalse(delegateEnumeration.hasMoreElements()); - Assert.assertSame(delegateEnumeration.nextElement(), null); - Assert.assertSame(delegateEnumeration.nextElement(), null); - Assert.assertFalse(delegateEnumeration.hasMoreElements()); + Assert.assertSame(delegateEnumeration.nextElement(), null); + Assert.assertSame(delegateEnumeration.nextElement(), null); + Assert.assertFalse(delegateEnumeration.hasMoreElements()); - } + } - @Test - public void testExceptionTest_Null2() throws Exception { - Enumeration enumeration = new Enumeration() { - private boolean first = true; - @Override - public boolean hasMoreElements() { - return first; - } + @Test + public void testExceptionTest_Null2() throws Exception { + Enumeration enumeration = new Enumeration() { + private boolean first = true; + @Override + public boolean hasMoreElements() { + return first; + } - @Override - public String nextElement() { - if (first) { - first = false; - return "exist"; - } - return null; - } - }; + @Override + public String nextElement() { + if (first) { + first = false; + return "exist"; + } + return null; + } + }; - DelegateEnumeration delegateEnumeration = new DelegateEnumeration(enumeration); + DelegateEnumeration delegateEnumeration = new DelegateEnumeration(enumeration); - Assert.assertTrue(delegateEnumeration.hasMoreElements()); - Assert.assertTrue(delegateEnumeration.hasMoreElements()); + Assert.assertTrue(delegateEnumeration.hasMoreElements()); + Assert.assertTrue(delegateEnumeration.hasMoreElements()); - Assert.assertSame(delegateEnumeration.nextElement(), "exist"); - Assert.assertFalse(delegateEnumeration.hasMoreElements()); + Assert.assertSame(delegateEnumeration.nextElement(), "exist"); + Assert.assertFalse(delegateEnumeration.hasMoreElements()); - Assert.assertSame(delegateEnumeration.nextElement(), null); - Assert.assertSame(delegateEnumeration.nextElement(), null); - Assert.assertFalse(delegateEnumeration.hasMoreElements()); + Assert.assertSame(delegateEnumeration.nextElement(), null); + Assert.assertSame(delegateEnumeration.nextElement(), null); + Assert.assertFalse(delegateEnumeration.hasMoreElements()); - } + } - private void assertNextElements_Expected_ExceptionEmulation(Enumeration elements, DelegateEnumeration delegateEnumeration) { - Exception original = getException(elements); - Assert.assertNotSame(original, null); + private void assertNextElements_Expected_ExceptionEmulation(Enumeration elements, DelegateEnumeration delegateEnumeration) { + Exception original = getException(elements); + Assert.assertNotSame(original, null); - Exception delegate = getException(delegateEnumeration); - Assert.assertNotSame(delegate, null); + Exception delegate = getException(delegateEnumeration); + Assert.assertNotSame(delegate, null); - Assert.assertEquals(original.getClass(), delegate.getClass()); - Assert.assertEquals(original.getMessage(), delegate.getMessage()); - Assert.assertEquals(original.getCause(), delegate.getCause()); - } + Assert.assertEquals(original.getClass(), delegate.getClass()); + Assert.assertEquals(original.getMessage(), delegate.getMessage()); + Assert.assertEquals(original.getCause(), delegate.getCause()); + } - private Exception getException(Enumeration elements) { - try { - elements.nextElement(); - } catch (Exception e) { - return e; - } - Assert.fail("NoSuchElementException"); - return null; - } + private Exception getException(Enumeration elements) { + try { + elements.nextElement(); + } catch (Exception e) { + return e; + } + Assert.fail("NoSuchElementException"); + return null; + } } \ No newline at end of file diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/util/JvmVersionTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/util/JvmVersionTest.java index 44850d246..cb66ffc81 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/util/JvmVersionTest.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/util/JvmVersionTest.java @@ -28,94 +28,94 @@ import com.navercorp.pinpoint.common.util.JvmVersion; */ public class JvmVersionTest { - @Test - public void testOnOrAfter() { - // JDK 5 - assertTrue(JAVA_5.onOrAfter(JAVA_5)); - assertFalse(JAVA_5.onOrAfter(JAVA_6)); - assertFalse(JAVA_5.onOrAfter(JAVA_7)); - assertFalse(JAVA_5.onOrAfter(JAVA_8)); - assertFalse(JAVA_5.onOrAfter(UNSUPPORTED)); - // JDK 6 - assertTrue(JAVA_6.onOrAfter(JAVA_5)); - assertTrue(JAVA_6.onOrAfter(JAVA_6)); - assertFalse(JAVA_6.onOrAfter(JAVA_7)); - assertFalse(JAVA_6.onOrAfter(JAVA_8)); - assertFalse(JAVA_6.onOrAfter(UNSUPPORTED)); - // JDK 7 - assertTrue(JAVA_7.onOrAfter(JAVA_5)); - assertTrue(JAVA_7.onOrAfter(JAVA_6)); - assertTrue(JAVA_7.onOrAfter(JAVA_7)); - assertFalse(JAVA_7.onOrAfter(JAVA_8)); - assertFalse(JAVA_7.onOrAfter(UNSUPPORTED)); - // JDK 8 - assertTrue(JAVA_8.onOrAfter(JAVA_5)); - assertTrue(JAVA_8.onOrAfter(JAVA_6)); - assertTrue(JAVA_8.onOrAfter(JAVA_7)); - assertTrue(JAVA_8.onOrAfter(JAVA_8)); - assertFalse(JAVA_8.onOrAfter(UNSUPPORTED)); - // Unsupported - assertFalse(UNSUPPORTED.onOrAfter(JAVA_5)); - assertFalse(UNSUPPORTED.onOrAfter(JAVA_6)); - assertFalse(UNSUPPORTED.onOrAfter(JAVA_7)); - assertFalse(UNSUPPORTED.onOrAfter(JAVA_8)); - assertFalse(UNSUPPORTED.onOrAfter(UNSUPPORTED)); - } - - @Test - public void testGetFromDoubleVersion() { - // JDK 5 - final JvmVersion java_5 = JvmVersion.getFromVersion(1.5); - assertSame(java_5, JAVA_5); - // JDK 6 - final JvmVersion java_6 = JvmVersion.getFromVersion(1.6); - assertSame(java_6, JAVA_6); - // JDK 7 - final JvmVersion java_7 = JvmVersion.getFromVersion(1.7); - assertSame(java_7, JAVA_7); - // JDK 8 - final JvmVersion java_8 = JvmVersion.getFromVersion(1.8); - assertSame(java_8, JAVA_8); - // Unsupported - final JvmVersion java_unsupported = JvmVersion.getFromVersion(0.9); - assertSame(java_unsupported, UNSUPPORTED); - } - - @Test - public void testGetFromStringVersion() { - // JDK 5 - final JvmVersion java_5 = JvmVersion.getFromVersion("1.5"); - assertSame(java_5, JAVA_5); - // JDK 6 - final JvmVersion java_6 = JvmVersion.getFromVersion("1.6"); - assertSame(java_6, JAVA_6); - // JDK 7 - final JvmVersion java_7 = JvmVersion.getFromVersion("1.7"); - assertSame(java_7, JAVA_7); - // JDK 8 - final JvmVersion java_8 = JvmVersion.getFromVersion("1.8"); - assertSame(java_8, JAVA_8); - // Unsupported - final JvmVersion java_unsupported = JvmVersion.getFromVersion("abc"); - assertSame(java_unsupported, UNSUPPORTED); - } + @Test + public void testOnOrAfter() { + // JDK 5 + assertTrue(JAVA_5.onOrAfter(JAVA_5)); + assertFalse(JAVA_5.onOrAfter(JAVA_6)); + assertFalse(JAVA_5.onOrAfter(JAVA_7)); + assertFalse(JAVA_5.onOrAfter(JAVA_8)); + assertFalse(JAVA_5.onOrAfter(UNSUPPORTED)); + // JDK 6 + assertTrue(JAVA_6.onOrAfter(JAVA_5)); + assertTrue(JAVA_6.onOrAfter(JAVA_6)); + assertFalse(JAVA_6.onOrAfter(JAVA_7)); + assertFalse(JAVA_6.onOrAfter(JAVA_8)); + assertFalse(JAVA_6.onOrAfter(UNSUPPORTED)); + // JDK 7 + assertTrue(JAVA_7.onOrAfter(JAVA_5)); + assertTrue(JAVA_7.onOrAfter(JAVA_6)); + assertTrue(JAVA_7.onOrAfter(JAVA_7)); + assertFalse(JAVA_7.onOrAfter(JAVA_8)); + assertFalse(JAVA_7.onOrAfter(UNSUPPORTED)); + // JDK 8 + assertTrue(JAVA_8.onOrAfter(JAVA_5)); + assertTrue(JAVA_8.onOrAfter(JAVA_6)); + assertTrue(JAVA_8.onOrAfter(JAVA_7)); + assertTrue(JAVA_8.onOrAfter(JAVA_8)); + assertFalse(JAVA_8.onOrAfter(UNSUPPORTED)); + // Unsupported + assertFalse(UNSUPPORTED.onOrAfter(JAVA_5)); + assertFalse(UNSUPPORTED.onOrAfter(JAVA_6)); + assertFalse(UNSUPPORTED.onOrAfter(JAVA_7)); + assertFalse(UNSUPPORTED.onOrAfter(JAVA_8)); + assertFalse(UNSUPPORTED.onOrAfter(UNSUPPORTED)); + } - @Test - public void testGetFromClassVersion() { - // JDK 5 - final JvmVersion java_5 = JvmVersion.getFromClassVersion(49); - assertSame(java_5, JAVA_5); - // JDK 6 - final JvmVersion java_6 = JvmVersion.getFromClassVersion(50); - assertSame(java_6, JAVA_6); - // JDK 7 - final JvmVersion java_7 = JvmVersion.getFromClassVersion(51); - assertSame(java_7, JAVA_7); - // JDK 8 - final JvmVersion java_8 = JvmVersion.getFromClassVersion(52); - assertSame(java_8, JAVA_8); - // Unsupported - final JvmVersion java_unsupported = JvmVersion.getFromClassVersion(-1); - assertSame(java_unsupported, UNSUPPORTED); - } + @Test + public void testGetFromDoubleVersion() { + // JDK 5 + final JvmVersion java_5 = JvmVersion.getFromVersion(1.5); + assertSame(java_5, JAVA_5); + // JDK 6 + final JvmVersion java_6 = JvmVersion.getFromVersion(1.6); + assertSame(java_6, JAVA_6); + // JDK 7 + final JvmVersion java_7 = JvmVersion.getFromVersion(1.7); + assertSame(java_7, JAVA_7); + // JDK 8 + final JvmVersion java_8 = JvmVersion.getFromVersion(1.8); + assertSame(java_8, JAVA_8); + // Unsupported + final JvmVersion java_unsupported = JvmVersion.getFromVersion(0.9); + assertSame(java_unsupported, UNSUPPORTED); + } + + @Test + public void testGetFromStringVersion() { + // JDK 5 + final JvmVersion java_5 = JvmVersion.getFromVersion("1.5"); + assertSame(java_5, JAVA_5); + // JDK 6 + final JvmVersion java_6 = JvmVersion.getFromVersion("1.6"); + assertSame(java_6, JAVA_6); + // JDK 7 + final JvmVersion java_7 = JvmVersion.getFromVersion("1.7"); + assertSame(java_7, JAVA_7); + // JDK 8 + final JvmVersion java_8 = JvmVersion.getFromVersion("1.8"); + assertSame(java_8, JAVA_8); + // Unsupported + final JvmVersion java_unsupported = JvmVersion.getFromVersion("abc"); + assertSame(java_unsupported, UNSUPPORTED); + } + + @Test + public void testGetFromClassVersion() { + // JDK 5 + final JvmVersion java_5 = JvmVersion.getFromClassVersion(49); + assertSame(java_5, JAVA_5); + // JDK 6 + final JvmVersion java_6 = JvmVersion.getFromClassVersion(50); + assertSame(java_6, JAVA_6); + // JDK 7 + final JvmVersion java_7 = JvmVersion.getFromClassVersion(51); + assertSame(java_7, JAVA_7); + // JDK 8 + final JvmVersion java_8 = JvmVersion.getFromClassVersion(52); + assertSame(java_8, JAVA_8); + // Unsupported + final JvmVersion java_unsupported = JvmVersion.getFromClassVersion(-1); + assertSame(java_unsupported, UNSUPPORTED); + } } diff --git a/commons/src/test/java/com/navercorp/pinpoint/common/util/TransactionIdUtilsTest.java b/commons/src/test/java/com/navercorp/pinpoint/common/util/TransactionIdUtilsTest.java index a87d2f15b..c3a4bbb27 100644 --- a/commons/src/test/java/com/navercorp/pinpoint/common/util/TransactionIdUtilsTest.java +++ b/commons/src/test/java/com/navercorp/pinpoint/common/util/TransactionIdUtilsTest.java @@ -43,16 +43,16 @@ public class TransactionIdUtilsTest { Assert.assertEquals(transactionId.getTransactionSequence(), 2L); } - @Test(expected = Exception.class) - public void testParseTransactionId_RpcHeaderDuplicateAdd_BugReproduce() { - // #27 http://yobi.navercorp.com/pinpoint/pinpoint/issue/27 - String id1 = "test" + TransactionIdUtils.TRANSACTION_ID_DELIMITER + "1" + TransactionIdUtils.TRANSACTION_ID_DELIMITER + "2"; - String id2 = "test" + TransactionIdUtils.TRANSACTION_ID_DELIMITER + "1" + TransactionIdUtils.TRANSACTION_ID_DELIMITER + "3"; - TransactionId transactionId = TransactionIdUtils.parseTransactionId(id1 + ", " + id2); - Assert.assertEquals(transactionId.getAgentId(), "test"); - Assert.assertEquals(transactionId.getAgentStartTime(), 1L); - Assert.assertEquals(transactionId.getTransactionSequence(), 2L); - } + @Test(expected = Exception.class) + public void testParseTransactionId_RpcHeaderDuplicateAdd_BugReproduce() { + // #27 http://yobi.navercorp.com/pinpoint/pinpoint/issue/27 + String id1 = "test" + TransactionIdUtils.TRANSACTION_ID_DELIMITER + "1" + TransactionIdUtils.TRANSACTION_ID_DELIMITER + "2"; + String id2 = "test" + TransactionIdUtils.TRANSACTION_ID_DELIMITER + "1" + TransactionIdUtils.TRANSACTION_ID_DELIMITER + "3"; + TransactionId transactionId = TransactionIdUtils.parseTransactionId(id1 + ", " + id2); + Assert.assertEquals(transactionId.getAgentId(), "test"); + Assert.assertEquals(transactionId.getAgentStartTime(), 1L); + Assert.assertEquals(transactionId.getTransactionSequence(), 2L); + } @Test diff --git a/profiler-optional/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/metric/EnhancedCpuLoadMetricSet.java b/profiler-optional/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/metric/EnhancedCpuLoadMetricSet.java index da5bbcc2c..4143c488d 100644 --- a/profiler-optional/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/metric/EnhancedCpuLoadMetricSet.java +++ b/profiler-optional/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/metric/EnhancedCpuLoadMetricSet.java @@ -25,29 +25,29 @@ import com.sun.management.OperatingSystemMXBean; */ public class EnhancedCpuLoadMetricSet extends AbstractCpuLoadMetricSet { - @Override - protected Gauge getJvmCpuLoadGauge(final OperatingSystemMXBean operatingSystemMXBean) { - return new Gauge() { - @Override - public Double getValue() { - return operatingSystemMXBean.getProcessCpuLoad(); - } - }; - } + @Override + protected Gauge getJvmCpuLoadGauge(final OperatingSystemMXBean operatingSystemMXBean) { + return new Gauge() { + @Override + public Double getValue() { + return operatingSystemMXBean.getProcessCpuLoad(); + } + }; + } - @Override - protected Gauge getSystemCpuLoadGauge(final OperatingSystemMXBean operatingSystemMXBean) { - return new Gauge() { - @Override - public Double getValue() { - return operatingSystemMXBean.getSystemCpuLoad(); - } - }; - } + @Override + protected Gauge getSystemCpuLoadGauge(final OperatingSystemMXBean operatingSystemMXBean) { + return new Gauge() { + @Override + public Double getValue() { + return operatingSystemMXBean.getSystemCpuLoad(); + } + }; + } + + @Override + public String toString() { + return "CpuLoadMetricSet for Java 1.7+"; + } - @Override - public String toString() { - return "CpuLoadMetricSet for Java 1.7+"; - } - } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentHandshakePropertyType.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentHandshakePropertyType.java index 5968d0225..848a5a43f 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentHandshakePropertyType.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentHandshakePropertyType.java @@ -28,52 +28,52 @@ import com.navercorp.pinpoint.rpc.util.ClassUtils; */ public enum AgentHandshakePropertyType { - SUPPORT_SERVER("supportServer", Boolean.class), - - HOSTNAME("hostName", String.class), - IP("ip", String.class), - AGENT_ID("agentId", String.class), - APPLICATION_NAME("applicationName", String.class), - SERVICE_TYPE("serviceType", Integer.class), - PID("pid", Integer.class), - VERSION("version", String.class), - START_TIMESTAMP("startTimestamp", Long.class); - + SUPPORT_SERVER("supportServer", Boolean.class), - private final String name; - private final Class clazzType; - - private AgentHandshakePropertyType(String name, Class clazzType) { - this.name = name; - this.clazzType = clazzType; - } + HOSTNAME("hostName", String.class), + IP("ip", String.class), + AGENT_ID("agentId", String.class), + APPLICATION_NAME("applicationName", String.class), + SERVICE_TYPE("serviceType", Integer.class), + PID("pid", Integer.class), + VERSION("version", String.class), + START_TIMESTAMP("startTimestamp", Long.class); - public String getName() { - return name; - } - - public Class getClazzType() { - return clazzType; - } - - public static boolean hasAllType(Map properties) { - for (AgentHandshakePropertyType type : AgentHandshakePropertyType.values()) { - if (type == SUPPORT_SERVER) { - continue; - } - - Object value = properties.get(type.getName()); - - if (value == null) { - return false; - } - - if (!ClassUtils.isAssignable(value.getClass(), type.getClazzType())) { - return false; - } - } - - return true; - } + + private final String name; + private final Class clazzType; + + private AgentHandshakePropertyType(String name, Class clazzType) { + this.name = name; + this.clazzType = clazzType; + } + + public String getName() { + return name; + } + + public Class getClazzType() { + return clazzType; + } + + public static boolean hasAllType(Map properties) { + for (AgentHandshakePropertyType type : AgentHandshakePropertyType.values()) { + if (type == SUPPORT_SERVER) { + continue; + } + + Object value = properties.get(type.getName()); + + if (value == null) { + return false; + } + + if (!ClassUtils.isAssignable(value.getClass(), type.getClazzType())) { + return false; + } + } + + return true; + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInfoSenderListener.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInfoSenderListener.java index 8d791ab92..fd2fdd883 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInfoSenderListener.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInfoSenderListener.java @@ -31,37 +31,37 @@ import com.navercorp.pinpoint.thrift.util.SerializationUtils; public class AgentInfoSenderListener implements FutureListener { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final AtomicBoolean isSuccessful; - - public AgentInfoSenderListener(AtomicBoolean isSuccessful) { - this.isSuccessful = isSuccessful; - } + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final AtomicBoolean isSuccessful; - @Override - public void onComplete(Future future) { - try { - if (future != null && future.isSuccess()) { - TBase tbase = deserialize(future); - if (tbase instanceof TResult) { - TResult result = (TResult) tbase; - if (result.isSuccess()) { - logger.debug("result success"); - this.isSuccessful.set(true); - return; - } else { - logger.warn("request fail. Caused:{}", result.getMessage()); - } - } else { - logger.warn("Invalid Class. {}", tbase); - } - } - } catch(Exception e) { - logger.warn("request fail. caused:{}", e.getMessage()); - } - } + public AgentInfoSenderListener(AtomicBoolean isSuccessful) { + this.isSuccessful = isSuccessful; + } - private TBase deserialize(Future future) { + @Override + public void onComplete(Future future) { + try { + if (future != null && future.isSuccess()) { + TBase tbase = deserialize(future); + if (tbase instanceof TResult) { + TResult result = (TResult) tbase; + if (result.isSuccess()) { + logger.debug("result success"); + this.isSuccessful.set(true); + return; + } else { + logger.warn("request fail. Caused:{}", result.getMessage()); + } + } else { + logger.warn("Invalid Class. {}", tbase); + } + } + } catch(Exception e) { + logger.warn("request fail. caused:{}", e.getMessage()); + } + } + + private TBase deserialize(Future future) { final ResponseMessage responseMessage = future.getResult(); // TODO Should we change this to thread local cache? This object's life cycle is different because it could be created many times. @@ -69,6 +69,6 @@ public class AgentInfoSenderListener implements FutureListener byte[] message = responseMessage.getMessage(); return SerializationUtils.deserialize(message, HeaderTBaseDeserializerFactory.DEFAULT_FACTORY, null); - } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInformation.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInformation.java index 507e2de8e..f33bccc82 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInformation.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInformation.java @@ -100,18 +100,18 @@ public class AgentInformation { } public Map toMap() { - Map map = new HashMap(); - - map.put(AgentHandshakePropertyType.AGENT_ID.getName(), this.agentId); - map.put(AgentHandshakePropertyType.APPLICATION_NAME.getName(), this.applicationName); - map.put(AgentHandshakePropertyType.HOSTNAME.getName(), this.machineName); - map.put(AgentHandshakePropertyType.IP.getName(), this.hostIp); - map.put(AgentHandshakePropertyType.PID.getName(), this.pid); - map.put(AgentHandshakePropertyType.SERVICE_TYPE.getName(), this.serverType); - map.put(AgentHandshakePropertyType.START_TIMESTAMP.getName(), this.startTime); - map.put(AgentHandshakePropertyType.VERSION.getName(), this.version); - - return map; + Map map = new HashMap(); + + map.put(AgentHandshakePropertyType.AGENT_ID.getName(), this.agentId); + map.put(AgentHandshakePropertyType.APPLICATION_NAME.getName(), this.applicationName); + map.put(AgentHandshakePropertyType.HOSTNAME.getName(), this.machineName); + map.put(AgentHandshakePropertyType.IP.getName(), this.hostIp); + map.put(AgentHandshakePropertyType.PID.getName(), this.pid); + map.put(AgentHandshakePropertyType.SERVICE_TYPE.getName(), this.serverType); + map.put(AgentHandshakePropertyType.START_TIMESTAMP.getName(), this.startTime); + map.put(AgentHandshakePropertyType.VERSION.getName(), this.version); + + return map; } @Override diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInformationFactory.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInformationFactory.java index 2fff74874..3971a3fee 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInformationFactory.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInformationFactory.java @@ -59,14 +59,14 @@ public class AgentInformationFactory { } private void validateId(String id, String idName, int maxlen) { - if (id == null) { - throw new NullPointerException("id must not be null"); - } - - // TODO AgengId should be validated before bootclass. - // or agent should stop when validataion is failed here. + if (id == null) { + throw new NullPointerException("id must not be null"); + } + + // TODO AgengId should be validated before bootclass. + // or agent should stop when validataion is failed here. final byte[] bytes = BytesUtils.toBytes(id); - if (bytes.length > maxlen) { + if (bytes.length > maxlen) { logger.warn("{} is too long(1~24). value={}", idName, id); } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentStatus.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentStatus.java index 17b494f1d..a81ee1e12 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentStatus.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentStatus.java @@ -17,7 +17,7 @@ package com.navercorp.pinpoint.profiler; public enum AgentStatus { - INITIALIZING, - RUNNING, - STOPPED + INITIALIZING, + RUNNING, + STOPPED } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/ClassFileFilter.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/ClassFileFilter.java index 1a2adf28e..692a83a21 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/ClassFileFilter.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/ClassFileFilter.java @@ -22,8 +22,8 @@ import java.security.ProtectionDomain; * @author emeroad */ public interface ClassFileFilter { - public static final boolean SKIP = true; - public static final boolean CONTINUE = false; + public static final boolean SKIP = true; + public static final boolean CONTINUE = false; - boolean doFilter(ClassLoader classLoader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classFileBuffer); + boolean doFilter(ClassLoader classLoader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classFileBuffer); } 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 63c574856..01558992e 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgent.java @@ -268,7 +268,7 @@ public class DefaultAgent implements Agent { } protected PinpointSocketFactory createPinpointSocketFactory(CommandDispatcher commandDispatcher) { - PinpointSocketFactory pinpointSocketFactory = new PinpointSocketFactory(); + PinpointSocketFactory pinpointSocketFactory = new PinpointSocketFactory(); pinpointSocketFactory.setTimeoutMillis(1000 * 5); Map properties = this.agentInformation.toMap(); @@ -276,12 +276,12 @@ public class DefaultAgent implements Agent { boolean isSupportServerMode = this.profilerConfig.isTcpDataSenderCommandAcceptEnable(); if (isSupportServerMode) { - pinpointSocketFactory.setMessageListener(commandDispatcher); - pinpointSocketFactory.setServerStreamChannelMessageListener(commandDispatcher); + pinpointSocketFactory.setMessageListener(commandDispatcher); + pinpointSocketFactory.setServerStreamChannelMessageListener(commandDispatcher); - properties.put(AgentHandshakePropertyType.SUPPORT_SERVER.getName(), true); + properties.put(AgentHandshakePropertyType.SUPPORT_SERVER.getName(), true); } else { - properties.put(AgentHandshakePropertyType.SUPPORT_SERVER.getName(), false); + properties.put(AgentHandshakePropertyType.SUPPORT_SERVER.getName(), false); } pinpointSocketFactory.setProperties(properties); diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultClassFileFilter.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultClassFileFilter.java index b7f9466f4..6c1f6bcab 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultClassFileFilter.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultClassFileFilter.java @@ -23,33 +23,33 @@ import java.security.ProtectionDomain; */ public class DefaultClassFileFilter implements ClassFileFilter { - private final ClassLoader agentLoader; + private final ClassLoader agentLoader; - public DefaultClassFileFilter(ClassLoader agentLoader) { - if (agentLoader == null) { - throw new NullPointerException("agentLoader must not be null"); - } - this.agentLoader = agentLoader; - } + public DefaultClassFileFilter(ClassLoader agentLoader) { + if (agentLoader == null) { + throw new NullPointerException("agentLoader must not be null"); + } + this.agentLoader = agentLoader; + } - @Override - public boolean doFilter(ClassLoader classLoader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classFileBuffer) { - // fast skip java classes - if (className.startsWith("java")) { - if (className.startsWith("/", 4) || className.startsWith("x/", 4)) { - return SKIP; - } - } + @Override + public boolean doFilter(ClassLoader classLoader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classFileBuffer) { + // fast skip java classes + if (className.startsWith("java")) { + if (className.startsWith("/", 4) || className.startsWith("x/", 4)) { + return SKIP; + } + } - if (classLoader == agentLoader) { - // skip classes loaded by agent class loader. - return SKIP; - } - - // Skip pinpoint packages too. - if (className.startsWith("com/navercorp/pinpoint/")) { - return SKIP; - } - return CONTINUE; - } + if (classLoader == agentLoader) { + // skip classes loaded by agent class loader. + return SKIP; + } + + // Skip pinpoint packages too. + if (className.startsWith("com/navercorp/pinpoint/")) { + return SKIP; + } + return CONTINUE; + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTrace.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTrace.java index 4526792b9..62edfe94a 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTrace.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTrace.java @@ -110,7 +110,7 @@ public final class DefaultTrace implements Trace { } public Storage getStorage() { - return this.storage; + return this.storage; } public short nextSequence() { diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTraceId.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTraceId.java index 244b61762..cabf5ff8f 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTraceId.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTraceId.java @@ -26,12 +26,12 @@ import com.navercorp.pinpoint.common.util.TransactionIdUtils; public class DefaultTraceId implements TraceId { private final String agentId; - private final long agentStartTime; + private final long agentStartTime; private final long transactionSequence; - private final long parentSpanId; - private final long spanId; - private final short flags; + private final long parentSpanId; + private final long spanId; + private final short flags; public DefaultTraceId(String agentId, long agentStartTime, long transactionId) { this(agentId, agentStartTime, transactionId, SpanId.NULL, SpanId.newSpanId(), (short) 0); @@ -46,11 +46,11 @@ public class DefaultTraceId implements TraceId { } - public TraceId getNextTraceId() { - return new DefaultTraceId(this.agentId, this.agentStartTime, transactionSequence, spanId, SpanId.nextSpanID(spanId, parentSpanId), flags); - } + public TraceId getNextTraceId() { + return new DefaultTraceId(this.agentId, this.agentStartTime, transactionSequence, spanId, SpanId.nextSpanID(spanId, parentSpanId), flags); + } - public DefaultTraceId(String agentId, long agentStartTime, long transactionId, long parentSpanId, long spanId, short flags) { + public DefaultTraceId(String agentId, long agentStartTime, long transactionId, long parentSpanId, long spanId, short flags) { if (agentId == null) { throw new NullPointerException("agentId must not be null"); } @@ -58,14 +58,14 @@ public class DefaultTraceId implements TraceId { this.agentStartTime = agentStartTime; this.transactionSequence = transactionId; - this.parentSpanId = parentSpanId; - this.spanId = spanId; - this.flags = flags; - } + this.parentSpanId = parentSpanId; + this.spanId = spanId; + this.flags = flags; + } - public String getTransactionId() { + public String getTransactionId() { return TransactionIdUtils.formatString(agentId, agentStartTime, transactionSequence); - } + } public String getAgentId() { return agentId; @@ -80,22 +80,22 @@ public class DefaultTraceId implements TraceId { } - public long getParentSpanId() { - return parentSpanId; - } + public long getParentSpanId() { + return parentSpanId; + } - public long getSpanId() { - return spanId; - } + public long getSpanId() { + return spanId; + } - public short getFlags() { - return flags; - } + public short getFlags() { + return flags; + } - public boolean isRoot() { - return this.parentSpanId == SpanId.NULL; - } + public boolean isRoot() { + return this.parentSpanId == SpanId.NULL; + } @Override diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/Span.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/Span.java index 9e38a8781..fc48d3861 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/Span.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/Span.java @@ -96,12 +96,12 @@ public class Span extends TSpan { } public int getErrCode() { - return getErr(); - } + return getErr(); + } - public void setErrCode(int exception) { + public void setErrCode(int exception) { super.setErr(exception); - } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/interceptor/bci/AspectWeaverClass.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/interceptor/bci/AspectWeaverClass.java index 63312812e..bbf05e9e3 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/interceptor/bci/AspectWeaverClass.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/interceptor/bci/AspectWeaverClass.java @@ -35,209 +35,209 @@ import java.util.List; */ public class AspectWeaverClass { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private static final MethodNameReplacer DEFAULT_METHOD_NAME_REPLACER = new DefaultMethodNameReplacer(); + private static final MethodNameReplacer DEFAULT_METHOD_NAME_REPLACER = new DefaultMethodNameReplacer(); - private final MethodNameReplacer methodNameReplacer; + private final MethodNameReplacer methodNameReplacer; - public AspectWeaverClass() { - methodNameReplacer = DEFAULT_METHOD_NAME_REPLACER; - } + public AspectWeaverClass() { + methodNameReplacer = DEFAULT_METHOD_NAME_REPLACER; + } - public void weaving(CtClass sourceClass, CtClass adviceClass) throws NotFoundException, CannotCompileException { - if (logger.isInfoEnabled()) { - logger.info("weaving sourceClass:{} advice:{}", sourceClass.getName(), adviceClass.getName()); - } - if (!isAspectClass(adviceClass)) { - throw new RuntimeException("@Aspect not found. adviceClass:" + adviceClass); - } - // advice class hierarchy check, - final boolean isSubClass = adviceClass.subclassOf(sourceClass); - if (!isSubClass) { - final CtClass superClass = adviceClass.getSuperclass(); - if (!superClass.getName().equals("java.lang.Object")) { - throw new CannotCompileException("invalid class hierarchy. " + sourceClass.getName() + " adviceSuperClass:" + superClass.getName()); - } - } + public void weaving(CtClass sourceClass, CtClass adviceClass) throws NotFoundException, CannotCompileException { + if (logger.isInfoEnabled()) { + logger.info("weaving sourceClass:{} advice:{}", sourceClass.getName(), adviceClass.getName()); + } + if (!isAspectClass(adviceClass)) { + throw new RuntimeException("@Aspect not found. adviceClass:" + adviceClass); + } + // advice class hierarchy check, + final boolean isSubClass = adviceClass.subclassOf(sourceClass); + if (!isSubClass) { + final CtClass superClass = adviceClass.getSuperclass(); + if (!superClass.getName().equals("java.lang.Object")) { + throw new CannotCompileException("invalid class hierarchy. " + sourceClass.getName() + " adviceSuperClass:" + superClass.getName()); + } + } - copyUtilMethod(sourceClass, adviceClass); + copyUtilMethod(sourceClass, adviceClass); - final List pointCutMethodList = findAnnotationMethod(adviceClass, PointCut.class); - final List jointPointList = findAnnotationMethod(adviceClass, JointPoint.class); + final List pointCutMethodList = findAnnotationMethod(adviceClass, PointCut.class); + final List jointPointList = findAnnotationMethod(adviceClass, JointPoint.class); - for (CtMethod adviceMethod : pointCutMethodList) { - final CtMethod sourceMethod = sourceClass.getDeclaredMethod(adviceMethod.getName(), adviceMethod.getParameterTypes()); - if (!sourceMethod.getSignature().equals(adviceMethod.getSignature())) { - throw new CannotCompileException("Signature miss match. method:" + adviceMethod.getName() + " source:" + sourceMethod.getSignature() + " advice:" + adviceMethod.getSignature()); - } - if (logger.isInfoEnabled()) { - logger.info("weaving method:{}{}", sourceMethod.getName(), sourceMethod.getSignature()); - } - weavingMethod(sourceClass, sourceMethod, adviceMethod, jointPointList, isSubClass); - } + for (CtMethod adviceMethod : pointCutMethodList) { + final CtMethod sourceMethod = sourceClass.getDeclaredMethod(adviceMethod.getName(), adviceMethod.getParameterTypes()); + if (!sourceMethod.getSignature().equals(adviceMethod.getSignature())) { + throw new CannotCompileException("Signature miss match. method:" + adviceMethod.getName() + " source:" + sourceMethod.getSignature() + " advice:" + adviceMethod.getSignature()); + } + if (logger.isInfoEnabled()) { + logger.info("weaving method:{}{}", sourceMethod.getName(), sourceMethod.getSignature()); + } + weavingMethod(sourceClass, sourceMethod, adviceMethod, jointPointList, isSubClass); + } - } + } - private void copyUtilMethod(CtClass sourceClass, CtClass adviceClass) throws CannotCompileException { - final List utilMethodList = findUtilMethod(adviceClass); - for (CtMethod method : utilMethodList) { - final CtMethod copyMethod = CtNewMethod.copy(method, method.getName(), sourceClass, null); - sourceClass.addMethod(copyMethod); - } - } + private void copyUtilMethod(CtClass sourceClass, CtClass adviceClass) throws CannotCompileException { + final List utilMethodList = findUtilMethod(adviceClass); + for (CtMethod method : utilMethodList) { + final CtMethod copyMethod = CtNewMethod.copy(method, method.getName(), sourceClass, null); + sourceClass.addMethod(copyMethod); + } + } - private List findUtilMethod(CtClass adviceClass) throws CannotCompileException { - List utilMethodList = new ArrayList(); - for (CtMethod method : adviceClass.getDeclaredMethods()) { - if (method.hasAnnotation(PointCut.class) || method.hasAnnotation(JointPoint.class)) { - continue; - } - int modifiers = method.getModifiers(); - if (!Modifier.isPrivate(modifiers)) { - throw new CannotCompileException("non private UtilMethod unsupported. method:" + method.getLongName()); - } - utilMethodList.add(method); - } - return utilMethodList; - } + private List findUtilMethod(CtClass adviceClass) throws CannotCompileException { + List utilMethodList = new ArrayList(); + for (CtMethod method : adviceClass.getDeclaredMethods()) { + if (method.hasAnnotation(PointCut.class) || method.hasAnnotation(JointPoint.class)) { + continue; + } + int modifiers = method.getModifiers(); + if (!Modifier.isPrivate(modifiers)) { + throw new CannotCompileException("non private UtilMethod unsupported. method:" + method.getLongName()); + } + utilMethodList.add(method); + } + return utilMethodList; + } - private boolean isAspectClass(CtClass aspectClass) { - return aspectClass.hasAnnotation(Aspect.class); - } + private boolean isAspectClass(CtClass aspectClass) { + return aspectClass.hasAnnotation(Aspect.class); + } - private void weavingMethod(CtClass sourceClass, CtMethod sourceMethod, CtMethod adviceMethod, List jointPointList, boolean isSubClass) throws CannotCompileException { - final CtMethod copyMethod = copyMethod(sourceClass, sourceMethod); - sourceClass.addMethod(copyMethod); + private void weavingMethod(CtClass sourceClass, CtMethod sourceMethod, CtMethod adviceMethod, List jointPointList, boolean isSubClass) throws CannotCompileException { + final CtMethod copyMethod = copyMethod(sourceClass, sourceMethod); + sourceClass.addMethod(copyMethod); - sourceMethod.setBody(adviceMethod, null); + sourceMethod.setBody(adviceMethod, null); - sourceMethod.instrument(new JointPointMethodEditor(sourceClass, sourceMethod, copyMethod, jointPointList, isSubClass)); - } + sourceMethod.instrument(new JointPointMethodEditor(sourceClass, sourceMethod, copyMethod, jointPointList, isSubClass)); + } - public class JointPointMethodEditor extends ExprEditor { - private final CtClass sourceClass; - private final CtMethod sourceMethod; - private final CtMethod replaceMethod; - private final List jointPointList; - private final boolean isSubClass; + public class JointPointMethodEditor extends ExprEditor { + private final CtClass sourceClass; + private final CtMethod sourceMethod; + private final CtMethod replaceMethod; + private final List jointPointList; + private final boolean isSubClass; - public JointPointMethodEditor(CtClass sourceClass, CtMethod sourceMethod, CtMethod replaceMethod, List jointPointList, boolean isSubClass) { - if (replaceMethod == null) { - throw new NullPointerException("replaceMethod must not be null"); - } - this.sourceClass = sourceClass; - this.sourceMethod = sourceMethod; - this.replaceMethod = replaceMethod; - this.jointPointList = jointPointList; - this.isSubClass = isSubClass; - } + public JointPointMethodEditor(CtClass sourceClass, CtMethod sourceMethod, CtMethod replaceMethod, List jointPointList, boolean isSubClass) { + if (replaceMethod == null) { + throw new NullPointerException("replaceMethod must not be null"); + } + this.sourceClass = sourceClass; + this.sourceMethod = sourceMethod; + this.replaceMethod = replaceMethod; + this.jointPointList = jointPointList; + this.isSubClass = isSubClass; + } - @Override - public void edit(MethodCall methodCall) throws CannotCompileException { + @Override + public void edit(MethodCall methodCall) throws CannotCompileException { - final boolean joinPointMethod = isJoinPointMethod(jointPointList, methodCall.getMethodName(), methodCall.getSignature()); - if (joinPointMethod) { - if (!methodCall.getSignature().equals(replaceMethod.getSignature())) { - throw new CannotCompileException("Signature miss match. method:" + sourceMethod.getName() + " source:" + sourceMethod.getSignature() + " jointPoint:" + replaceMethod.getSignature()); - } - final String invokeSource = invokeSourceMethod(); - if (logger.isDebugEnabled()) { - logger.debug("JointPoint method {}{} -> invokeOriginal:{}", methodCall.getMethodName(), methodCall.getSignature(), invokeSource); - } - methodCall.replace(invokeSource); - } else { - if (isSubClass) { - // validate super class method - try { - CtMethod method = methodCall.getMethod(); - CtClass declaringClass = method.getDeclaringClass(); - if (sourceClass.subclassOf(declaringClass)) { - sourceClass.getMethod(methodCall.getMethodName(), methodCall.getSignature()); - } - } catch (NotFoundException e) { - throw new CannotCompileException(e.getMessage(), e); - } - } - } - } + final boolean joinPointMethod = isJoinPointMethod(jointPointList, methodCall.getMethodName(), methodCall.getSignature()); + if (joinPointMethod) { + if (!methodCall.getSignature().equals(replaceMethod.getSignature())) { + throw new CannotCompileException("Signature miss match. method:" + sourceMethod.getName() + " source:" + sourceMethod.getSignature() + " jointPoint:" + replaceMethod.getSignature()); + } + final String invokeSource = invokeSourceMethod(); + if (logger.isDebugEnabled()) { + logger.debug("JointPoint method {}{} -> invokeOriginal:{}", methodCall.getMethodName(), methodCall.getSignature(), invokeSource); + } + methodCall.replace(invokeSource); + } else { + if (isSubClass) { + // validate super class method + try { + CtMethod method = methodCall.getMethod(); + CtClass declaringClass = method.getDeclaringClass(); + if (sourceClass.subclassOf(declaringClass)) { + sourceClass.getMethod(methodCall.getMethodName(), methodCall.getSignature()); + } + } catch (NotFoundException e) { + throw new CannotCompileException(e.getMessage(), e); + } + } + } + } - private boolean isJoinPointMethod(List jointPointList, String methodName, String methodSignature) { - for (CtMethod method : jointPointList) { - if (method.getName().equals(methodName) && method.getSignature().equals(methodSignature)) { - return true; - } - } - return false; - } + private boolean isJoinPointMethod(List jointPointList, String methodName, String methodSignature) { + for (CtMethod method : jointPointList) { + if (method.getName().equals(methodName) && method.getSignature().equals(methodSignature)) { + return true; + } + } + return false; + } - private String invokeSourceMethod() { - CodeBuilder builder = new CodeBuilder(32); - if (!isVoid(replaceMethod.getSignature())) { - builder.append("$_="); - } + private String invokeSourceMethod() { + CodeBuilder builder = new CodeBuilder(32); + if (!isVoid(replaceMethod.getSignature())) { + builder.append("$_="); + } - builder.format("%1$s($$);", methodNameReplacer.replaceMethodName(sourceMethod.getName())); - return builder.toString(); - } + builder.format("%1$s($$);", methodNameReplacer.replaceMethodName(sourceMethod.getName())); + return builder.toString(); + } - public boolean isVoid(String signature) { - return signature.endsWith("V"); - } - } + public boolean isVoid(String signature) { + return signature.endsWith("V"); + } + } - private CtMethod copyMethod(CtClass sourceClass, CtMethod sourceMethod) throws CannotCompileException { + private CtMethod copyMethod(CtClass sourceClass, CtMethod sourceMethod) throws CannotCompileException { - // need id? + // need id? - String copyMethodName = methodNameReplacer.replaceMethodName(sourceMethod.getName()); + String copyMethodName = methodNameReplacer.replaceMethodName(sourceMethod.getName()); - final CtMethod copy = CtNewMethod.copy(sourceMethod, copyMethodName, sourceClass, null); + final CtMethod copy = CtNewMethod.copy(sourceMethod, copyMethodName, sourceClass, null); - // set private - final int modifiers = copy.getModifiers(); - copy.setModifiers(Modifier.setPrivate(modifiers)); + // set private + final int modifiers = copy.getModifiers(); + copy.setModifiers(Modifier.setPrivate(modifiers)); - return copy; + return copy; - } + } - private List findAnnotationMethod(CtClass ctClass, Class annotation) { - if (ctClass == null) { - throw new NullPointerException("ctClass must not be null"); - } - if (annotation == null) { - throw new NullPointerException("annotation must not be null"); - } + private List findAnnotationMethod(CtClass ctClass, Class annotation) { + if (ctClass == null) { + throw new NullPointerException("ctClass must not be null"); + } + if (annotation == null) { + throw new NullPointerException("annotation must not be null"); + } - final List annotationList = new ArrayList(); + final List annotationList = new ArrayList(); - for (CtMethod method : ctClass.getDeclaredMethods()) { - if (method.hasAnnotation(annotation)) { - annotationList.add(method); - } - } - return annotationList; - } + for (CtMethod method : ctClass.getDeclaredMethods()) { + if (method.hasAnnotation(annotation)) { + annotationList.add(method); + } + } + return annotationList; + } - public static interface MethodNameReplacer { - String replaceMethodName(String methodName); - } + public static interface MethodNameReplacer { + String replaceMethodName(String methodName); + } - public static class DefaultMethodNameReplacer implements MethodNameReplacer { - public static final String PREFIX = "__"; - public static final String POSTFIX = "_$$pinpoint"; + public static class DefaultMethodNameReplacer implements MethodNameReplacer { + public static final String PREFIX = "__"; + public static final String POSTFIX = "_$$pinpoint"; - public String replaceMethodName(String methodName) { - if (methodName == null) { - throw new NullPointerException("methodName must not be null"); - } - return PREFIX + methodName + POSTFIX; - } - } + public String replaceMethodName(String methodName) { + if (methodName == null) { + throw new NullPointerException("methodName must not be null"); + } + return PREFIX + methodName + POSTFIX; + } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/DefaultModifierRegistry.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/DefaultModifierRegistry.java index cb68bfeb7..825d93c40 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/DefaultModifierRegistry.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/DefaultModifierRegistry.java @@ -196,60 +196,60 @@ public class DefaultModifierRegistry implements ModifierRegistry { } } - public void addTomcatModifier() { - StandardHostValveInvokeModifier standardHostValveInvokeModifier = new StandardHostValveInvokeModifier(byteCodeInstrumentor, agent); - addModifier(standardHostValveInvokeModifier); + public void addTomcatModifier() { + StandardHostValveInvokeModifier standardHostValveInvokeModifier = new StandardHostValveInvokeModifier(byteCodeInstrumentor, agent); + addModifier(standardHostValveInvokeModifier); - HttpServletModifier httpServletModifier = new HttpServletModifier(byteCodeInstrumentor, agent); - addModifier(httpServletModifier); + HttpServletModifier httpServletModifier = new HttpServletModifier(byteCodeInstrumentor, agent); + addModifier(httpServletModifier); - SpringFrameworkServletModifier springServletModifier = new SpringFrameworkServletModifier(byteCodeInstrumentor, agent); - addModifier(springServletModifier); + SpringFrameworkServletModifier springServletModifier = new SpringFrameworkServletModifier(byteCodeInstrumentor, agent); + addModifier(springServletModifier); - AbstractModifier tomcatStandardServiceModifier = new StandardServiceModifier(byteCodeInstrumentor, agent); - addModifier(tomcatStandardServiceModifier); + AbstractModifier tomcatStandardServiceModifier = new StandardServiceModifier(byteCodeInstrumentor, agent); + addModifier(tomcatStandardServiceModifier); - AbstractModifier tomcatConnectorModifier = new TomcatConnectorModifier(byteCodeInstrumentor, agent); - addModifier(tomcatConnectorModifier); + AbstractModifier tomcatConnectorModifier = new TomcatConnectorModifier(byteCodeInstrumentor, agent); + addModifier(tomcatConnectorModifier); - AbstractModifier tomcatWebappLoaderModifier = new WebappLoaderModifier(byteCodeInstrumentor, agent); + AbstractModifier tomcatWebappLoaderModifier = new WebappLoaderModifier(byteCodeInstrumentor, agent); addModifier(tomcatWebappLoaderModifier); - if (profilerConfig.isTomcatHidePinpointHeader()) { - AbstractModifier requestFacadeModifier = new RequestFacadeModifier(byteCodeInstrumentor, agent); - addModifier(requestFacadeModifier); - } - } + if (profilerConfig.isTomcatHidePinpointHeader()) { + AbstractModifier requestFacadeModifier = new RequestFacadeModifier(byteCodeInstrumentor, agent); + addModifier(requestFacadeModifier); + } + } - public void addJdbcModifier() { - // TODO Can we check if JDBC driver exists here? - - if (!profilerConfig.isJdbcProfile()) { - return; - } + public void addJdbcModifier() { + // TODO Can we check if JDBC driver exists here? - if (profilerConfig.isJdbcProfileMySql()) { - addMySqlDriver(); - } + if (!profilerConfig.isJdbcProfile()) { + return; + } - if (profilerConfig.isJdbcProfileJtds()) { - addJtdsDriver(); - } + if (profilerConfig.isJdbcProfileMySql()) { + addMySqlDriver(); + } - if (profilerConfig.isJdbcProfileOracle()) { - addOracleDriver(); - } - if (profilerConfig.isJdbcProfileCubrid()) { - addCubridDriver(); - } + if (profilerConfig.isJdbcProfileJtds()) { + addJtdsDriver(); + } - if (profilerConfig.isJdbcProfileDbcp()) { - addDbcpDriver(); - } - } + if (profilerConfig.isJdbcProfileOracle()) { + addOracleDriver(); + } + if (profilerConfig.isJdbcProfileCubrid()) { + addCubridDriver(); + } - private void addMySqlDriver() { - // TODO In some MySQL drivers Connection is an interface and in the others it's a class. Is this OK? + if (profilerConfig.isJdbcProfileDbcp()) { + addDbcpDriver(); + } + } + + private void addMySqlDriver() { + // TODO In some MySQL drivers Connection is an interface and in the others it's a class. Is this OK? AbstractModifier mysqlNonRegisteringDriverModifier = new MySQLNonRegisteringDriverModifier(byteCodeInstrumentor, agent); addModifier(mysqlNonRegisteringDriverModifier); @@ -268,15 +268,15 @@ public class DefaultModifierRegistry implements ModifierRegistry { AbstractModifier mysqlPreparedStatementModifier = new MySQLPreparedStatementModifier(byteCodeInstrumentor, agent); addModifier(mysqlPreparedStatementModifier); - MySQLPreparedStatementJDBC4Modifier myqlPreparedStatementJDBC4Modifier = new MySQLPreparedStatementJDBC4Modifier(byteCodeInstrumentor, agent); - addModifier(myqlPreparedStatementJDBC4Modifier); + MySQLPreparedStatementJDBC4Modifier myqlPreparedStatementJDBC4Modifier = new MySQLPreparedStatementJDBC4Modifier(byteCodeInstrumentor, agent); + addModifier(myqlPreparedStatementJDBC4Modifier); // TODO Need to create result set fetch counter -// Modifier mysqlResultSetModifier = new MySQLResultSetModifier(byteCodeInstrumentor, agent); -// addModifier(mysqlResultSetModifier); - } +// Modifier mysqlResultSetModifier = new MySQLResultSetModifier(byteCodeInstrumentor, agent); +// addModifier(mysqlResultSetModifier); + } - private void addJtdsDriver() { + private void addJtdsDriver() { JtdsDriverModifier jtdsDriverModifier = new JtdsDriverModifier(byteCodeInstrumentor, agent); addModifier(jtdsDriverModifier); @@ -295,7 +295,7 @@ public class DefaultModifierRegistry implements ModifierRegistry { AbstractModifier mssqlResultSetModifier = new JtdsResultSetModifier(byteCodeInstrumentor, agent); addModifier(mssqlResultSetModifier); - } + } private void addOracleDriver() { AbstractModifier oracleDriverModifier = new OracleDriverModifier(byteCodeInstrumentor, agent); @@ -316,45 +316,45 @@ public class DefaultModifierRegistry implements ModifierRegistry { // addModifier(oracleResultSetModifier); } - private void addCubridDriver() { - // TODO Cubrid doesn't have connection impl too. Check it out. - addModifier(new CubridConnectionModifier(byteCodeInstrumentor, agent)); - addModifier(new CubridDriverModifier(byteCodeInstrumentor, agent)); - addModifier(new CubridStatementModifier(byteCodeInstrumentor, agent)); - addModifier(new CubridPreparedStatementModifier(byteCodeInstrumentor, agent)); - addModifier(new CubridResultSetModifier(byteCodeInstrumentor, agent)); -// addModifier(new CubridUStatementModifier(byteCodeInstrumentor, agent)); - } + private void addCubridDriver() { + // TODO Cubrid doesn't have connection impl too. Check it out. + addModifier(new CubridConnectionModifier(byteCodeInstrumentor, agent)); + addModifier(new CubridDriverModifier(byteCodeInstrumentor, agent)); + addModifier(new CubridStatementModifier(byteCodeInstrumentor, agent)); + addModifier(new CubridPreparedStatementModifier(byteCodeInstrumentor, agent)); + addModifier(new CubridResultSetModifier(byteCodeInstrumentor, agent)); +// addModifier(new CubridUStatementModifier(byteCodeInstrumentor, agent)); + } - private void addDbcpDriver() { + private void addDbcpDriver() { // TODO Cubrid doesn't have connection impl too. Check it out. AbstractModifier dbcpBasicDataSourceModifier = new DBCPBasicDataSourceModifier(byteCodeInstrumentor, agent); addModifier(dbcpBasicDataSourceModifier); if (profilerConfig.isJdbcProfileDbcpConnectionClose()) { - AbstractModifier dbcpPoolModifier = new DBCPPoolGuardConnectionWrapperModifier(byteCodeInstrumentor, agent); - addModifier(dbcpPoolModifier); + AbstractModifier dbcpPoolModifier = new DBCPPoolGuardConnectionWrapperModifier(byteCodeInstrumentor, agent); + addModifier(dbcpPoolModifier); } - } - - /** - * Support ORM(iBatis, myBatis, etc.) - */ - public void addOrmModifier() { - addIBatisSupport(); - addMyBatisSupport(); - } - - private void addIBatisSupport() { + } + + /** + * Support ORM(iBatis, myBatis, etc.) + */ + public void addOrmModifier() { + addIBatisSupport(); + addMyBatisSupport(); + } + + private void addIBatisSupport() { if (profilerConfig.isIBatisEnabled()) { addModifier(new SqlMapSessionImplModifier(byteCodeInstrumentor, agent)); addModifier(new SqlMapClientImplModifier(byteCodeInstrumentor, agent)); addModifier(new SqlMapClientTemplateModifier(byteCodeInstrumentor, agent)); } - } + } - private void addMyBatisSupport() { + private void addMyBatisSupport() { if (profilerConfig.isMyBatisEnabled()) { addModifier(new DefaultSqlSessionModifier(byteCodeInstrumentor, agent)); addModifier(new SqlSessionTemplateModifier(byteCodeInstrumentor, agent)); diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/Modifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/Modifier.java index d58a749f0..ace3f4b96 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/Modifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/Modifier.java @@ -22,5 +22,5 @@ import java.security.ProtectionDomain; * @author emeroad */ public interface Modifier { - byte[] modify(ClassLoader classLoader, String className, ProtectionDomain protectedDomain, byte[] classFileBuffer); + byte[] modify(ClassLoader classLoader, String className, ProtectionDomain protectedDomain, byte[] classFileBuffer); } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/ArcusClientModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/ArcusClientModifier.java index ff70a54d7..b4d167a8d 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/ArcusClientModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/ArcusClientModifier.java @@ -40,31 +40,31 @@ import com.navercorp.pinpoint.profiler.modifier.arcus.interceptor.IndexParameter */ public class ArcusClientModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public ArcusClientModifier(ByteCodeInstrumentor byteCodeInstrumentor, - Agent agent) { - super(byteCodeInstrumentor, agent); - } + public ArcusClientModifier(ByteCodeInstrumentor byteCodeInstrumentor, + Agent agent) { + super(byteCodeInstrumentor, agent); + } - public String getTargetClass() { - return "net/spy/memcached/ArcusClient"; - } + public String getTargetClass() { + return "net/spy/memcached/ArcusClient"; + } - public byte[] modify(ClassLoader classLoader, String javassistClassName, - ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { + public byte[] modify(ClassLoader classLoader, String javassistClassName, + ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { logger.info("Modifing. {}", javassistClassName); - } + } - try { - InstrumentClass arcusClient = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + try { + InstrumentClass arcusClient = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); if (!checkCompatibility(arcusClient)) { return null; } - final Interceptor setCacheManagerInterceptor = byteCodeInstrumentor.newInterceptor(classLoader,protectedDomain,"com.navercorp.pinpoint.profiler.modifier.arcus.interceptor.SetCacheManagerInterceptor"); + final Interceptor setCacheManagerInterceptor = byteCodeInstrumentor.newInterceptor(classLoader,protectedDomain,"com.navercorp.pinpoint.profiler.modifier.arcus.interceptor.SetCacheManagerInterceptor"); final String[] args = {"net.spy.memcached.CacheManager"}; arcusClient.addInterceptor("setCacheManager", args, setCacheManagerInterceptor, Type.before); @@ -72,7 +72,7 @@ public class ArcusClientModifier extends AbstractModifier { for (MethodInfo method : declaredMethods) { SimpleAroundInterceptor apiInterceptor = (SimpleAroundInterceptor) byteCodeInstrumentor.newInterceptor(classLoader, protectedDomain, - "com.navercorp.pinpoint.profiler.modifier.arcus.interceptor.ApiInterceptor"); + "com.navercorp.pinpoint.profiler.modifier.arcus.interceptor.ApiInterceptor"); if (agent.getProfilerConfig().isArucsKeyTrace()) { final int index = ParameterUtils.findFirstString(method, 3); if (index != -1) { @@ -80,16 +80,16 @@ public class ArcusClientModifier extends AbstractModifier { } } arcusClient.addScopeInterceptor(method.getName(), method.getParameterTypes(), apiInterceptor, ArcusScope.SCOPE); - } + } - return arcusClient.toBytecode(); - } catch (Exception e) { - if (logger.isWarnEnabled()) { + return arcusClient.toBytecode(); + } catch (Exception e) { + if (logger.isWarnEnabled()) { logger.warn(e.getMessage(), e); - } - return null; - } - } + } + return null; + } + } private boolean checkCompatibility(InstrumentClass arcusClient) { // Check if the class has addOp method diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/MemcachedClientModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/MemcachedClientModifier.java index 927ce8424..1600b046f 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/MemcachedClientModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/MemcachedClientModifier.java @@ -40,32 +40,32 @@ import org.slf4j.LoggerFactory; */ public class MemcachedClientModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(MemcachedClientModifier.class.getName()); + private final Logger logger = LoggerFactory.getLogger(MemcachedClientModifier.class.getName()); - public MemcachedClientModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public MemcachedClientModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - public String getTargetClass() { - return "net/spy/memcached/MemcachedClient"; - } + public String getTargetClass() { + return "net/spy/memcached/MemcachedClient"; + } - public byte[] modify(ClassLoader classLoader, String javassistClassName, - ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } + public byte[] modify(ClassLoader classLoader, String javassistClassName, + ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } - try { - InstrumentClass aClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + try { + InstrumentClass aClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); String[] args = {"java.lang.String", "net.spy.memcached.ops.Operation"}; if (!checkCompatibility(aClass, args)) { return null; } - aClass.addTraceVariable("__serviceCode", "__setServiceCode", "__getServiceCode", "java.lang.String"); + aClass.addTraceVariable("__serviceCode", "__setServiceCode", "__getServiceCode", "java.lang.String"); - Interceptor addOpInterceptor = byteCodeInstrumentor.newInterceptor(classLoader, protectedDomain, + Interceptor addOpInterceptor = byteCodeInstrumentor.newInterceptor(classLoader, protectedDomain, "com.navercorp.pinpoint.profiler.modifier.arcus.interceptor.AddOpInterceptor"); aClass.addInterceptor("addOp", args, addOpInterceptor, Type.before); @@ -80,19 +80,19 @@ public class MemcachedClientModifier extends AbstractModifier { ((ParameterExtractorSupport)apiInterceptor).setParameterExtractor(new IndexParameterExtractor(index)); } } - aClass.addScopeInterceptor(method.getName(), method.getParameterTypes(), apiInterceptor, ArcusScope.SCOPE); - } - return aClass.toBytecode(); - } catch (Exception e) { - if (logger.isWarnEnabled()) { - logger.warn(e.getMessage(), e); - } - return null; - } - } + aClass.addScopeInterceptor(method.getName(), method.getParameterTypes(), apiInterceptor, ArcusScope.SCOPE); + } + return aClass.toBytecode(); + } catch (Exception e) { + if (logger.isWarnEnabled()) { + logger.warn(e.getMessage(), e); + } + return null; + } + } private boolean checkCompatibility(InstrumentClass aClass, String[] args) { - // if addOp exists, compatibility is okay for now. + // if addOp exists, compatibility is okay for now. final boolean addOp = aClass.hasDeclaredMethod("addOp", args); if (!addOp) { logger.warn("addOp() not found. skip MemcachedClientModifier"); diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/AddOpInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/AddOpInterceptor.java index 6fb725492..f9ad60b87 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/AddOpInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/AddOpInterceptor.java @@ -31,23 +31,23 @@ import net.spy.memcached.ops.Operation; */ public class AddOpInterceptor implements SimpleAroundInterceptor, TargetClassLoader { - private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); + private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); private final boolean isDebug = logger.isDebugEnabled(); - private MetaObject getServiceCode = new MetaObject("__getServiceCode"); - private MetaObject setServiceCode = new MetaObject("__setServiceCode", String.class); + private MetaObject getServiceCode = new MetaObject("__getServiceCode"); + private MetaObject setServiceCode = new MetaObject("__setServiceCode", String.class); - @Override - public void before(Object target, Object[] args) { - if (isDebug) { + @Override + public void before(Object target, Object[] args) { + if (isDebug) { logger.beforeInterceptor(target, args); - } + } - String serviceCode = getServiceCode.invoke(target); - Operation op = (Operation) args[1]; + String serviceCode = getServiceCode.invoke(target); + Operation op = (Operation) args[1]; - setServiceCode.invoke(op, serviceCode); - } + setServiceCode.invoke(op, serviceCode); + } @Override public void after(Object target, Object[] args, Object result, Throwable throwable) { diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/ApiInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/ApiInterceptor.java index 317928b4b..135218aff 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/ApiInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/ApiInterceptor.java @@ -44,9 +44,9 @@ public class ApiInterceptor extends SpanEventSimpleAroundInterceptor implements } @Override - public void doInBeforeTrace(RecordableTrace trace, final Object target, Object[] args) { - trace.markBeforeTime(); - } + public void doInBeforeTrace(RecordableTrace trace, final Object target, Object[] args) { + trace.markBeforeTime(); + } @Override public void doInAfterTrace(RecordableTrace trace, Object target, Object[] args, Object result, Throwable throwable) { diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/BaseOperationCancelInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/BaseOperationCancelInterceptor.java index d7d02c2bf..cc0251a63 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/BaseOperationCancelInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/BaseOperationCancelInterceptor.java @@ -32,34 +32,34 @@ import net.spy.memcached.protocol.BaseOperationImpl; @Deprecated public class BaseOperationCancelInterceptor implements SimpleAroundInterceptor { - private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); + private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); private final boolean isDebug = logger.isDebugEnabled(); - private MetaObject getAsyncTrace = new MetaObject("__getAsyncTrace"); + private MetaObject getAsyncTrace = new MetaObject("__getAsyncTrace"); - @Override - public void before(Object target, Object[] args) { - if (isDebug) { - logger.beforeInterceptor(target, args); - } + @Override + public void before(Object target, Object[] args) { + if (isDebug) { + logger.beforeInterceptor(target, args); + } - AsyncTrace asyncTrace = (AsyncTrace) getAsyncTrace.invoke(target); - if (asyncTrace == null) { - logger.debug("asyncTrace not found "); - return; - } + AsyncTrace asyncTrace = (AsyncTrace) getAsyncTrace.invoke(target); + if (asyncTrace == null) { + logger.debug("asyncTrace not found "); + return; + } - if (asyncTrace.getState() != DefaultAsyncTrace.STATE_INIT) { - // Operation already completed. - return; - } + if (asyncTrace.getState() != DefaultAsyncTrace.STATE_INIT) { + // Operation already completed. + return; + } - BaseOperationImpl baseOperation = (BaseOperationImpl) target; - if (!baseOperation.isCancelled()) { - TimeObject timeObject = (TimeObject) asyncTrace.getAttachObject(); - timeObject.markCancelTime(); - } - } + BaseOperationImpl baseOperation = (BaseOperationImpl) target; + if (!baseOperation.isCancelled()) { + TimeObject timeObject = (TimeObject) asyncTrace.getAttachObject(); + timeObject.markCancelTime(); + } + } @Override public void after(Object target, Object[] args, Object result, Throwable throwable) { diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/BaseOperationConstructInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/BaseOperationConstructInterceptor.java index 48d8666d8..8ed6f92fd 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/BaseOperationConstructInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/BaseOperationConstructInterceptor.java @@ -30,10 +30,10 @@ import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory; @Deprecated public class BaseOperationConstructInterceptor implements SimpleAroundInterceptor, TraceContextSupport { - private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); + private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); private final boolean isDebug = logger.isDebugEnabled(); -// private final MetaObject setAsyncTrace = new MetaObject("__setAsyncTrace", Object.class); +// private final MetaObject setAsyncTrace = new MetaObject("__setAsyncTrace", Object.class); private TraceContext traceContext; @@ -42,25 +42,25 @@ public class BaseOperationConstructInterceptor implements SimpleAroundIntercepto } @Override - public void after(Object target, Object[] args, Object result, Throwable throwable) { - if (isDebug) { + public void after(Object target, Object[] args, Object result, Throwable throwable) { + if (isDebug) { logger.afterInterceptor(target, args, result, throwable); - } + } - Trace trace = traceContext.currentTraceObject(); + Trace trace = traceContext.currentTraceObject(); - if (trace == null) { - return; - } + if (trace == null) { + return; + } - // Assuming no events are missed, do not process timeout. -// AsyncTrace asyncTrace = trace.createAsyncTrace(); -// asyncTrace.markBeforeTime(); + // Assuming no events are missed, do not process timeout. +// AsyncTrace asyncTrace = trace.createAsyncTrace(); +// asyncTrace.markBeforeTime(); // -// asyncTrace.setAttachObject(new TimeObject()); +// asyncTrace.setAttachObject(new TimeObject()); // -// setAsyncTrace.invoke(target, asyncTrace); - } +// setAsyncTrace.invoke(target, asyncTrace); + } @Override public void setTraceContext(TraceContext traceContext) { diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/BaseOperationTransitionStateInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/BaseOperationTransitionStateInterceptor.java index a8c288b24..d3608c7bf 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/BaseOperationTransitionStateInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/BaseOperationTransitionStateInterceptor.java @@ -44,101 +44,101 @@ import net.spy.memcached.protocol.BaseOperationImpl; @Deprecated public class BaseOperationTransitionStateInterceptor implements SimpleAroundInterceptor, ByteCodeMethodDescriptorSupport, TraceContextSupport { - private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); + private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); private final boolean isDebug = logger.isDebugEnabled(); - private static final Charset UTF8 = Charset.forName("UTF-8"); + private static final Charset UTF8 = Charset.forName("UTF-8"); - private MetaObject getAsyncTrace = new MetaObject("__getAsyncTrace"); - private MetaObject getServiceCode = new MetaObject("__getServiceCode"); + private MetaObject getAsyncTrace = new MetaObject("__getAsyncTrace"); + private MetaObject getServiceCode = new MetaObject("__getServiceCode"); private MethodDescriptor methodDescriptor; private TraceContext traceContext; @Override - public void before(Object target, Object[] args) { - if (isDebug) { - logger.beforeInterceptor(target, args); - } + public void before(Object target, Object[] args) { + if (isDebug) { + logger.beforeInterceptor(target, args); + } - AsyncTrace asyncTrace = (AsyncTrace) getAsyncTrace.invoke(target); - if (asyncTrace == null) { + AsyncTrace asyncTrace = (AsyncTrace) getAsyncTrace.invoke(target); + if (asyncTrace == null) { if (isDebug) { - logger.debug("asyncTrace not found"); + logger.debug("asyncTrace not found"); } - return; - } + return; + } // TODO Don't we have to check null? Don't fix now because this interceptor is deprecated. - OperationState newState = (OperationState) args[0]; + OperationState newState = (OperationState) args[0]; - BaseOperationImpl baseOperation = (BaseOperationImpl) target; - if (newState == OperationState.READING) { - if (isDebug) { - logger.debug("event:{} asyncTrace:{}", newState, asyncTrace); - } - if (asyncTrace.getState() != AsyncTrace.STATE_INIT) { - return; - } - MemcachedNode handlingNode = baseOperation.getHandlingNode(); - SocketAddress socketAddress = handlingNode.getSocketAddress(); - if (socketAddress instanceof InetSocketAddress) { - InetSocketAddress address = (InetSocketAddress) socketAddress; - asyncTrace.recordEndPoint(address.getHostName() + ":" + address.getPort()); - } + BaseOperationImpl baseOperation = (BaseOperationImpl) target; + if (newState == OperationState.READING) { + if (isDebug) { + logger.debug("event:{} asyncTrace:{}", newState, asyncTrace); + } + if (asyncTrace.getState() != AsyncTrace.STATE_INIT) { + return; + } + MemcachedNode handlingNode = baseOperation.getHandlingNode(); + SocketAddress socketAddress = handlingNode.getSocketAddress(); + if (socketAddress instanceof InetSocketAddress) { + InetSocketAddress address = (InetSocketAddress) socketAddress; + asyncTrace.recordEndPoint(address.getHostName() + ":" + address.getPort()); + } - String serviceCode = (String) getServiceCode.invoke(target); + String serviceCode = (String) getServiceCode.invoke(target); - if (serviceCode == null) { - serviceCode = "UNKNOWN"; - } - - ServiceType svcType = ServiceType.ARCUS; - - if(serviceCode.equals(ServiceType.MEMCACHED.getDesc())) { - svcType = ServiceType.MEMCACHED; - } + if (serviceCode == null) { + serviceCode = "UNKNOWN"; + } + + ServiceType svcType = ServiceType.ARCUS; + + if(serviceCode.equals(ServiceType.MEMCACHED.getDesc())) { + svcType = ServiceType.MEMCACHED; + } asyncTrace.recordServiceType(svcType); -// asyncTrace.recordRpcName(baseOperation.getClass().getSimpleName()); +// asyncTrace.recordRpcName(baseOperation.getClass().getSimpleName()); asyncTrace.recordApi(methodDescriptor); asyncTrace.recordDestinationId(serviceCode); - String cmd = getCommand(baseOperation); -// asyncTrace.recordAttribute(AnnotationKey.ARCUS_COMMAND, cmd); + String cmd = getCommand(baseOperation); +// asyncTrace.recordAttribute(AnnotationKey.ARCUS_COMMAND, cmd); - // TimeObject timeObject = (TimeObject) - // asyncTrace.getFrameObject(); - // timeObject.markSendTime(); + // TimeObject timeObject = (TimeObject) + // asyncTrace.getFrameObject(); + // timeObject.markSendTime(); - // long createTime = asyncTrace.getBeforeTime(); - asyncTrace.markAfterTime(); -// asyncTrace.traceBlockEnd(); - } else if (newState == OperationState.COMPLETE || isArcusTimeout(newState)) { - if (isDebug) { + // long createTime = asyncTrace.getBeforeTime(); + asyncTrace.markAfterTime(); +// asyncTrace.traceBlockEnd(); + } else if (newState == OperationState.COMPLETE || isArcusTimeout(newState)) { + if (isDebug) { logger.debug("event:{} asyncTrace:{}", newState, asyncTrace); - } - boolean fire = asyncTrace.fire(); - if (!fire) { - return; - } - Exception exception = baseOperation.getException(); + } + boolean fire = asyncTrace.fire(); + if (!fire) { + return; + } + Exception exception = baseOperation.getException(); asyncTrace.recordException(exception); - if (!baseOperation.isCancelled()) { - TimeObject timeObject = (TimeObject) asyncTrace.getAttachObject(); - // asyncTrace.record(Annotation.ClientRecv, timeObject.getSendTime()); - asyncTrace.markAfterTime(); - asyncTrace.traceBlockEnd(); - } else { - asyncTrace.recordAttribute(AnnotationKey.EXCEPTION, "cancelled by user"); - TimeObject timeObject = (TimeObject) asyncTrace.getAttachObject(); - // asyncTrace.record(Annotation.ClientRecv, timeObject.getCancelTime()); - asyncTrace.markAfterTime(); - asyncTrace.traceBlockEnd(); - } - } - } + if (!baseOperation.isCancelled()) { + TimeObject timeObject = (TimeObject) asyncTrace.getAttachObject(); + // asyncTrace.record(Annotation.ClientRecv, timeObject.getSendTime()); + asyncTrace.markAfterTime(); + asyncTrace.traceBlockEnd(); + } else { + asyncTrace.recordAttribute(AnnotationKey.EXCEPTION, "cancelled by user"); + TimeObject timeObject = (TimeObject) asyncTrace.getAttachObject(); + // asyncTrace.record(Annotation.ClientRecv, timeObject.getCancelTime()); + asyncTrace.markAfterTime(); + asyncTrace.traceBlockEnd(); + } + } + } private boolean isArcusTimeout(OperationState newState) { if (newState == null) { @@ -150,15 +150,15 @@ public class BaseOperationTransitionStateInterceptor implements SimpleAroundInte } private String getCommand(BaseOperationImpl baseOperation) { - ByteBuffer buffer = baseOperation.getBuffer(); - if (buffer == null) { - return "UNKNOWN"; - } - // System.out.println(buffer.array().length + " po:" + buffer.position() - // + " limit:" + buffer.limit() + " remaining" - // + buffer.remaining() + " aoffset:" + buffer.arrayOffset()); - return new String(buffer.array(), UTF8); - } + ByteBuffer buffer = baseOperation.getBuffer(); + if (buffer == null) { + return "UNKNOWN"; + } + // System.out.println(buffer.array().length + " po:" + buffer.position() + // + " limit:" + buffer.limit() + " remaining" + // + buffer.remaining() + " aoffset:" + buffer.arrayOffset()); + return new String(buffer.array(), UTF8); + } @Override public void setMethodDescriptor(MethodDescriptor descriptor) { diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/CacheManagerConstructInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/CacheManagerConstructInterceptor.java index 033c3732f..d41c21922 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/CacheManagerConstructInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/CacheManagerConstructInterceptor.java @@ -28,22 +28,22 @@ import com.navercorp.pinpoint.bootstrap.util.MetaObject; */ public class CacheManagerConstructInterceptor implements SimpleAroundInterceptor { - private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); + private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); private final boolean isDebug = logger.isDebugEnabled(); - private MetaObject setServiceCode = new MetaObject("__setServiceCode", String.class); + private MetaObject setServiceCode = new MetaObject("__setServiceCode", String.class); @Override public void before(Object target, Object[] args) { } - @Override - public void after(Object target, Object[] args, Object result, Throwable throwable) { - if (isDebug) { + @Override + public void after(Object target, Object[] args, Object result, Throwable throwable) { + if (isDebug) { logger.afterInterceptor(target, args, result, throwable); - } + } - setServiceCode.invoke(target, (String) args[1]); - } + setServiceCode.invoke(target, (String) args[1]); + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureGetInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureGetInterceptor.java index b14ef142e..6d6f25caf 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureGetInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureGetInterceptor.java @@ -35,7 +35,7 @@ import net.spy.memcached.ops.Operation; */ public class FutureGetInterceptor implements SimpleAroundInterceptor, ByteCodeMethodDescriptorSupport, TraceContextSupport, TargetClassLoader { - private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); + private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); private final boolean isDebug = logger.isDebugEnabled(); private MetaObject getOperation = new MetaObject("__getOperation"); @@ -45,30 +45,30 @@ public class FutureGetInterceptor implements SimpleAroundInterceptor, ByteCodeMe private TraceContext traceContext; @Override - public void before(Object target, Object[] args) { - if (isDebug) { - logger.beforeInterceptor(target, args); - } + public void before(Object target, Object[] args) { + if (isDebug) { + logger.beforeInterceptor(target, args); + } - final Trace trace = traceContext.currentTraceObject(); - if (trace == null) { + final Trace trace = traceContext.currentTraceObject(); + if (trace == null) { return; - } - - trace.traceBlockBegin(); - trace.markBeforeTime(); - } + } + + trace.traceBlockBegin(); + trace.markBeforeTime(); + } @Override public void after(Object target, Object[] args, Object result, Throwable throwable) { - if (isDebug) { - logger.afterInterceptor(target, args, result, throwable); - } + if (isDebug) { + logger.afterInterceptor(target, args, result, throwable); + } - final Trace trace = traceContext.currentTraceObject(); - if (trace == null) { - return; - } + final Trace trace = traceContext.currentTraceObject(); + if (trace == null) { + return; + } try { trace.recordApi(methodDescriptor); diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureSetOperationInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureSetOperationInterceptor.java index 59975a729..cdee21a18 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureSetOperationInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureSetOperationInterceptor.java @@ -31,20 +31,20 @@ import net.spy.memcached.ops.Operation; */ public class FutureSetOperationInterceptor implements SimpleAroundInterceptor, TargetClassLoader { - private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); + private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); private final boolean isDebug = logger.isDebugEnabled(); private MetaObject setOperation = new MetaObject("__setOperation", Operation.class); @Override - public void before(Object target, Object[] args) { - if (isDebug) { - logger.beforeInterceptor(target, args); - } + public void before(Object target, Object[] args) { + if (isDebug) { + logger.beforeInterceptor(target, args); + } - setOperation.invoke(target, (Operation) args[0]); - } + setOperation.invoke(target, (Operation) args[0]); + } @Override public void after(Object target, Object[] args, Object result, Throwable throwable) { diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/SetCacheManagerInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/SetCacheManagerInterceptor.java index db8bae277..ecc380bfe 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/SetCacheManagerInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/SetCacheManagerInterceptor.java @@ -32,23 +32,23 @@ import net.spy.memcached.MemcachedClient; */ public class SetCacheManagerInterceptor implements SimpleAroundInterceptor, TargetClassLoader { - private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); + private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); private final boolean isDebug = logger.isDebugEnabled(); - private MetaObject getServiceCode = new MetaObject("__getServiceCode"); - private MetaObject setServiceCode = new MetaObject("__setServiceCode", String.class); + private MetaObject getServiceCode = new MetaObject("__getServiceCode"); + private MetaObject setServiceCode = new MetaObject("__setServiceCode", String.class); - @Override - public void before(Object target, Object[] args) { - if (isDebug) { - logger.beforeInterceptor(target, args); - } - - CacheManager cm = (CacheManager) args[0]; - String serviceCode = getServiceCode.invoke(cm); - - setServiceCode.invoke((MemcachedClient) target, serviceCode); - } + @Override + public void before(Object target, Object[] args) { + if (isDebug) { + logger.beforeInterceptor(target, args); + } + + CacheManager cm = (CacheManager) args[0]; + String serviceCode = getServiceCode.invoke(cm); + + setServiceCode.invoke((MemcachedClient) target, serviceCode); + } @Override public void after(Object target, Object[] args, Object result, Throwable throwable) { diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/asynchttpclient/AsyncHttpClientModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/asynchttpclient/AsyncHttpClientModifier.java index e913d0115..155abca42 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/asynchttpclient/AsyncHttpClientModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/asynchttpclient/AsyncHttpClientModifier.java @@ -35,32 +35,32 @@ import com.navercorp.pinpoint.profiler.modifier.AbstractModifier; * */ public class AsyncHttpClientModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public AsyncHttpClientModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public AsyncHttpClientModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - public String getTargetClass() { - return "com/ning/http/client/AsyncHttpClient"; - } + public String getTargetClass() { + return "com/ning/http/client/AsyncHttpClient"; + } - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } - try { - InstrumentClass aClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + try { + InstrumentClass aClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); - Interceptor executeRequestInterceptor = byteCodeInstrumentor.newInterceptor(classLoader, protectedDomain, "com.navercorp.pinpoint.profiler.modifier.connector.asynchttpclient.interceptor.ExecuteRequestInterceptor"); - aClass.addInterceptor("executeRequest", new String[] { "com.ning.http.client.Request", "com.ning.http.client.AsyncHandler" }, executeRequestInterceptor); + Interceptor executeRequestInterceptor = byteCodeInstrumentor.newInterceptor(classLoader, protectedDomain, "com.navercorp.pinpoint.profiler.modifier.connector.asynchttpclient.interceptor.ExecuteRequestInterceptor"); + aClass.addInterceptor("executeRequest", new String[] { "com.ning.http.client.Request", "com.ning.http.client.AsyncHandler" }, executeRequestInterceptor); - return aClass.toBytecode(); - } catch (Throwable e) { - logger.warn("httpClient4 modifier error. Caused:{}", e.getMessage(), e); - return null; - } - } + return aClass.toBytecode(); + } catch (Throwable e) { + logger.warn("httpClient4 modifier error. Caused:{}", e.getMessage(), e); + return null; + } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/asynchttpclient/interceptor/ExecuteRequestInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/asynchttpclient/interceptor/ExecuteRequestInterceptor.java index 314a64f48..37298c05d 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/asynchttpclient/interceptor/ExecuteRequestInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/asynchttpclient/interceptor/ExecuteRequestInterceptor.java @@ -54,354 +54,354 @@ import com.ning.http.client.cookie.Cookie; */ public class ExecuteRequestInterceptor implements SimpleAroundInterceptor, ByteCodeMethodDescriptorSupport, TraceContextSupport, TargetClassLoader { - protected final PLogger logger = PLoggerFactory.getLogger(ExecuteRequestInterceptor.class); - protected final boolean isDebug = logger.isDebugEnabled(); + protected final PLogger logger = PLoggerFactory.getLogger(ExecuteRequestInterceptor.class); + protected final boolean isDebug = logger.isDebugEnabled(); - protected TraceContext traceContext; - protected MethodDescriptor descriptor; + protected TraceContext traceContext; + protected MethodDescriptor descriptor; - protected boolean dumpCookie; - protected DumpType cookieDumpType; - protected SimpleSampler cookieSampler; - protected int cookieDumpSize; + protected boolean dumpCookie; + protected DumpType cookieDumpType; + protected SimpleSampler cookieSampler; + protected int cookieDumpSize; - protected boolean dumpEntity; - protected DumpType entityDumpType; - protected SimpleSampler entitySampler; - protected int entityDumpSize; + protected boolean dumpEntity; + protected DumpType entityDumpType; + protected SimpleSampler entitySampler; + protected int entityDumpSize; - protected boolean dumpParam; - protected DumpType paramDumpType; - protected SimpleSampler paramSampler; - protected int paramDumpSize; + protected boolean dumpParam; + protected DumpType paramDumpType; + protected SimpleSampler paramSampler; + protected int paramDumpSize; @Override - public void before(Object target, Object[] args) { - if (isDebug) { - logger.beforeInterceptor(target, args); - } + public void before(Object target, Object[] args) { + if (isDebug) { + logger.beforeInterceptor(target, args); + } - final Trace trace = traceContext.currentRawTraceObject(); - if (trace == null) { - return; - } + final Trace trace = traceContext.currentRawTraceObject(); + if (trace == null) { + return; + } - if (args.length == 0 || !(args[0] instanceof com.ning.http.client.Request)) { - return; - } + if (args.length == 0 || !(args[0] instanceof com.ning.http.client.Request)) { + return; + } - final com.ning.http.client.Request httpRequest = (com.ning.http.client.Request) args[0]; + final com.ning.http.client.Request httpRequest = (com.ning.http.client.Request) args[0]; - final boolean sampling = trace.canSampled(); + final boolean sampling = trace.canSampled(); - if (!sampling) { - if (isDebug) { - logger.debug("set Sampling flag=false"); - } - if (httpRequest != null) { + if (!sampling) { + if (isDebug) { + logger.debug("set Sampling flag=false"); + } + if (httpRequest != null) { final FluentCaseInsensitiveStringsMap httpRequestHeaders = httpRequest.getHeaders(); - httpRequestHeaders.add(Header.HTTP_SAMPLED.toString(), SamplingFlagUtils.SAMPLING_RATE_FALSE); - } - return; - } + httpRequestHeaders.add(Header.HTTP_SAMPLED.toString(), SamplingFlagUtils.SAMPLING_RATE_FALSE); + } + return; + } - trace.traceBlockBegin(); - trace.markBeforeTime(); + trace.traceBlockBegin(); + trace.markBeforeTime(); - TraceId nextId = trace.getTraceId().getNextTraceId(); - trace.recordNextSpanId(nextId.getSpanId()); - trace.recordServiceType(ServiceType.HTTP_CLIENT); + TraceId nextId = trace.getTraceId().getNextTraceId(); + trace.recordNextSpanId(nextId.getSpanId()); + trace.recordServiceType(ServiceType.HTTP_CLIENT); - if (httpRequest != null) { + if (httpRequest != null) { final FluentCaseInsensitiveStringsMap httpRequestHeaders = httpRequest.getHeaders(); - putHeader(httpRequestHeaders, Header.HTTP_TRACE_ID.toString(), nextId.getTransactionId()); - putHeader(httpRequestHeaders, Header.HTTP_SPAN_ID.toString(), String.valueOf(nextId.getSpanId())); - putHeader(httpRequestHeaders, Header.HTTP_PARENT_SPAN_ID.toString(), String.valueOf(nextId.getParentSpanId())); - putHeader(httpRequestHeaders, Header.HTTP_FLAGS.toString(), String.valueOf(nextId.getFlags())); - putHeader(httpRequestHeaders, Header.HTTP_PARENT_APPLICATION_NAME.toString(), traceContext.getApplicationName()); - putHeader(httpRequestHeaders, Header.HTTP_PARENT_APPLICATION_TYPE.toString(), Short.toString(traceContext.getServerTypeCode())); - } - } + putHeader(httpRequestHeaders, Header.HTTP_TRACE_ID.toString(), nextId.getTransactionId()); + putHeader(httpRequestHeaders, Header.HTTP_SPAN_ID.toString(), String.valueOf(nextId.getSpanId())); + putHeader(httpRequestHeaders, Header.HTTP_PARENT_SPAN_ID.toString(), String.valueOf(nextId.getParentSpanId())); + putHeader(httpRequestHeaders, Header.HTTP_FLAGS.toString(), String.valueOf(nextId.getFlags())); + putHeader(httpRequestHeaders, Header.HTTP_PARENT_APPLICATION_NAME.toString(), traceContext.getApplicationName()); + putHeader(httpRequestHeaders, Header.HTTP_PARENT_APPLICATION_TYPE.toString(), Short.toString(traceContext.getServerTypeCode())); + } + } - private void putHeader(FluentCaseInsensitiveStringsMap httpRequestHeaders, String key, String value) { - final List valueList = new ArrayList(); - valueList.add(value); - httpRequestHeaders.put(key, valueList); - } + private void putHeader(FluentCaseInsensitiveStringsMap httpRequestHeaders, String key, String value) { + final List valueList = new ArrayList(); + valueList.add(value); + httpRequestHeaders.put(key, valueList); + } - @Override - public void after(Object target, Object[] args, Object result, Throwable throwable) { - if (isDebug) { - // Do not log result - logger.afterInterceptor(target, args); - } + @Override + public void after(Object target, Object[] args, Object result, Throwable throwable) { + if (isDebug) { + // Do not log result + logger.afterInterceptor(target, args); + } - final Trace trace = traceContext.currentTraceObject(); - if (trace == null) { - return; - } + final Trace trace = traceContext.currentTraceObject(); + if (trace == null) { + return; + } - if (args.length == 0 || !(args[0] instanceof com.ning.http.client.Request)) { - return; - } + if (args.length == 0 || !(args[0] instanceof com.ning.http.client.Request)) { + return; + } - try { - final com.ning.http.client.Request httpRequest = (com.ning.http.client.Request) args[0]; + try { + final com.ning.http.client.Request httpRequest = (com.ning.http.client.Request) args[0]; - if (httpRequest != null) { - // Accessing httpRequest here not before() becuase it can cause side effect. - trace.recordAttribute(AnnotationKey.HTTP_URL, httpRequest.getUrl()); + if (httpRequest != null) { + // Accessing httpRequest here not before() becuase it can cause side effect. + trace.recordAttribute(AnnotationKey.HTTP_URL, httpRequest.getUrl()); - String endpoint = getEndpoint(httpRequest.getURI().getHost(), httpRequest.getURI().getPort()); - trace.recordDestinationId(endpoint); + String endpoint = getEndpoint(httpRequest.getURI().getHost(), httpRequest.getURI().getPort()); + trace.recordDestinationId(endpoint); - recordHttpRequest(trace, httpRequest, throwable); - } + recordHttpRequest(trace, httpRequest, throwable); + } - trace.recordApi(descriptor); - trace.recordException(throwable); - trace.markAfterTime(); - } finally { - trace.traceBlockEnd(); - } - } + trace.recordApi(descriptor); + trace.recordException(throwable); + trace.markAfterTime(); + } finally { + trace.traceBlockEnd(); + } + } - private String getEndpoint(String host, int port) { - if (host == null) { - return "UnknownHttpClient"; - } - if (port < 0) { - return host; - } - final StringBuilder sb = new StringBuilder(host.length() + 8); - sb.append(host); - sb.append(':'); - sb.append(port); - return sb.toString(); - } + private String getEndpoint(String host, int port) { + if (host == null) { + return "UnknownHttpClient"; + } + if (port < 0) { + return host; + } + final StringBuilder sb = new StringBuilder(host.length() + 8); + sb.append(host); + sb.append(':'); + sb.append(port); + return sb.toString(); + } - private void recordHttpRequest(Trace trace, com.ning.http.client.Request httpRequest, Throwable throwable) { - final boolean isException = InterceptorUtils.isThrowable(throwable); - if (dumpCookie) { - if (DumpType.ALWAYS == cookieDumpType) { - recordCookie(httpRequest, trace); - } else if (DumpType.EXCEPTION == cookieDumpType && isException) { - recordCookie(httpRequest, trace); - } - } - if (dumpEntity) { - if (DumpType.ALWAYS == entityDumpType) { - recordEntity(httpRequest, trace); - } else if (DumpType.EXCEPTION == entityDumpType && isException) { - recordEntity(httpRequest, trace); - } - } - if (dumpParam) { - if (DumpType.ALWAYS == paramDumpType) { - recordParam(httpRequest, trace); - } else if (DumpType.EXCEPTION == paramDumpType && isException) { - recordParam(httpRequest, trace); - } - } - } + private void recordHttpRequest(Trace trace, com.ning.http.client.Request httpRequest, Throwable throwable) { + final boolean isException = InterceptorUtils.isThrowable(throwable); + if (dumpCookie) { + if (DumpType.ALWAYS == cookieDumpType) { + recordCookie(httpRequest, trace); + } else if (DumpType.EXCEPTION == cookieDumpType && isException) { + recordCookie(httpRequest, trace); + } + } + if (dumpEntity) { + if (DumpType.ALWAYS == entityDumpType) { + recordEntity(httpRequest, trace); + } else if (DumpType.EXCEPTION == entityDumpType && isException) { + recordEntity(httpRequest, trace); + } + } + if (dumpParam) { + if (DumpType.ALWAYS == paramDumpType) { + recordParam(httpRequest, trace); + } else if (DumpType.EXCEPTION == paramDumpType && isException) { + recordParam(httpRequest, trace); + } + } + } - protected void recordCookie(com.ning.http.client.Request httpRequest, Trace trace) { - if (cookieSampler.isSampling()) { - Collection cookies = httpRequest.getCookies(); + protected void recordCookie(com.ning.http.client.Request httpRequest, Trace trace) { + if (cookieSampler.isSampling()) { + Collection cookies = httpRequest.getCookies(); - if (cookies.isEmpty()) { - return; - } + if (cookies.isEmpty()) { + return; + } - StringBuilder sb = new StringBuilder(cookieDumpSize * 2); - Iterator iterator = cookies.iterator(); - while (iterator.hasNext()) { - Cookie cookie = iterator.next(); - sb.append(cookie.getName()).append("=").append(cookie.getValue()); - if (iterator.hasNext()) { - sb.append(","); - } - } - trace.recordAttribute(AnnotationKey.HTTP_COOKIE, StringUtils.drop(sb.toString(), cookieDumpSize)); - } - } + StringBuilder sb = new StringBuilder(cookieDumpSize * 2); + Iterator iterator = cookies.iterator(); + while (iterator.hasNext()) { + Cookie cookie = iterator.next(); + sb.append(cookie.getName()).append("=").append(cookie.getValue()); + if (iterator.hasNext()) { + sb.append(","); + } + } + trace.recordAttribute(AnnotationKey.HTTP_COOKIE, StringUtils.drop(sb.toString(), cookieDumpSize)); + } + } - protected void recordEntity(final com.ning.http.client.Request httpRequest, final Trace trace) { - if (entitySampler.isSampling()) { - recordNonMultipartData(httpRequest, trace); - recordMultipartData(httpRequest, trace); - } - } + protected void recordEntity(final com.ning.http.client.Request httpRequest, final Trace trace) { + if (entitySampler.isSampling()) { + recordNonMultipartData(httpRequest, trace); + recordMultipartData(httpRequest, trace); + } + } - /** - *
-	 * Body could be String, byte array, Stream or EntityWriter.
-	 * We collect String data only.
-	 * 
- * - * @param httpRequest - * @param trace - */ - protected void recordNonMultipartData(final com.ning.http.client.Request httpRequest, final Trace trace) { - final String stringData = httpRequest.getStringData(); - if (stringData != null) { - trace.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, StringUtils.drop(stringData, entityDumpSize)); - return; - } + /** + *
+     * Body could be String, byte array, Stream or EntityWriter.
+     * We collect String data only.
+     * 
+ * + * @param httpRequest + * @param trace + */ + protected void recordNonMultipartData(final com.ning.http.client.Request httpRequest, final Trace trace) { + final String stringData = httpRequest.getStringData(); + if (stringData != null) { + trace.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, StringUtils.drop(stringData, entityDumpSize)); + return; + } - final byte[] byteData = httpRequest.getByteData(); - if (byteData != null) { - trace.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, "BYTE_DATA"); - return; - } + final byte[] byteData = httpRequest.getByteData(); + if (byteData != null) { + trace.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, "BYTE_DATA"); + return; + } - final InputStream streamData = httpRequest.getStreamData(); - if (streamData != null) { - trace.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, "STREAM_DATA"); - return; - } + final InputStream streamData = httpRequest.getStreamData(); + if (streamData != null) { + trace.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, "STREAM_DATA"); + return; + } - final EntityWriter entityWriter = httpRequest.getEntityWriter(); - if (entityWriter != null) { - trace.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, "STREAM_DATA"); - return; - } - } + final EntityWriter entityWriter = httpRequest.getEntityWriter(); + if (entityWriter != null) { + trace.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, "STREAM_DATA"); + return; + } + } - /** - * record http multipart data - * - * @param httpRequest - * @param trace - */ - protected void recordMultipartData(final com.ning.http.client.Request httpRequest, final Trace trace) { - List parts = httpRequest.getParts(); - if (parts != null && parts.isEmpty()) { - StringBuilder sb = new StringBuilder(entityDumpSize * 2); - Iterator iterator = parts.iterator(); - while (iterator.hasNext()) { - Part part = iterator.next(); - if (part instanceof com.ning.http.client.ByteArrayPart) { - com.ning.http.client.ByteArrayPart p = (com.ning.http.client.ByteArrayPart) part; - sb.append(part.getName()); - sb.append("=BYTE_ARRAY_"); - sb.append(p.getData().length); - } else if (part instanceof com.ning.http.client.FilePart) { - com.ning.http.client.FilePart p = (com.ning.http.client.FilePart) part; - sb.append(part.getName()); - sb.append("=FILE_"); - sb.append(p.getMimeType()); - } else if (part instanceof com.ning.http.client.StringPart) { - com.ning.http.client.StringPart p = (com.ning.http.client.StringPart) part; - sb.append(part.getName()); - sb.append("="); - sb.append(p.getValue()); - } else if (part instanceof com.ning.http.multipart.FilePart) { - com.ning.http.multipart.FilePart p = (com.ning.http.multipart.FilePart) part; - sb.append(part.getName()); - sb.append("=FILE_"); - sb.append(p.getContentType()); - } else if (part instanceof com.ning.http.multipart.StringPart) { - com.ning.http.multipart.StringPart p = (com.ning.http.multipart.StringPart) part; - sb.append(part.getName()); - // Ignore value because there's no way to get string value and StringPart is an adaptation class of Apache HTTP client. - sb.append("=STRING"); - } + /** + * record http multipart data + * + * @param httpRequest + * @param trace + */ + protected void recordMultipartData(final com.ning.http.client.Request httpRequest, final Trace trace) { + List parts = httpRequest.getParts(); + if (parts != null && parts.isEmpty()) { + StringBuilder sb = new StringBuilder(entityDumpSize * 2); + Iterator iterator = parts.iterator(); + while (iterator.hasNext()) { + Part part = iterator.next(); + if (part instanceof com.ning.http.client.ByteArrayPart) { + com.ning.http.client.ByteArrayPart p = (com.ning.http.client.ByteArrayPart) part; + sb.append(part.getName()); + sb.append("=BYTE_ARRAY_"); + sb.append(p.getData().length); + } else if (part instanceof com.ning.http.client.FilePart) { + com.ning.http.client.FilePart p = (com.ning.http.client.FilePart) part; + sb.append(part.getName()); + sb.append("=FILE_"); + sb.append(p.getMimeType()); + } else if (part instanceof com.ning.http.client.StringPart) { + com.ning.http.client.StringPart p = (com.ning.http.client.StringPart) part; + sb.append(part.getName()); + sb.append("="); + sb.append(p.getValue()); + } else if (part instanceof com.ning.http.multipart.FilePart) { + com.ning.http.multipart.FilePart p = (com.ning.http.multipart.FilePart) part; + sb.append(part.getName()); + sb.append("=FILE_"); + sb.append(p.getContentType()); + } else if (part instanceof com.ning.http.multipart.StringPart) { + com.ning.http.multipart.StringPart p = (com.ning.http.multipart.StringPart) part; + sb.append(part.getName()); + // Ignore value because there's no way to get string value and StringPart is an adaptation class of Apache HTTP client. + sb.append("=STRING"); + } - if (sb.length() >= entityDumpSize) { - break; - } + if (sb.length() >= entityDumpSize) { + break; + } - if (iterator.hasNext()) { - sb.append(","); - } - } - trace.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, StringUtils.drop(sb.toString(), entityDumpSize)); - } - } + if (iterator.hasNext()) { + sb.append(","); + } + } + trace.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, StringUtils.drop(sb.toString(), entityDumpSize)); + } + } - /** - * record http request parameter - * - * @param httpRequest - * @param trace - */ - protected void recordParam(final com.ning.http.client.Request httpRequest, final Trace trace) { - if (paramSampler.isSampling()) { - FluentStringsMap requestParams = httpRequest.getParams(); - if (requestParams != null) { - String params = paramsToString(requestParams, paramDumpSize); - trace.recordAttribute(AnnotationKey.HTTP_PARAM, StringUtils.drop(params, paramDumpSize)); - } - } - } + /** + * record http request parameter + * + * @param httpRequest + * @param trace + */ + protected void recordParam(final com.ning.http.client.Request httpRequest, final Trace trace) { + if (paramSampler.isSampling()) { + FluentStringsMap requestParams = httpRequest.getParams(); + if (requestParams != null) { + String params = paramsToString(requestParams, paramDumpSize); + trace.recordAttribute(AnnotationKey.HTTP_PARAM, StringUtils.drop(params, paramDumpSize)); + } + } + } - /** - * Returns string without double quotations marks, spaces, semi-colons from com.ning.http.client.FluentStringsMap.toString() - * - * @param params - * @param limit - * @return - */ - private String paramsToString(FluentStringsMap params, int limit) { - StringBuilder result = new StringBuilder(limit * 2); + /** + * Returns string without double quotations marks, spaces, semi-colons from com.ning.http.client.FluentStringsMap.toString() + * + * @param params + * @param limit + * @return + */ + private String paramsToString(FluentStringsMap params, int limit) { + StringBuilder result = new StringBuilder(limit * 2); - for (Map.Entry> entry : params.entrySet()) { - if (result.length() > 0) { - result.append(","); - } - result.append(entry.getKey()); - result.append("="); + for (Map.Entry> entry : params.entrySet()) { + if (result.length() > 0) { + result.append(","); + } + result.append(entry.getKey()); + result.append("="); - boolean needsComma = false; + boolean needsComma = false; - for (String value : entry.getValue()) { - if (needsComma) { - result.append(", "); - } else { - needsComma = true; - } - result.append(value); - } - - if (result.length() >= limit) { - break; - } - } - return result.toString(); - } + for (String value : entry.getValue()) { + if (needsComma) { + result.append(", "); + } else { + needsComma = true; + } + result.append(value); + } - @Override - public void setTraceContext(TraceContext traceContext) { - this.traceContext = traceContext; + if (result.length() >= limit) { + break; + } + } + return result.toString(); + } - final ProfilerConfig profilerConfig = traceContext.getProfilerConfig(); - this.dumpCookie = profilerConfig.isNingAsyncHttpClientProfileCookie(); - this.cookieDumpType = profilerConfig.getNingAsyncHttpClientProfileCookieDumpType(); - this.cookieDumpSize = profilerConfig.getNingAsyncHttpClientProfileCookieDumpSize(); - if (dumpCookie) { - this.cookieSampler = SimpleSamplerFactory.createSampler(dumpCookie, profilerConfig.getNingAsyncHttpClientProfileCookieSamplingRate()); - } + @Override + public void setTraceContext(TraceContext traceContext) { + this.traceContext = traceContext; - this.dumpEntity = profilerConfig.isNingAsyncHttpClientProfileEntity(); - this.entityDumpType = profilerConfig.getNingAsyncHttpClientProfileEntityDumpType(); - this.entityDumpSize = profilerConfig.getNingAsyncHttpClientProfileEntityDumpSize(); - if (dumpEntity) { - this.entitySampler = SimpleSamplerFactory.createSampler(dumpEntity, profilerConfig.getNingAsyncHttpClientProfileEntitySamplingRate()); - } + final ProfilerConfig profilerConfig = traceContext.getProfilerConfig(); + this.dumpCookie = profilerConfig.isNingAsyncHttpClientProfileCookie(); + this.cookieDumpType = profilerConfig.getNingAsyncHttpClientProfileCookieDumpType(); + this.cookieDumpSize = profilerConfig.getNingAsyncHttpClientProfileCookieDumpSize(); + if (dumpCookie) { + this.cookieSampler = SimpleSamplerFactory.createSampler(dumpCookie, profilerConfig.getNingAsyncHttpClientProfileCookieSamplingRate()); + } - this.dumpParam = profilerConfig.isNingAsyncHttpClientProfileParam(); - this.paramDumpType = profilerConfig.getNingAsyncHttpClientProfileParamDumpType(); - this.paramDumpSize = profilerConfig.getNingAsyncHttpClientProfileParamDumpSize(); - if (dumpParam) { - this.paramSampler = SimpleSamplerFactory.createSampler(dumpParam, profilerConfig.getNingAsyncHttpClientProfileParamSamplingRate()); - } - } + this.dumpEntity = profilerConfig.isNingAsyncHttpClientProfileEntity(); + this.entityDumpType = profilerConfig.getNingAsyncHttpClientProfileEntityDumpType(); + this.entityDumpSize = profilerConfig.getNingAsyncHttpClientProfileEntityDumpSize(); + if (dumpEntity) { + this.entitySampler = SimpleSamplerFactory.createSampler(dumpEntity, profilerConfig.getNingAsyncHttpClientProfileEntitySamplingRate()); + } - @Override - public void setMethodDescriptor(MethodDescriptor descriptor) { - this.descriptor = descriptor; - traceContext.cacheApi(descriptor); - } + this.dumpParam = profilerConfig.isNingAsyncHttpClientProfileParam(); + this.paramDumpType = profilerConfig.getNingAsyncHttpClientProfileParamDumpType(); + this.paramDumpSize = profilerConfig.getNingAsyncHttpClientProfileParamDumpSize(); + if (dumpParam) { + this.paramSampler = SimpleSamplerFactory.createSampler(dumpParam, profilerConfig.getNingAsyncHttpClientProfileParamSamplingRate()); + } + } + + @Override + public void setMethodDescriptor(MethodDescriptor descriptor) { + this.descriptor = descriptor; + traceContext.cacheApi(descriptor); + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/BasicFutureModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/BasicFutureModifier.java index e2d17182a..6fc0e1dcc 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/BasicFutureModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/BasicFutureModifier.java @@ -34,43 +34,43 @@ import com.navercorp.pinpoint.profiler.modifier.AbstractModifier; * */ public class BasicFutureModifier extends AbstractModifier { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public BasicFutureModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } - @Override - public String getTargetClass() { - return "org/apache/http/concurrent/BasicFuture"; - } + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Override - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {} @ {}", javassistClassName, classLoader); - } + public BasicFutureModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - try { - InstrumentClass aClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + @Override + public String getTargetClass() { + return "org/apache/http/concurrent/BasicFuture"; + } - Interceptor futureGetInterceptor = byteCodeInstrumentor.newInterceptor(classLoader, protectedDomain, "com.navercorp.pinpoint.profiler.modifier.connector.httpclient4.interceptor.BasicFutureGetInterceptor"); - aClass.addInterceptor("get", null, futureGetInterceptor); - - Interceptor futureGetInterceptor2 = byteCodeInstrumentor.newInterceptor(classLoader, protectedDomain, "com.navercorp.pinpoint.profiler.modifier.connector.httpclient4.interceptor.BasicFutureGetInterceptor"); - aClass.addInterceptor("get", new String[] { "long", "java.util.concurrent.TimeUnit" }, futureGetInterceptor2); + @Override + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {} @ {}", javassistClassName, classLoader); + } - Interceptor futureCompletedInterceptor = byteCodeInstrumentor.newInterceptor(classLoader, protectedDomain, "com.navercorp.pinpoint.profiler.modifier.connector.httpclient4.interceptor.BasicFutureCompletedInterceptor"); - aClass.addInterceptor("completed", new String[] { "java.lang.Object" }, futureCompletedInterceptor); + try { + InstrumentClass aClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); - Interceptor futureFailedInterceptor = byteCodeInstrumentor.newInterceptor(classLoader, protectedDomain, "com.navercorp.pinpoint.profiler.modifier.connector.httpclient4.interceptor.BasicFutureFailedInterceptor"); - aClass.addInterceptor("failed", new String[] { "java.lang.Exception" }, futureFailedInterceptor); - - return aClass.toBytecode(); - } catch (InstrumentException e) { - logger.info("modify fail. Cause:{}", e.getMessage(), e); - return null; - } - } + Interceptor futureGetInterceptor = byteCodeInstrumentor.newInterceptor(classLoader, protectedDomain, "com.navercorp.pinpoint.profiler.modifier.connector.httpclient4.interceptor.BasicFutureGetInterceptor"); + aClass.addInterceptor("get", null, futureGetInterceptor); + + Interceptor futureGetInterceptor2 = byteCodeInstrumentor.newInterceptor(classLoader, protectedDomain, "com.navercorp.pinpoint.profiler.modifier.connector.httpclient4.interceptor.BasicFutureGetInterceptor"); + aClass.addInterceptor("get", new String[] { "long", "java.util.concurrent.TimeUnit" }, futureGetInterceptor2); + + Interceptor futureCompletedInterceptor = byteCodeInstrumentor.newInterceptor(classLoader, protectedDomain, "com.navercorp.pinpoint.profiler.modifier.connector.httpclient4.interceptor.BasicFutureCompletedInterceptor"); + aClass.addInterceptor("completed", new String[] { "java.lang.Object" }, futureCompletedInterceptor); + + Interceptor futureFailedInterceptor = byteCodeInstrumentor.newInterceptor(classLoader, protectedDomain, "com.navercorp.pinpoint.profiler.modifier.connector.httpclient4.interceptor.BasicFutureFailedInterceptor"); + aClass.addInterceptor("failed", new String[] { "java.lang.Exception" }, futureFailedInterceptor); + + return aClass.toBytecode(); + } catch (InstrumentException e) { + logger.info("modify fail. Cause:{}", e.getMessage(), e); + return null; + } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/ClosableHttpAsyncClientModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/ClosableHttpAsyncClientModifier.java index c15fbd530..b492eb67e 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/ClosableHttpAsyncClientModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/ClosableHttpAsyncClientModifier.java @@ -36,60 +36,60 @@ import com.navercorp.pinpoint.profiler.modifier.AbstractModifier; */ public class ClosableHttpAsyncClientModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public ClosableHttpAsyncClientModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public ClosableHttpAsyncClientModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - @Override - public String getTargetClass() { - return "org/apache/http/impl/nio/client/CloseableHttpAsyncClient"; - } + @Override + public String getTargetClass() { + return "org/apache/http/impl/nio/client/CloseableHttpAsyncClient"; + } - @Override - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {} @ {}", javassistClassName, classLoader); - } + @Override + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {} @ {}", javassistClassName, classLoader); + } - try { - InstrumentClass aClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + try { + InstrumentClass aClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); - /** - * Below two methods are overloaded, but they don't call each other. No Scope required. - */ - Interceptor executeInterceptor = byteCodeInstrumentor.newInterceptor(classLoader, - protectedDomain, - "com.navercorp.pinpoint.profiler.modifier.connector.httpclient4.interceptor.AsyncClientExecuteInterceptor"); - - String[] executeParams = new String[] { - "org.apache.http.HttpHost", - "org.apache.http.HttpRequest", - "org.apache.http.protocol.HttpContext", - "org.apache.http.concurrent.FutureCallback" - }; - aClass.addInterceptor("execute", executeParams, executeInterceptor); - - /** - * - */ - Interceptor internalExecuteInterceptor = byteCodeInstrumentor.newInterceptor(classLoader, - protectedDomain, - "com.navercorp.pinpoint.profiler.modifier.connector.httpclient4.interceptor.AsyncInternalClientExecuteInterceptor"); - - String[] internalExecuteParams = new String[] { - "org.apache.http.nio.protocol.HttpAsyncRequestProducer", - "org.apache.http.nio.protocol.HttpAsyncResponseConsumer", - "org.apache.http.concurrent.FutureCallback" - }; - aClass.addInterceptor("execute", internalExecuteParams, internalExecuteInterceptor); - - return aClass.toBytecode(); - } catch (InstrumentException e) { - logger.info("modify fail. Cause:{}", e.getMessage(), e); - return null; - } - } + /** + * Below two methods are overloaded, but they don't call each other. No Scope required. + */ + Interceptor executeInterceptor = byteCodeInstrumentor.newInterceptor(classLoader, + protectedDomain, + "com.navercorp.pinpoint.profiler.modifier.connector.httpclient4.interceptor.AsyncClientExecuteInterceptor"); + + String[] executeParams = new String[] { + "org.apache.http.HttpHost", + "org.apache.http.HttpRequest", + "org.apache.http.protocol.HttpContext", + "org.apache.http.concurrent.FutureCallback" + }; + aClass.addInterceptor("execute", executeParams, executeInterceptor); + + /** + * + */ + Interceptor internalExecuteInterceptor = byteCodeInstrumentor.newInterceptor(classLoader, + protectedDomain, + "com.navercorp.pinpoint.profiler.modifier.connector.httpclient4.interceptor.AsyncInternalClientExecuteInterceptor"); + + String[] internalExecuteParams = new String[] { + "org.apache.http.nio.protocol.HttpAsyncRequestProducer", + "org.apache.http.nio.protocol.HttpAsyncResponseConsumer", + "org.apache.http.concurrent.FutureCallback" + }; + aClass.addInterceptor("execute", internalExecuteParams, internalExecuteInterceptor); + + return aClass.toBytecode(); + } catch (InstrumentException e) { + logger.info("modify fail. Cause:{}", e.getMessage(), e); + return null; + } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/InternalHttpAsyncClientModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/InternalHttpAsyncClientModifier.java index 4a6127e9e..79335c6c5 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/InternalHttpAsyncClientModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/InternalHttpAsyncClientModifier.java @@ -36,42 +36,42 @@ import com.navercorp.pinpoint.profiler.modifier.AbstractModifier; @Deprecated public class InternalHttpAsyncClientModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public InternalHttpAsyncClientModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public InternalHttpAsyncClientModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - @Override - public String getTargetClass() { - return "org/apache/http/impl/nio/client/InternalHttpAsyncClient"; - } + @Override + public String getTargetClass() { + return "org/apache/http/impl/nio/client/InternalHttpAsyncClient"; + } - @Override - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {} @ {}", javassistClassName, classLoader); - } + @Override + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {} @ {}", javassistClassName, classLoader); + } - try { - InstrumentClass aClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + try { + InstrumentClass aClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); - Interceptor internalExecuteInterceptor = byteCodeInstrumentor.newInterceptor(classLoader, - protectedDomain, - "com.navercorp.pinpoint.profiler.modifier.connector.httpclient4.interceptor.AsyncInternalClientExecuteInterceptor"); - - String[] internalExecuteParams = new String[] { - "org.apache.http.nio.protocol.HttpAsyncRequestProducer", - "org.apache.http.nio.protocol.HttpAsyncResponseConsumer", - "org.apache.http.protocol.HttpContext", - "org.apache.http.concurrent.FutureCallback" - }; - aClass.addInterceptor("execute", internalExecuteParams, internalExecuteInterceptor); - - return aClass.toBytecode(); - } catch (InstrumentException e) { - logger.info("modify fail. Cause:{}", e.getMessage(), e); - return null; - } - } + Interceptor internalExecuteInterceptor = byteCodeInstrumentor.newInterceptor(classLoader, + protectedDomain, + "com.navercorp.pinpoint.profiler.modifier.connector.httpclient4.interceptor.AsyncInternalClientExecuteInterceptor"); + + String[] internalExecuteParams = new String[] { + "org.apache.http.nio.protocol.HttpAsyncRequestProducer", + "org.apache.http.nio.protocol.HttpAsyncResponseConsumer", + "org.apache.http.protocol.HttpContext", + "org.apache.http.concurrent.FutureCallback" + }; + aClass.addInterceptor("execute", internalExecuteParams, internalExecuteInterceptor); + + return aClass.toBytecode(); + } catch (InstrumentException e) { + logger.info("modify fail. Cause:{}", e.getMessage(), e); + return null; + } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/AsyncClientExecuteInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/AsyncClientExecuteInterceptor.java index e5c732a35..2c526c435 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/AsyncClientExecuteInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/AsyncClientExecuteInterceptor.java @@ -54,21 +54,21 @@ public class AsyncClientExecuteInterceptor extends AbstractHttpRequestExecute im } @Override - protected NameIntValuePair getHost(Object[] args) { - if (args[0] instanceof org.apache.http.HttpHost) { - final org.apache.http.HttpHost httpHost = (org.apache.http.HttpHost) args[0]; - return new NameIntValuePair(httpHost.getHostName(), httpHost.getPort()); - } else { - return null; - } - } + protected NameIntValuePair getHost(Object[] args) { + if (args[0] instanceof org.apache.http.HttpHost) { + final org.apache.http.HttpHost httpHost = (org.apache.http.HttpHost) args[0]; + return new NameIntValuePair(httpHost.getHostName(), httpHost.getPort()); + } else { + return null; + } + } - @Override - protected org.apache.http.HttpRequest getHttpRequest(final Object[] args) { - if (args[1] instanceof org.apache.http.HttpRequest) { - return (org.apache.http.HttpRequest) args[1]; - } else { - return null; - } - } + @Override + protected org.apache.http.HttpRequest getHttpRequest(final Object[] args) { + if (args[1] instanceof org.apache.http.HttpRequest) { + return (org.apache.http.HttpRequest) args[1]; + } else { + return null; + } + } } \ No newline at end of file diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/AsyncInternalClientExecuteInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/AsyncInternalClientExecuteInterceptor.java index 3ed0e8170..ac263cbfb 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/AsyncInternalClientExecuteInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/AsyncInternalClientExecuteInterceptor.java @@ -38,32 +38,32 @@ import com.navercorp.pinpoint.bootstrap.pair.NameIntValuePair; * public Future execute( * final org.apache.http.nio.protocol.HttpAsyncRequestProducer requestProducer, * final org.apache.http.nio.protocol.HttpAsyncResponseConsumer responseConsumer, - * final org.apache.http.protocol.HttpContext context, - * final org.apache.http.concurrent.FutureCallback callback) { + * final org.apache.http.protocol.HttpContext context, + * final org.apache.http.concurrent.FutureCallback callback) { * - * final Status status = getStatus(); - * Asserts.check(status == Status.ACTIVE, "Request cannot be executed; I/O reactor status: %s", status); + * final Status status = getStatus(); + * Asserts.check(status == Status.ACTIVE, "Request cannot be executed; I/O reactor status: %s", status); * - * final BasicFuture future = new BasicFuture(callback); - * final HttpClientContext localcontext = HttpClientContext.adapt(context != null ? context : new BasicHttpContext()); - * setupContext(localcontext); + * final BasicFuture future = new BasicFuture(callback); + * final HttpClientContext localcontext = HttpClientContext.adapt(context != null ? context : new BasicHttpContext()); + * setupContext(localcontext); * - * @SuppressWarnings("resource") - * final DefaultClientExchangeHandlerImpl handler = new DefaultClientExchangeHandlerImpl( - * this.log, - * requestProducer, - * responseConsumer, - * localcontext, - * future, - * this.connmgr, - * this.exec); + * @SuppressWarnings("resource") + * final DefaultClientExchangeHandlerImpl handler = new DefaultClientExchangeHandlerImpl( + * this.log, + * requestProducer, + * responseConsumer, + * localcontext, + * future, + * this.connmgr, + * this.exec); * - * try { - * handler.start(); - * } catch (final Exception ex) { - * handler.failed(ex); - * } - * return future; + * try { + * handler.start(); + * } catch (final Exception ex) { + * handler.failed(ex); + * } + * return future; * } * * OR @@ -90,30 +90,30 @@ public class AsyncInternalClientExecuteInterceptor extends AbstractHttpRequestEx } @Override - protected NameIntValuePair getHost(Object[] args) { - if (!(args[0] instanceof org.apache.http.nio.protocol.HttpAsyncRequestProducer)) { - return null; - } + protected NameIntValuePair getHost(Object[] args) { + if (!(args[0] instanceof org.apache.http.nio.protocol.HttpAsyncRequestProducer)) { + return null; + } - final org.apache.http.nio.protocol.HttpAsyncRequestProducer producer = (org.apache.http.nio.protocol.HttpAsyncRequestProducer) args[0]; - final HttpHost httpHost = producer.getTarget(); + final org.apache.http.nio.protocol.HttpAsyncRequestProducer producer = (org.apache.http.nio.protocol.HttpAsyncRequestProducer) args[0]; + final HttpHost httpHost = producer.getTarget(); - return new NameIntValuePair(httpHost.getHostName(), httpHost.getPort()); - } + return new NameIntValuePair(httpHost.getHostName(), httpHost.getPort()); + } - @Override - protected org.apache.http.HttpRequest getHttpRequest(final Object[] args) { - if (!(args[0] instanceof org.apache.http.nio.protocol.HttpAsyncRequestProducer)) { - return null; - } - final org.apache.http.nio.protocol.HttpAsyncRequestProducer producer = (org.apache.http.nio.protocol.HttpAsyncRequestProducer) args[0]; - try { - /** - * FIXME Implementations other than org.apache.http.nio.protocol.BasicAsyncRequestProducer.generateRequest() can cause some trouble. - */ - return producer.generateRequest(); - } catch (Exception e) { - return null; - } - } + @Override + protected org.apache.http.HttpRequest getHttpRequest(final Object[] args) { + if (!(args[0] instanceof org.apache.http.nio.protocol.HttpAsyncRequestProducer)) { + return null; + } + final org.apache.http.nio.protocol.HttpAsyncRequestProducer producer = (org.apache.http.nio.protocol.HttpAsyncRequestProducer) args[0]; + try { + /** + * FIXME Implementations other than org.apache.http.nio.protocol.BasicAsyncRequestProducer.generateRequest() can cause some trouble. + */ + return producer.generateRequest(); + } catch (Exception e) { + return null; + } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/BasicFutureCompletedInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/BasicFutureCompletedInterceptor.java index 5c350df54..b4a098bae 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/BasicFutureCompletedInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/BasicFutureCompletedInterceptor.java @@ -37,20 +37,20 @@ import com.navercorp.pinpoint.common.ServiceType; * original code of method * *
- * 	public boolean completed(final T result) {
- * 		synchronized (this) {
- * 			if (this.completed) {
- * 				return false;
- * 			}
- * 			this.completed = true;
- * 			this.result = result;
- * 			notifyAll();
- * 		}
- * 		if (this.callback != null) {
- * 			this.callback.completed(result);
- * 		}
- * 		return true;
- * 	}
+ *     public boolean completed(final T result) {
+ *         synchronized (this) {
+ *             if (this.completed) {
+ *                 return false;
+ *             }
+ *             this.completed = true;
+ *             this.result = result;
+ *             notifyAll();
+ *         }
+ *         if (this.callback != null) {
+ *             this.callback.completed(result);
+ *         }
+ *         return true;
+ *     }
  * 
*
* @@ -65,50 +65,50 @@ public class BasicFutureCompletedInterceptor implements SimpleAroundInterceptor, private TraceContext traceContext; private MethodDescriptor descriptor; - @Override - public void before(Object target, Object[] args) { - if (isDebug) { - logger.beforeInterceptor(target, args); - } + @Override + public void before(Object target, Object[] args) { + if (isDebug) { + logger.beforeInterceptor(target, args); + } - Trace trace = traceContext.currentTraceObject(); - if (trace == null) { - return; - } + Trace trace = traceContext.currentTraceObject(); + if (trace == null) { + return; + } - trace.traceBlockBegin(); - trace.markBeforeTime(); - trace.recordServiceType(ServiceType.HTTP_CLIENT_INTERNAL); - } + trace.traceBlockBegin(); + trace.markBeforeTime(); + trace.recordServiceType(ServiceType.HTTP_CLIENT_INTERNAL); + } - @Override - public void after(Object target, Object[] args, Object result, Throwable throwable) { - if (isDebug) { - logger.afterInterceptor(target, args); - } + @Override + public void after(Object target, Object[] args, Object result, Throwable throwable) { + if (isDebug) { + logger.afterInterceptor(target, args); + } - Trace trace = traceContext.currentTraceObject(); - if (trace == null) { - return; - } + Trace trace = traceContext.currentTraceObject(); + if (trace == null) { + return; + } - try { - trace.recordApi(descriptor); - trace.recordException(throwable); - trace.markAfterTime(); - } finally { - trace.traceBlockEnd(); - } - } + try { + trace.recordApi(descriptor); + trace.recordException(throwable); + trace.markAfterTime(); + } finally { + trace.traceBlockEnd(); + } + } - @Override - public void setTraceContext(TraceContext traceContext) { - this.traceContext = traceContext; - } + @Override + public void setTraceContext(TraceContext traceContext) { + this.traceContext = traceContext; + } - @Override - public void setMethodDescriptor(MethodDescriptor descriptor) { - this.descriptor = descriptor; - traceContext.cacheApi(descriptor); - } + @Override + public void setMethodDescriptor(MethodDescriptor descriptor) { + this.descriptor = descriptor; + traceContext.cacheApi(descriptor); + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/BasicFutureFailedInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/BasicFutureFailedInterceptor.java index 9d2a911e7..03e1159c7 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/BasicFutureFailedInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/BasicFutureFailedInterceptor.java @@ -37,20 +37,20 @@ import com.navercorp.pinpoint.common.ServiceType; * original code of method * *
- * 	public boolean failed(final Exception exception) {
- * 		synchronized (this) {
- * 			if (this.completed) {
- * 				return false;
- * 			}
- * 			this.completed = true;
- * 			this.ex = exception;
- * 			notifyAll();
- * 		}
- * 		if (this.callback != null) {
- * 			this.callback.failed(exception);
- * 		}
- * 		return true;
- * 	}
+ *     public boolean failed(final Exception exception) {
+ *         synchronized (this) {
+ *             if (this.completed) {
+ *                 return false;
+ *             }
+ *             this.completed = true;
+ *             this.ex = exception;
+ *             notifyAll();
+ *         }
+ *         if (this.callback != null) {
+ *             this.callback.failed(exception);
+ *         }
+ *         return true;
+ *     }
  * 
*
* @@ -59,56 +59,56 @@ import com.navercorp.pinpoint.common.ServiceType; */ public class BasicFutureFailedInterceptor implements SimpleAroundInterceptor, ByteCodeMethodDescriptorSupport, TraceContextSupport, TargetClassLoader { - private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); + private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); private final boolean isDebug = logger.isDebugEnabled(); - private TraceContext traceContext; + private TraceContext traceContext; private MethodDescriptor descriptor; - @Override - public void before(Object target, Object[] args) { - if (isDebug) { + @Override + public void before(Object target, Object[] args) { + if (isDebug) { logger.beforeInterceptor(target, args); } - Trace trace = traceContext.currentTraceObject(); - if (trace == null) { - return; - } + Trace trace = traceContext.currentTraceObject(); + if (trace == null) { + return; + } - trace.traceBlockBegin(); - trace.markBeforeTime(); - trace.recordServiceType(ServiceType.HTTP_CLIENT_INTERNAL); - } + trace.traceBlockBegin(); + trace.markBeforeTime(); + trace.recordServiceType(ServiceType.HTTP_CLIENT_INTERNAL); + } - @Override - public void after(Object target, Object[] args, Object result, Throwable throwable) { - if (isDebug) { - logger.afterInterceptor(target, args); - } + @Override + public void after(Object target, Object[] args, Object result, Throwable throwable) { + if (isDebug) { + logger.afterInterceptor(target, args); + } - Trace trace = traceContext.currentTraceObject(); - if (trace == null) { - return; - } + Trace trace = traceContext.currentTraceObject(); + if (trace == null) { + return; + } - try { - trace.recordApi(descriptor); - trace.recordException(throwable); - trace.markAfterTime(); - } finally { - trace.traceBlockEnd(); - } - } + try { + trace.recordApi(descriptor); + trace.recordException(throwable); + trace.markAfterTime(); + } finally { + trace.traceBlockEnd(); + } + } - @Override - public void setTraceContext(TraceContext traceContext) { - this.traceContext = traceContext; - } + @Override + public void setTraceContext(TraceContext traceContext) { + this.traceContext = traceContext; + } - @Override - public void setMethodDescriptor(MethodDescriptor descriptor) { - this.descriptor = descriptor; - traceContext.cacheApi(descriptor); - } + @Override + public void setMethodDescriptor(MethodDescriptor descriptor) { + this.descriptor = descriptor; + traceContext.cacheApi(descriptor); + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/BasicFutureGetInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/BasicFutureGetInterceptor.java index 7cdfb0cf5..8e1bd860c 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/BasicFutureGetInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/BasicFutureGetInterceptor.java @@ -37,36 +37,36 @@ import com.navercorp.pinpoint.common.ServiceType; * * *
- * 	public synchronized T get() throws InterruptedException, ExecutionException {
- * 		while (!this.completed) {
- * 			wait();
- * 		}
- * 		return getResult();
- * 	}
+ *     public synchronized T get() throws InterruptedException, ExecutionException {
+ *         while (!this.completed) {
+ *             wait();
+ *         }
+ *         return getResult();
+ *     }
  * 
- * 	public synchronized T get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
- * 		Args.notNull(unit, "Time unit");
- * 		final long msecs = unit.toMillis(timeout);
- * 		final long startTime = (msecs <= 0) ? 0 : System.currentTimeMillis();
- * 		long waitTime = msecs;
- * 		if (this.completed) {
- * 			return getResult();
- * 		} else if (waitTime <= 0) {
- * 			throw new TimeoutException();
- * 		} else {
- * 			for (;;) {
- * 				wait(waitTime);
- * 				if (this.completed) {
- * 					return getResult();
- * 				} else {
- * 					waitTime = msecs - (System.currentTimeMillis() - startTime);
- * 					if (waitTime <= 0) {
- * 						throw new TimeoutException();
- * 					}
- * 				}
- * 			}
- * 		}
- * 	}
+ *     public synchronized T get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
+ *         Args.notNull(unit, "Time unit");
+ *         final long msecs = unit.toMillis(timeout);
+ *         final long startTime = (msecs <= 0) ? 0 : System.currentTimeMillis();
+ *         long waitTime = msecs;
+ *         if (this.completed) {
+ *             return getResult();
+ *         } else if (waitTime <= 0) {
+ *             throw new TimeoutException();
+ *         } else {
+ *             for (;;) {
+ *                 wait(waitTime);
+ *                 if (this.completed) {
+ *                     return getResult();
+ *                 } else {
+ *                     waitTime = msecs - (System.currentTimeMillis() - startTime);
+ *                     if (waitTime <= 0) {
+ *                         throw new TimeoutException();
+ *                     }
+ *                 }
+ *             }
+ *         }
+ *     }
  * 
*
* @@ -78,53 +78,53 @@ public class BasicFutureGetInterceptor implements SimpleAroundInterceptor, ByteC protected final PLogger logger = PLoggerFactory.getLogger(this.getClass()); protected final boolean isDebug = logger.isDebugEnabled(); - protected TraceContext traceContext; - protected MethodDescriptor descriptor; + protected TraceContext traceContext; + protected MethodDescriptor descriptor; - @Override - public void before(Object target, Object[] args) { - if (isDebug) { - logger.beforeInterceptor(target, args); - } + @Override + public void before(Object target, Object[] args) { + if (isDebug) { + logger.beforeInterceptor(target, args); + } - Trace trace = traceContext.currentTraceObject(); - if (trace == null) { - return; - } + Trace trace = traceContext.currentTraceObject(); + if (trace == null) { + return; + } - trace.traceBlockBegin(); - trace.markBeforeTime(); - trace.recordServiceType(ServiceType.HTTP_CLIENT_INTERNAL); - } + trace.traceBlockBegin(); + trace.markBeforeTime(); + trace.recordServiceType(ServiceType.HTTP_CLIENT_INTERNAL); + } - @Override - public void after(Object target, Object[] args, Object result, Throwable throwable) { - if (isDebug) { - logger.afterInterceptor(target, args); - } + @Override + public void after(Object target, Object[] args, Object result, Throwable throwable) { + if (isDebug) { + logger.afterInterceptor(target, args); + } - Trace trace = traceContext.currentTraceObject(); - if (trace == null) { - return; - } + Trace trace = traceContext.currentTraceObject(); + if (trace == null) { + return; + } - try { - trace.recordApi(descriptor); - trace.recordException(throwable); - trace.markAfterTime(); - } finally { - trace.traceBlockEnd(); - } - } + try { + trace.recordApi(descriptor); + trace.recordException(throwable); + trace.markAfterTime(); + } finally { + trace.traceBlockEnd(); + } + } - @Override - public void setTraceContext(TraceContext traceContext) { - this.traceContext = traceContext; - } + @Override + public void setTraceContext(TraceContext traceContext) { + this.traceContext = traceContext; + } - @Override - public void setMethodDescriptor(MethodDescriptor descriptor) { - this.descriptor = descriptor; - traceContext.cacheApi(descriptor); - } + @Override + public void setMethodDescriptor(MethodDescriptor descriptor) { + this.descriptor = descriptor; + traceContext.cacheApi(descriptor); + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/HttpUriRequestExecuteInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/HttpUriRequestExecuteInterceptor.java index 625358108..55e5933c2 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/HttpUriRequestExecuteInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/httpclient4/interceptor/HttpUriRequestExecuteInterceptor.java @@ -73,57 +73,57 @@ public class HttpUriRequestExecuteInterceptor extends AbstractHttpRequestExecute * @return */ private NameIntValuePair extractHost(final URI uri) { - if (uri == null) { - return null; - } + if (uri == null) { + return null; + } NameIntValuePair target = null; - if (uri.isAbsolute()) { - int port = uri.getPort(); // may be overridden later - String host = uri.getHost(); - if (host == null) { // normal parse failed; let's do it ourselves - // authority does not seem to care about the valid character-set - // for host names - host = uri.getAuthority(); - if (host != null) { - // Strip off any leading user credentials - int at = host.indexOf('@'); - if (at >= 0) { - if (host.length() > at + 1) { - host = host.substring(at + 1); - } else { - host = null; // @ on its own - } - } - // Extract the port suffix, if present - if (host != null) { - int colon = host.indexOf(':'); - if (colon >= 0) { - int pos = colon + 1; - int len = 0; - for (int i = pos; i < host.length(); i++) { - if (Character.isDigit(host.charAt(i))) { - len++; - } else { - break; - } - } - if (len > 0) { - try { - port = Integer.parseInt(host.substring(pos, pos + len)); - } catch (NumberFormatException ignore) { + if (uri.isAbsolute()) { + int port = uri.getPort(); // may be overridden later + String host = uri.getHost(); + if (host == null) { // normal parse failed; let's do it ourselves + // authority does not seem to care about the valid character-set + // for host names + host = uri.getAuthority(); + if (host != null) { + // Strip off any leading user credentials + int at = host.indexOf('@'); + if (at >= 0) { + if (host.length() > at + 1) { + host = host.substring(at + 1); + } else { + host = null; // @ on its own + } + } + // Extract the port suffix, if present + if (host != null) { + int colon = host.indexOf(':'); + if (colon >= 0) { + int pos = colon + 1; + int len = 0; + for (int i = pos; i < host.length(); i++) { + if (Character.isDigit(host.charAt(i))) { + len++; + } else { + break; + } + } + if (len > 0) { + try { + port = Integer.parseInt(host.substring(pos, pos + len)); + } catch (NumberFormatException ignore) { // skip - } - } - host = host.substring(0, colon); - } - } - } - } - if (host != null) { - target = new NameIntValuePair(host, port); - } - } - return target; - } + } + } + host = host.substring(0, colon); + } + } + } + } + if (host != null) { + target = new NameIntValuePair(host, port); + } + } + return target; + } } \ No newline at end of file diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/jdkhttpconnector/HttpURLConnectionModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/jdkhttpconnector/HttpURLConnectionModifier.java index 89f1f1bda..60ef94305 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/jdkhttpconnector/HttpURLConnectionModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/jdkhttpconnector/HttpURLConnectionModifier.java @@ -35,30 +35,30 @@ import org.slf4j.LoggerFactory; */ public class HttpURLConnectionModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public HttpURLConnectionModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public HttpURLConnectionModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - public String getTargetClass() { - return "sun/net/www/protocol/http/HttpURLConnection"; - } + public String getTargetClass() { + return "sun/net/www/protocol/http/HttpURLConnection"; + } - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } - try { - InstrumentClass aClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + try { + InstrumentClass aClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); ConnectMethodInterceptor connectMethodInterceptor = new ConnectMethodInterceptor(); aClass.addInterceptor("connect", null, connectMethodInterceptor); - return aClass.toBytecode(); - } catch (InstrumentException e) { - logger.warn("HttpURLConnectionModifier fail. Caused:", e.getMessage(), e); - return null; - } - } + return aClass.toBytecode(); + } catch (InstrumentException e) { + logger.warn("HttpURLConnectionModifier fail. Caused:", e.getMessage(), e); + return null; + } + } } \ No newline at end of file diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/jdkhttpconnector/interceptor/ConnectMethodInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/jdkhttpconnector/interceptor/ConnectMethodInterceptor.java index efd0489a1..4f86d02c4 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/jdkhttpconnector/interceptor/ConnectMethodInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/connector/jdkhttpconnector/interceptor/ConnectMethodInterceptor.java @@ -39,17 +39,17 @@ import com.navercorp.pinpoint.common.ServiceType; */ public class ConnectMethodInterceptor implements SimpleAroundInterceptor, ByteCodeMethodDescriptorSupport, TraceContextSupport { - private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); - private final boolean isDebug = logger.isDebugEnabled(); + private final PLogger logger = PLoggerFactory.getLogger(this.getClass()); + private final boolean isDebug = logger.isDebugEnabled(); - private MethodDescriptor descriptor; + private MethodDescriptor descriptor; private TraceContext traceContext; @Override - public void before(Object target, Object[] args) { - if (isDebug) { - logger.beforeInterceptor(target, args); - } + public void before(Object target, Object[] args) { + if (isDebug) { + logger.beforeInterceptor(target, args); + } Trace trace = traceContext.currentRawTraceObject(); if (trace == null) { return; @@ -64,34 +64,34 @@ public class ConnectMethodInterceptor implements SimpleAroundInterceptor, ByteCo } - trace.traceBlockBegin(); - trace.markBeforeTime(); + trace.traceBlockBegin(); + trace.markBeforeTime(); - TraceId nextId = trace.getTraceId().getNextTraceId(); - trace.recordNextSpanId(nextId.getSpanId()); + TraceId nextId = trace.getTraceId().getNextTraceId(); + trace.recordNextSpanId(nextId.getSpanId()); - request.setRequestProperty(Header.HTTP_TRACE_ID.toString(), nextId.getTransactionId()); - request.setRequestProperty(Header.HTTP_SPAN_ID.toString(), String.valueOf(nextId.getSpanId())); - request.setRequestProperty(Header.HTTP_PARENT_SPAN_ID.toString(), String.valueOf(nextId.getParentSpanId())); + request.setRequestProperty(Header.HTTP_TRACE_ID.toString(), nextId.getTransactionId()); + request.setRequestProperty(Header.HTTP_SPAN_ID.toString(), String.valueOf(nextId.getSpanId())); + request.setRequestProperty(Header.HTTP_PARENT_SPAN_ID.toString(), String.valueOf(nextId.getParentSpanId())); - request.setRequestProperty(Header.HTTP_FLAGS.toString(), String.valueOf(nextId.getFlags())); - request.setRequestProperty(Header.HTTP_PARENT_APPLICATION_NAME.toString(), traceContext.getApplicationName()); - request.setRequestProperty(Header.HTTP_PARENT_APPLICATION_TYPE.toString(), Short.toString(traceContext.getServerTypeCode())); + request.setRequestProperty(Header.HTTP_FLAGS.toString(), String.valueOf(nextId.getFlags())); + request.setRequestProperty(Header.HTTP_PARENT_APPLICATION_NAME.toString(), traceContext.getApplicationName()); + request.setRequestProperty(Header.HTTP_PARENT_APPLICATION_TYPE.toString(), Short.toString(traceContext.getServerTypeCode())); - trace.recordServiceType(ServiceType.JDK_HTTPURLCONNECTOR); + trace.recordServiceType(ServiceType.JDK_HTTPURLCONNECTOR); final URL url = request.getURL(); final String host = url.getHost(); - final int port = url.getPort(); + final int port = url.getPort(); - // TODO How to represent protocol? + // TODO How to represent protocol? String endpoint = getEndpoint(host, port); // Don't record end point because it's same with destination id. - trace.recordDestinationId(endpoint); - trace.recordAttribute(AnnotationKey.HTTP_URL, url.toString()); - } + trace.recordDestinationId(endpoint); + trace.recordAttribute(AnnotationKey.HTTP_URL, url.toString()); + } private String getEndpoint(String host, int port) { if (port < 0) { @@ -105,16 +105,16 @@ public class ConnectMethodInterceptor implements SimpleAroundInterceptor, ByteCo } @Override - public void after(Object target, Object[] args, Object result, Throwable throwable) { - if (isDebug) { - // do not log result - logger.afterInterceptor(target, args); - } + public void after(Object target, Object[] args, Object result, Throwable throwable) { + if (isDebug) { + // do not log result + logger.afterInterceptor(target, args); + } - Trace trace = traceContext.currentTraceObject(); - if (trace == null) { - return; - } + Trace trace = traceContext.currentTraceObject(); + if (trace == null) { + return; + } try { trace.recordApi(descriptor); @@ -124,13 +124,13 @@ public class ConnectMethodInterceptor implements SimpleAroundInterceptor, ByteCo } finally { trace.traceBlockEnd(); } - } + } - @Override - public void setMethodDescriptor(MethodDescriptor descriptor) { - this.descriptor = descriptor; - traceContext.cacheApi(descriptor); - } + @Override + public void setMethodDescriptor(MethodDescriptor descriptor) { + this.descriptor = descriptor; + traceContext.cacheApi(descriptor); + } @Override public void setTraceContext(TraceContext traceContext) { diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/DefaultDatabaseInfo.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/DefaultDatabaseInfo.java index 805d7c23d..66c9ea37e 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/DefaultDatabaseInfo.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/DefaultDatabaseInfo.java @@ -26,15 +26,15 @@ import java.util.List; */ public class DefaultDatabaseInfo implements DatabaseInfo { - private ServiceType type = ServiceType.UNKNOWN_DB; + private ServiceType type = ServiceType.UNKNOWN_DB; private ServiceType executeQueryType = ServiceType.UNKNOWN_DB_EXECUTE_QUERY; private String databaseId; - private String realUrl; // URL before refinement + private String realUrl; // URL before refinement private String normalizedUrl; private List host; private String multipleHost; - public DefaultDatabaseInfo(ServiceType type, ServiceType executeQueryType, String realUrl, String normalizedUrl, List host, String databaseId) { + public DefaultDatabaseInfo(ServiceType type, ServiceType executeQueryType, String realUrl, String normalizedUrl, List host, String databaseId) { if (type == null) { throw new NullPointerException("type must not be null"); } @@ -43,12 +43,12 @@ public class DefaultDatabaseInfo implements DatabaseInfo { } this.type = type; this.executeQueryType = executeQueryType; - this.realUrl = realUrl; - this.normalizedUrl = normalizedUrl; - this.host = host; + this.realUrl = realUrl; + this.normalizedUrl = normalizedUrl; + this.host = host; this.multipleHost = merge(host); - this.databaseId = databaseId; - } + this.databaseId = databaseId; + } private String merge(List host) { if (host.isEmpty()) { @@ -68,8 +68,8 @@ public class DefaultDatabaseInfo implements DatabaseInfo { @Override public List getHost() { // With replication, this is not simple because there could be multiple hosts or ports. - return host; - } + return host; + } @Override public String getMultipleHost() { @@ -78,23 +78,23 @@ public class DefaultDatabaseInfo implements DatabaseInfo { @Override public String getDatabaseId() { - return databaseId; - } + return databaseId; + } - @Override + @Override public String getRealUrl() { - return realUrl; - } + return realUrl; + } - @Override + @Override public String getUrl() { - return normalizedUrl; - } + return normalizedUrl; + } - @Override + @Override public ServiceType getType() { - return type; - } + return type; + } @Override public ServiceType getExecuteQueryType() { diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/JDBCUrlParser.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/JDBCUrlParser.java index 67ae58cff..1616ea540 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/JDBCUrlParser.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/JDBCUrlParser.java @@ -72,7 +72,7 @@ public class JDBCUrlParser { return parseJtds(url); } if (driverTypeCheck(lowCaseURL, "cubrid")) { - return parseCubrid(url); + return parseCubrid(url); } return createUnknownDataBase(url); } @@ -113,9 +113,9 @@ public class JDBCUrlParser { } - - private DatabaseInfo parseCubrid(String url) { + + private DatabaseInfo parseCubrid(String url) { final ConnectionStringParser parser = new CubridConnectionStringParser(); return parser.parse(url); - } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridConnectionModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridConnectionModifier.java index 41f64f7c3..b91c0a885 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridConnectionModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridConnectionModifier.java @@ -36,22 +36,22 @@ import org.slf4j.LoggerFactory; */ public class CubridConnectionModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public CubridConnectionModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public CubridConnectionModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - public String getTargetClass() { - return "cubrid/jdbc/driver/CUBRIDConnection"; - } + public String getTargetClass() { + return "cubrid/jdbc/driver/CUBRIDConnection"; + } - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } - try { - InstrumentClass cubridConnection = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } + try { + InstrumentClass cubridConnection = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); cubridConnection.addTraceValue(DatabaseInfoTraceValue.class); @@ -106,11 +106,11 @@ public class CubridConnectionModifier extends AbstractModifier { } return cubridConnection.toBytecode(); - } catch (InstrumentException e) { - if (logger.isWarnEnabled()) { - logger.warn("{} modify fail. Cause:{}", this.getClass().getSimpleName(), e.getMessage(), e); - } - return null; - } - } + } catch (InstrumentException e) { + if (logger.isWarnEnabled()) { + logger.warn("{} modify fail. Cause:{}", this.getClass().getSimpleName(), e.getMessage(), e); + } + return null; + } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridConnectionStringParser.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridConnectionStringParser.java index 3c677614d..8cf1bb835 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridConnectionStringParser.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridConnectionStringParser.java @@ -107,22 +107,22 @@ public class CubridConnectionStringParser implements ConnectionStringParser { /* - private DatabaseInfo parseCubrid(String url) { - // jdbc:cubrid:10.20.30.40:12345:pinpoint::: - StringMaker maker = new StringMaker(url); - maker.after("jdbc:cubrid:"); - // 10.11.12.13:3306 In case of replication driver could have multiple values - // We have to consider mm db too. - String host = maker.after("//").before('/').value(); - List hostList = new ArrayList(1); - hostList.add(host); - // String port = maker.next().after(':').before('/').value(); + private DatabaseInfo parseCubrid(String url) { + // jdbc:cubrid:10.20.30.40:12345:pinpoint::: + StringMaker maker = new StringMaker(url); + maker.after("jdbc:cubrid:"); + // 10.11.12.13:3306 In case of replication driver could have multiple values + // We have to consider mm db too. + String host = maker.after("//").before('/').value(); + List hostList = new ArrayList(1); + hostList.add(host); + // String port = maker.next().after(':').before('/').value(); - String databaseId = maker.next().afterLast('/').before('?').value(); - String normalizedUrl = maker.clear().before('?').value(); + String databaseId = maker.next().afterLast('/').before('?').value(); + String normalizedUrl = maker.clear().before('?').value(); - return new DatabaseInfo(ServiceType.CUBRID, ServiceType.CUBRID_EXECUTE_QUERY, url, normalizedUrl, hostList, databaseId); - } - */ + return new DatabaseInfo(ServiceType.CUBRID, ServiceType.CUBRID_EXECUTE_QUERY, url, normalizedUrl, hostList, databaseId); + } + */ } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridDriverModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridDriverModifier.java index 6de386b2c..2c4a64ad3 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridDriverModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridDriverModifier.java @@ -31,22 +31,22 @@ import org.slf4j.LoggerFactory; public class CubridDriverModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public CubridDriverModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public CubridDriverModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - public String getTargetClass() { - return "cubrid/jdbc/driver/CUBRIDDriver"; - } + public String getTargetClass() { + return "cubrid/jdbc/driver/CUBRIDDriver"; + } - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } - try { - InstrumentClass mysqlConnection = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } + try { + InstrumentClass mysqlConnection = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); final Scope scope = byteCodeInstrumentor.getScope(CubridScope.SCOPE_NAME); DriverConnectInterceptor driverConnectInterceptor = new DriverConnectInterceptor(scope); @@ -57,11 +57,11 @@ public class CubridDriverModifier extends AbstractModifier { } return mysqlConnection.toBytecode(); - } catch (InstrumentException e) { - if (logger.isWarnEnabled()) { - logger.warn("{} modify fail. Cause:{}", this.getClass().getSimpleName(), e.getMessage(), e); - } - return null; - } - } + } catch (InstrumentException e) { + if (logger.isWarnEnabled()) { + logger.warn("{} modify fail. Cause:{}", this.getClass().getSimpleName(), e.getMessage(), e); + } + return null; + } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridPreparedStatementModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridPreparedStatementModifier.java index 56d9c3984..93fd664ef 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridPreparedStatementModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridPreparedStatementModifier.java @@ -45,23 +45,23 @@ import org.slf4j.LoggerFactory; */ public class CubridPreparedStatementModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public CubridPreparedStatementModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public CubridPreparedStatementModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - public String getTargetClass() { - return "cubrid/jdbc/driver/CUBRIDPreparedStatement"; - } + public String getTargetClass() { + return "cubrid/jdbc/driver/CUBRIDPreparedStatement"; + } - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } - try { - InstrumentClass preparedStatementClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } + try { + InstrumentClass preparedStatementClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); Interceptor executeInterceptor = new PreparedStatementExecuteQueryInterceptor(); preparedStatementClass.addScopeInterceptor("execute", null, executeInterceptor, CubridScope.SCOPE_NAME); @@ -76,37 +76,37 @@ public class CubridPreparedStatementModifier extends AbstractModifier { preparedStatementClass.addTraceValue(ParsingResultTraceValue.class); preparedStatementClass.addTraceValue(BindValueTraceValue.class, "new java.util.HashMap();"); - bindVariableIntercept(preparedStatementClass, classLoader, protectedDomain); + bindVariableIntercept(preparedStatementClass, classLoader, protectedDomain); - return preparedStatementClass.toBytecode(); - } catch (InstrumentException e) { - if (logger.isWarnEnabled()) { - logger.warn("{} modify fail. Cause:{}", this.getClass().getSimpleName(), e.getMessage(), e); - } - return null; - } - } + return preparedStatementClass.toBytecode(); + } catch (InstrumentException e) { + if (logger.isWarnEnabled()) { + logger.warn("{} modify fail. Cause:{}", this.getClass().getSimpleName(), e.getMessage(), e); + } + return null; + } + } - private void bindVariableIntercept(InstrumentClass preparedStatement, ClassLoader classLoader, ProtectionDomain protectedDomain) throws InstrumentException { - List bindMethod = PreparedStatementUtils.findBindVariableSetMethod(); + private void bindVariableIntercept(InstrumentClass preparedStatement, ClassLoader classLoader, ProtectionDomain protectedDomain) throws InstrumentException { + List bindMethod = PreparedStatementUtils.findBindVariableSetMethod(); final Scope scope = byteCodeInstrumentor.getScope(CubridScope.SCOPE_NAME); Interceptor interceptor = new ScopeDelegateStaticInterceptor(new PreparedStatementBindVariableInterceptor(), scope); - int interceptorId = -1; - for (Method method : bindMethod) { - String methodName = method.getName(); - String[] parameterType = JavaAssistUtils.getParameterType(method.getParameterTypes()); - try { - if (interceptorId == -1) { - interceptorId = preparedStatement.addInterceptor(methodName, parameterType, interceptor); - } else { - preparedStatement.reuseInterceptor(methodName, parameterType, interceptorId); - } - } catch (NotFoundInstrumentException e) { - // Cannot find bind variable setter method. This is not an error. Just some log will be enough. + int interceptorId = -1; + for (Method method : bindMethod) { + String methodName = method.getName(); + String[] parameterType = JavaAssistUtils.getParameterType(method.getParameterTypes()); + try { + if (interceptorId == -1) { + interceptorId = preparedStatement.addInterceptor(methodName, parameterType, interceptor); + } else { + preparedStatement.reuseInterceptor(methodName, parameterType, interceptorId); + } + } catch (NotFoundInstrumentException e) { + // Cannot find bind variable setter method. This is not an error. Just some log will be enough. if (logger.isDebugEnabled()) { logger.debug("bindVariable api not found. method:{} param:{} Cause:{}", methodName, Arrays.toString(parameterType), e.getMessage()); } - } - } - } + } + } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridResultSetModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridResultSetModifier.java index ff7db9b18..73c608fd8 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridResultSetModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridResultSetModifier.java @@ -30,20 +30,20 @@ import org.slf4j.LoggerFactory; */ public class CubridResultSetModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public CubridResultSetModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public CubridResultSetModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - public String getTargetClass() { - return "cubrid/jdbc/driver/CUBRIDResultSet"; - } + public String getTargetClass() { + return "cubrid/jdbc/driver/CUBRIDResultSet"; + } - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } - return null; - } + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } + return null; + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridStatementModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridStatementModifier.java index b7eb72b04..ddc6e265f 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridStatementModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridStatementModifier.java @@ -36,22 +36,22 @@ import org.slf4j.LoggerFactory; */ public class CubridStatementModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public CubridStatementModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public CubridStatementModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - public String getTargetClass() { - return "cubrid/jdbc/driver/CUBRIDStatement"; - } + public String getTargetClass() { + return "cubrid/jdbc/driver/CUBRIDStatement"; + } - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } - try { - InstrumentClass statementClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } + try { + InstrumentClass statementClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); Interceptor executeQueryInterceptor = new StatementExecuteQueryInterceptor(); statementClass.addScopeInterceptor("executeQuery", new String[]{"java.lang.String"}, executeQueryInterceptor, CubridScope.SCOPE_NAME); @@ -60,22 +60,22 @@ public class CubridStatementModifier extends AbstractModifier { statementClass.addScopeInterceptor("executeUpdate", new String[]{"java.lang.String"}, executeUpdateInterceptor1, CubridScope.SCOPE_NAME); Interceptor executeUpdateInterceptor2 = new StatementExecuteUpdateInterceptor(); - statementClass.addScopeInterceptor("executeUpdate", new String[]{"java.lang.String", "int"}, executeUpdateInterceptor2, CubridScope.SCOPE_NAME); + statementClass.addScopeInterceptor("executeUpdate", new String[]{"java.lang.String", "int"}, executeUpdateInterceptor2, CubridScope.SCOPE_NAME); Interceptor executeInterceptor1 = new StatementExecuteUpdateInterceptor(); statementClass.addScopeInterceptor("execute", new String[]{"java.lang.String"}, executeInterceptor1, CubridScope.SCOPE_NAME); Interceptor executeInterceptor2 = new StatementExecuteUpdateInterceptor(); - statementClass.addScopeInterceptor("execute", new String[]{"java.lang.String", "int"}, executeInterceptor2, CubridScope.SCOPE_NAME); + statementClass.addScopeInterceptor("execute", new String[]{"java.lang.String", "int"}, executeInterceptor2, CubridScope.SCOPE_NAME); statementClass.addTraceValue(DatabaseInfoTraceValue.class); - return statementClass.toBytecode(); - } catch (InstrumentException e) { - if (logger.isWarnEnabled()) { - logger.warn("{} modify fail. Cause:{}", this.getClass().getSimpleName(), e.getMessage(), e); - } - return null; - } - } + return statementClass.toBytecode(); + } catch (InstrumentException e) { + if (logger.isWarnEnabled()) { + logger.warn("{} modify fail. Cause:{}", this.getClass().getSimpleName(), e.getMessage(), e); + } + return null; + } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridUStatementModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridUStatementModifier.java index cb2a01fcb..6308cce7a 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridUStatementModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/db/cubrid/CubridUStatementModifier.java @@ -34,30 +34,30 @@ import org.slf4j.LoggerFactory; */ public class CubridUStatementModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public CubridUStatementModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public CubridUStatementModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - public String getTargetClass() { - return "cubrid/jdbc/jci/UStatement"; - } + public String getTargetClass() { + return "cubrid/jdbc/jci/UStatement"; + } - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } - try { - InstrumentClass ustatementClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + try { + InstrumentClass ustatementClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); - return ustatementClass.toBytecode(); - } catch (InstrumentException e) { - if (logger.isWarnEnabled()) { - logger.warn("{} modify fail. Cause:{}", this.getClass().getSimpleName(), e.getMessage(), e); - } - return null; - } - } + return ustatementClass.toBytecode(); + } catch (InstrumentException e) { + if (logger.isWarnEnabled()) { + logger.warn("{} modify fail. Cause:{}", this.getClass().getSimpleName(), e.getMessage(), e); + } + return null; + } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/method/MethodModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/method/MethodModifier.java index 044ff74a8..55102b2fa 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/method/MethodModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/method/MethodModifier.java @@ -39,41 +39,41 @@ import org.slf4j.LoggerFactory; */ public class MethodModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public MethodModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public MethodModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - public String getTargetClass() { - return "*"; - } + public String getTargetClass() { + return "*"; + } - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } - try { - InstrumentClass clazz = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + try { + InstrumentClass clazz = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); - if (!clazz.isInterceptable()) { - return null; - } + if (!clazz.isInterceptable()) { + return null; + } - List methodList = clazz.getDeclaredMethods(EmptyMethodFilter.FILTER); - for (MethodInfo method : methodList) { - final Interceptor interceptor = new MethodInterceptor(); + List methodList = clazz.getDeclaredMethods(EmptyMethodFilter.FILTER); + for (MethodInfo method : methodList) { + final Interceptor interceptor = new MethodInterceptor(); if (logger.isTraceEnabled()) { logger.trace("### c={}, m={}, params={}", javassistClassName, method.getName(), Arrays.toString(method.getParameterTypes())); } - clazz.addInterceptor(method.getName(), method.getParameterTypes(), interceptor); - } + clazz.addInterceptor(method.getName(), method.getParameterTypes(), interceptor); + } - return clazz.toBytecode(); - } catch (Exception e) { - logger.warn("modify fail. Cause:{}", e.getMessage(), e); - return null; - } - } + return clazz.toBytecode(); + } catch (Exception e) { + logger.warn("modify fail. Cause:{}", e.getMessage(), e); + return null; + } + } } \ No newline at end of file diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/method/interceptor/MethodInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/method/interceptor/MethodInterceptor.java index ac686de39..12c533b00 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/method/interceptor/MethodInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/method/interceptor/MethodInterceptor.java @@ -30,21 +30,21 @@ import com.navercorp.pinpoint.common.ServiceType; */ public class MethodInterceptor implements SimpleAroundInterceptor, ServiceTypeSupport, ByteCodeMethodDescriptorSupport, TraceContextSupport { - private final PLogger logger = PLoggerFactory.getLogger(MethodInterceptor.class); + private final PLogger logger = PLoggerFactory.getLogger(MethodInterceptor.class); private final boolean isDebug = logger.isDebugEnabled(); - private MethodDescriptor descriptor; - private TraceContext traceContext; + private MethodDescriptor descriptor; + private TraceContext traceContext; private ServiceType serviceType = ServiceType.INTERNAL_METHOD; - @Override - public void before(Object target, Object[] args) { - if (isDebug) { - logger.beforeInterceptor(target, args); - } + @Override + public void before(Object target, Object[] args) { + if (isDebug) { + logger.beforeInterceptor(target, args); + } - Trace trace = traceContext.currentTraceObject(); + Trace trace = traceContext.currentTraceObject(); if (trace == null) { return; } @@ -53,18 +53,18 @@ public class MethodInterceptor implements SimpleAroundInterceptor, ServiceTypeSu trace.markBeforeTime(); trace.recordServiceType(serviceType); - } + } - @Override - public void after(Object target, Object[] args, Object result, Throwable throwable) { - if (isDebug) { + @Override + public void after(Object target, Object[] args, Object result, Throwable throwable) { + if (isDebug) { logger.afterInterceptor(target, args); - } + } - Trace trace = traceContext.currentTraceObject(); - if (trace == null) { - return; - } + Trace trace = traceContext.currentTraceObject(); + if (trace == null) { + return; + } try { trace.recordApi(descriptor); @@ -74,20 +74,20 @@ public class MethodInterceptor implements SimpleAroundInterceptor, ServiceTypeSu } finally { trace.traceBlockEnd(); } - } + } public void setServiceType(ServiceType serviceType) { this.serviceType = serviceType; } @Override - public void setMethodDescriptor(MethodDescriptor descriptor) { - this.descriptor = descriptor; + public void setMethodDescriptor(MethodDescriptor descriptor) { + this.descriptor = descriptor; this.traceContext.cacheApi(descriptor); } - @Override - public void setTraceContext(TraceContext traceContext) { - this.traceContext = traceContext; + @Override + public void setTraceContext(TraceContext traceContext) { + this.traceContext = traceContext; } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/SqlMapOperationInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/SqlMapOperationInterceptor.java index 0ef054c9c..6515de7ce 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/SqlMapOperationInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/SqlMapOperationInterceptor.java @@ -26,20 +26,20 @@ import com.navercorp.pinpoint.common.ServiceType; */ public abstract class SqlMapOperationInterceptor extends SpanEventSimpleAroundInterceptor { - private final ServiceType serviceType; + private final ServiceType serviceType; - public SqlMapOperationInterceptor(ServiceType serviceType, Class childClazz) { + public SqlMapOperationInterceptor(ServiceType serviceType, Class childClazz) { super(childClazz); - this.serviceType = serviceType; - } - - @Override - public final void doInBeforeTrace(RecordableTrace trace, final Object target, Object[] args) { - trace.markBeforeTime(); - } + this.serviceType = serviceType; + } - @Override - public final void doInAfterTrace(RecordableTrace trace, Object target, Object[] args, Object result, Throwable throwable) { + @Override + public final void doInBeforeTrace(RecordableTrace trace, final Object target, Object[] args) { + trace.markBeforeTime(); + } + + @Override + public final void doInAfterTrace(RecordableTrace trace, Object target, Object[] args, Object result, Throwable throwable) { trace.recordServiceType(this.serviceType); trace.recordException(throwable); if (args != null && args.length > 0) { @@ -48,6 +48,6 @@ public abstract class SqlMapOperationInterceptor extends SpanEventSimpleAroundIn trace.recordApi(getMethodDescriptor()); } trace.markAfterTime(); - } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/IbatisClientModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/IbatisClientModifier.java index 8ec9f74cf..7e0f94ce1 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/IbatisClientModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/IbatisClientModifier.java @@ -39,35 +39,35 @@ import com.navercorp.pinpoint.profiler.modifier.orm.ibatis.interceptor.IbatisSql */ public abstract class IbatisClientModifier extends AbstractModifier { - private static final ServiceType serviceType = ServiceType.IBATIS; - private static final String SCOPE = IbatisScope.SCOPE; + private static final ServiceType serviceType = ServiceType.IBATIS; + private static final String SCOPE = IbatisScope.SCOPE; protected Logger logger; protected abstract MethodFilter getIbatisApiMethodFilter(); - public IbatisClientModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public IbatisClientModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - @Override - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { + @Override + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { logger.info("Modifying. {}", javassistClassName); - } - try { - InstrumentClass ibatisClientImpl = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); - List declaredMethods = ibatisClientImpl.getDeclaredMethods(getIbatisApiMethodFilter()); + } + try { + InstrumentClass ibatisClientImpl = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + List declaredMethods = ibatisClientImpl.getDeclaredMethods(getIbatisApiMethodFilter()); - for (MethodInfo method : declaredMethods) { - Interceptor ibatisApiInterceptor = new IbatisSqlMapOperationInterceptor(serviceType); - ibatisClientImpl.addScopeInterceptor(method.getName(), method.getParameterTypes(), ibatisApiInterceptor, SCOPE); - } - - return ibatisClientImpl.toBytecode(); - } catch (Throwable e) { - this.logger.warn("{} modifier error. Cause:{}", javassistClassName, e.getMessage(), e); - return null; - } - } + for (MethodInfo method : declaredMethods) { + Interceptor ibatisApiInterceptor = new IbatisSqlMapOperationInterceptor(serviceType); + ibatisClientImpl.addScopeInterceptor(method.getName(), method.getParameterTypes(), ibatisApiInterceptor, SCOPE); + } + + return ibatisClientImpl.toBytecode(); + } catch (Throwable e) { + this.logger.warn("{} modifier error. Cause:{}", javassistClassName, e.getMessage(), e); + return null; + } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/SqlMapClientImplModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/SqlMapClientImplModifier.java index 9e4177602..999714e79 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/SqlMapClientImplModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/SqlMapClientImplModifier.java @@ -33,24 +33,24 @@ import com.navercorp.pinpoint.profiler.modifier.orm.ibatis.filter.SqlMapClientMe */ public final class SqlMapClientImplModifier extends IbatisClientModifier { - private static final MethodFilter sqlMapClientMethodFilter = new SqlMapClientMethodFilter(); - - public static final String TARGET_CLASS_NAME = "com/ibatis/sqlmap/engine/impl/SqlMapClientImpl"; + private static final MethodFilter sqlMapClientMethodFilter = new SqlMapClientMethodFilter(); - public SqlMapClientImplModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); + public static final String TARGET_CLASS_NAME = "com/ibatis/sqlmap/engine/impl/SqlMapClientImpl"; + + public SqlMapClientImplModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); this.logger = LoggerFactory.getLogger(this.getClass()); - } + } - @Override - public String getTargetClass() { - return TARGET_CLASS_NAME; - } + @Override + public String getTargetClass() { + return TARGET_CLASS_NAME; + } - @Override - protected MethodFilter getIbatisApiMethodFilter() { - return sqlMapClientMethodFilter; - } + @Override + protected MethodFilter getIbatisApiMethodFilter() { + return sqlMapClientMethodFilter; + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/SqlMapSessionImplModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/SqlMapSessionImplModifier.java index 6fa808394..104edecb7 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/SqlMapSessionImplModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/SqlMapSessionImplModifier.java @@ -33,24 +33,24 @@ import com.navercorp.pinpoint.profiler.modifier.orm.ibatis.filter.SqlMapSessionM */ public final class SqlMapSessionImplModifier extends IbatisClientModifier { - private static final MethodFilter sqlMapSessionMethodFilter = new SqlMapSessionMethodFilter(); + private static final MethodFilter sqlMapSessionMethodFilter = new SqlMapSessionMethodFilter(); - public static final String TARGET_CLASS_NAME = "com/ibatis/sqlmap/engine/impl/SqlMapSessionImpl"; + public static final String TARGET_CLASS_NAME = "com/ibatis/sqlmap/engine/impl/SqlMapSessionImpl"; - public SqlMapSessionImplModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); + public SqlMapSessionImplModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); this.logger = LoggerFactory.getLogger(this.getClass()); } - @Override - public String getTargetClass() { - return TARGET_CLASS_NAME; - } + @Override + public String getTargetClass() { + return TARGET_CLASS_NAME; + } - @Override - protected MethodFilter getIbatisApiMethodFilter() { - return sqlMapSessionMethodFilter; - } + @Override + protected MethodFilter getIbatisApiMethodFilter() { + return sqlMapSessionMethodFilter; + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/filter/IbatisInterfaceApi.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/filter/IbatisInterfaceApi.java index 6e0e4ca77..d106ef6ab 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/filter/IbatisInterfaceApi.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/filter/IbatisInterfaceApi.java @@ -20,36 +20,36 @@ package com.navercorp.pinpoint.profiler.modifier.orm.ibatis.filter; * @author Hyun Jeong */ public final class IbatisInterfaceApi { - - private IbatisInterfaceApi() {} - private static final String[] sqlMapExecutorApis = { - "insert", - "delete", - "update", - "queryForList", - "queryForMap", - "queryForObject", - "queryForPaginatedList", - "queryForRowHandler" - }; -// private static final String[] sqlMapTransactionManagerApis = { -// "startTransaction", -// "endTransaction", -// "commitTransaction", -// "getDataSource", -// "getUserConnection", -// "getCurrentConnection", -// }; -// static final String[] sqlMapSessionApis = ArrayUtils.addAll( -// ArrayUtils.addAll(sqlMapExecutorApis, sqlMapTransactionManagerApis), -// "close" -// ); - static final String[] sqlMapSessionApis = sqlMapExecutorApis; -// static final String[] sqlMapClientApis = ArrayUtils.addAll( -// sqlMapExecutorApis, -// sqlMapTransactionManagerApis -// ); - static final String[] sqlMapClientApis = sqlMapExecutorApis; - + private IbatisInterfaceApi() {} + + private static final String[] sqlMapExecutorApis = { + "insert", + "delete", + "update", + "queryForList", + "queryForMap", + "queryForObject", + "queryForPaginatedList", + "queryForRowHandler" + }; +// private static final String[] sqlMapTransactionManagerApis = { +// "startTransaction", +// "endTransaction", +// "commitTransaction", +// "getDataSource", +// "getUserConnection", +// "getCurrentConnection", +// }; +// static final String[] sqlMapSessionApis = ArrayUtils.addAll( +// ArrayUtils.addAll(sqlMapExecutorApis, sqlMapTransactionManagerApis), +// "close" +// ); + static final String[] sqlMapSessionApis = sqlMapExecutorApis; +// static final String[] sqlMapClientApis = ArrayUtils.addAll( +// sqlMapExecutorApis, +// sqlMapTransactionManagerApis +// ); + static final String[] sqlMapClientApis = sqlMapExecutorApis; + } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/filter/IbatisMethodFilter.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/filter/IbatisMethodFilter.java index 4e309c8f8..07335f1bd 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/filter/IbatisMethodFilter.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/filter/IbatisMethodFilter.java @@ -26,42 +26,42 @@ import com.navercorp.pinpoint.bootstrap.instrument.MethodInfo; */ public abstract class IbatisMethodFilter implements MethodFilter { - private static final boolean TRACK = false; - private static final boolean DO_NOT_TRACK = true; + private static final boolean TRACK = false; + private static final boolean DO_NOT_TRACK = true; - protected abstract boolean shouldTrackMethod(String methodName); + protected abstract boolean shouldTrackMethod(String methodName); - @Override - public boolean filter(MethodInfo ctMethod) { - final int modifiers = ctMethod.getModifiers(); - if (!Modifier.isPublic(modifiers) || Modifier.isStatic(modifiers) || Modifier.isAbstract(modifiers) || Modifier.isNative(modifiers)) { - return DO_NOT_TRACK; - } - return filterApiForTracking(ctMethod); - } + @Override + public boolean filter(MethodInfo ctMethod) { + final int modifiers = ctMethod.getModifiers(); + if (!Modifier.isPublic(modifiers) || Modifier.isStatic(modifiers) || Modifier.isAbstract(modifiers) || Modifier.isNative(modifiers)) { + return DO_NOT_TRACK; + } + return filterApiForTracking(ctMethod); + } - private boolean filterApiForTracking(MethodInfo ctMethod) { - if (!shouldTrackMethod(ctMethod.getName())) { - return DO_NOT_TRACK; - } + private boolean filterApiForTracking(MethodInfo ctMethod) { + if (!shouldTrackMethod(ctMethod.getName())) { + return DO_NOT_TRACK; + } - final int parameterIndexToMatch = 0; // 0-based index - String[] parameterTypes = ctMethod.getParameterTypes(); - if (parameterTypes != null && parameterTypes.length > 0) { - return parameterTypeMatches(parameterTypes, parameterIndexToMatch, String.class); - } else { - return TRACK; - } - } + final int parameterIndexToMatch = 0; // 0-based index + String[] parameterTypes = ctMethod.getParameterTypes(); + if (parameterTypes != null && parameterTypes.length > 0) { + return parameterTypeMatches(parameterTypes, parameterIndexToMatch, String.class); + } else { + return TRACK; + } + } - private boolean parameterTypeMatches(final String[] parameterTypes, final int parameterIndex, final Class parameterType) { - if (parameterTypes == null || parameterTypes.length <= parameterIndex) { - return DO_NOT_TRACK; - } - if (parameterType.getName().equals(parameterTypes[parameterIndex])) { - return TRACK; - } - return DO_NOT_TRACK; - } + private boolean parameterTypeMatches(final String[] parameterTypes, final int parameterIndex, final Class parameterType) { + if (parameterTypes == null || parameterTypes.length <= parameterIndex) { + return DO_NOT_TRACK; + } + if (parameterType.getName().equals(parameterTypes[parameterIndex])) { + return TRACK; + } + return DO_NOT_TRACK; + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/filter/SqlMapClientMethodFilter.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/filter/SqlMapClientMethodFilter.java index 970fba2cd..dd6f2cebb 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/filter/SqlMapClientMethodFilter.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/filter/SqlMapClientMethodFilter.java @@ -25,13 +25,13 @@ import java.util.Set; */ public class SqlMapClientMethodFilter extends IbatisMethodFilter { - private static final Set WHITE_LIST_API = createWhiteListApi(); + private static final Set WHITE_LIST_API = createWhiteListApi(); - private static Set createWhiteListApi() { - return new HashSet(Arrays.asList(IbatisInterfaceApi.sqlMapClientApis)); - } - - protected final boolean shouldTrackMethod(String methodName) { - return WHITE_LIST_API.contains(methodName); - } + private static Set createWhiteListApi() { + return new HashSet(Arrays.asList(IbatisInterfaceApi.sqlMapClientApis)); + } + + protected final boolean shouldTrackMethod(String methodName) { + return WHITE_LIST_API.contains(methodName); + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/filter/SqlMapSessionMethodFilter.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/filter/SqlMapSessionMethodFilter.java index c142c54b0..765978022 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/filter/SqlMapSessionMethodFilter.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/filter/SqlMapSessionMethodFilter.java @@ -24,16 +24,16 @@ import java.util.Set; * @author Hyun Jeong */ public class SqlMapSessionMethodFilter extends IbatisMethodFilter { - - private static final Set WHITE_LIST_API = createWhiteListApi(); - private static Set createWhiteListApi() { - return new HashSet(Arrays.asList(IbatisInterfaceApi.sqlMapSessionApis)); - } - - @Override - protected boolean shouldTrackMethod(String methodName) { - return WHITE_LIST_API.contains(methodName); - } + private static final Set WHITE_LIST_API = createWhiteListApi(); + + private static Set createWhiteListApi() { + return new HashSet(Arrays.asList(IbatisInterfaceApi.sqlMapSessionApis)); + } + + @Override + protected boolean shouldTrackMethod(String methodName) { + return WHITE_LIST_API.contains(methodName); + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/interceptor/IbatisSqlMapOperationInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/interceptor/IbatisSqlMapOperationInterceptor.java index 5c1faa2f2..9de753e71 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/interceptor/IbatisSqlMapOperationInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/interceptor/IbatisSqlMapOperationInterceptor.java @@ -25,8 +25,8 @@ import com.navercorp.pinpoint.profiler.modifier.orm.SqlMapOperationInterceptor; */ public class IbatisSqlMapOperationInterceptor extends SqlMapOperationInterceptor { - public IbatisSqlMapOperationInterceptor(ServiceType serviceType) { - super(serviceType, IbatisSqlMapOperationInterceptor.class); - } + public IbatisSqlMapOperationInterceptor(ServiceType serviceType) { + super(serviceType, IbatisSqlMapOperationInterceptor.class); + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/SqlSessionTemplateModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/SqlSessionTemplateModifier.java index b592d25bd..dc53a88ad 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/SqlSessionTemplateModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/SqlSessionTemplateModifier.java @@ -24,16 +24,16 @@ import com.navercorp.pinpoint.bootstrap.instrument.ByteCodeInstrumentor; */ public class SqlSessionTemplateModifier extends MyBatisClientModifier { - public static final String TARGET_CLASS_NAME = "org/mybatis/spring/SqlSessionTemplate"; + public static final String TARGET_CLASS_NAME = "org/mybatis/spring/SqlSessionTemplate"; - public SqlSessionTemplateModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent, SqlSessionTemplateModifier.class); - } + public SqlSessionTemplateModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent, SqlSessionTemplateModifier.class); + } - @Override - public String getTargetClass() { - return TARGET_CLASS_NAME; - } + @Override + public String getTargetClass() { + return TARGET_CLASS_NAME; + } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/filter/SqlSessionMethodFilter.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/filter/SqlSessionMethodFilter.java index 92517abb2..06869ff8d 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/filter/SqlSessionMethodFilter.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/filter/SqlSessionMethodFilter.java @@ -28,36 +28,36 @@ import com.navercorp.pinpoint.bootstrap.instrument.MethodInfo; */ public class SqlSessionMethodFilter implements MethodFilter { - private static final boolean TRACK = false; - private static final boolean DO_NOT_TRACK = true; - - private static final Set WHITE_LIST_API = createWhiteListApi(); - - private static Set createWhiteListApi() { - return new HashSet(Arrays.asList( - "selectOne", - "selectList", - "selectMap", - "select", - "insert", - "update", - "delete" -// "commit", -// "rollback", -// "flushStatements", -// "close", -// "getConfiguration", -// "getMapper", -// "getConnection" - )); - } + private static final boolean TRACK = false; + private static final boolean DO_NOT_TRACK = true; + + private static final Set WHITE_LIST_API = createWhiteListApi(); + + private static Set createWhiteListApi() { + return new HashSet(Arrays.asList( + "selectOne", + "selectList", + "selectMap", + "select", + "insert", + "update", + "delete" +// "commit", +// "rollback", +// "flushStatements", +// "close", +// "getConfiguration", +// "getMapper", +// "getConnection" + )); + } + + @Override + public boolean filter(MethodInfo ctMethod) { + if (WHITE_LIST_API.contains(ctMethod.getName())) { + return TRACK; + } + return DO_NOT_TRACK; + } - @Override - public boolean filter(MethodInfo ctMethod) { - if (WHITE_LIST_API.contains(ctMethod.getName())) { - return TRACK; - } - return DO_NOT_TRACK; - } - } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/interceptor/MyBatisSqlMapOperationInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/interceptor/MyBatisSqlMapOperationInterceptor.java index 9a389e5ae..9784e1f9a 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/interceptor/MyBatisSqlMapOperationInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/interceptor/MyBatisSqlMapOperationInterceptor.java @@ -24,9 +24,9 @@ import com.navercorp.pinpoint.profiler.modifier.orm.SqlMapOperationInterceptor; * @author netspider */ public class MyBatisSqlMapOperationInterceptor extends SqlMapOperationInterceptor { - - public MyBatisSqlMapOperationInterceptor(ServiceType serviceType) { - super(serviceType, MyBatisSqlMapOperationInterceptor.class); - } + + public MyBatisSqlMapOperationInterceptor(ServiceType serviceType) { + super(serviceType, MyBatisSqlMapOperationInterceptor.class); + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/servlet/FilterModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/servlet/FilterModifier.java index 5d7a444ef..a552761b5 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/servlet/FilterModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/servlet/FilterModifier.java @@ -36,34 +36,34 @@ import org.slf4j.LoggerFactory; */ public class FilterModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public FilterModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public FilterModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - public String getTargetClass() { - return "javax/servlet/Filter"; - } + public String getTargetClass() { + return "javax/servlet/Filter"; + } - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } - try { - Interceptor doFilterInterceptor = new MethodInterceptor(); + try { + Interceptor doFilterInterceptor = new MethodInterceptor(); -// setTraceContext(doFilterInterceptor); +// setTraceContext(doFilterInterceptor); - InstrumentClass servlet = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + InstrumentClass servlet = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); - servlet.addInterceptor("doFilter", new String[] { "javax.servlet.ServletRequest", "javax.servlet.ServletResponse", "javax.servlet.FilterChain" }, doFilterInterceptor); + servlet.addInterceptor("doFilter", new String[] { "javax.servlet.ServletRequest", "javax.servlet.ServletResponse", "javax.servlet.FilterChain" }, doFilterInterceptor); - return servlet.toBytecode(); - } catch (InstrumentException e) { - logger.warn("modify fail. Cause:{}", e.getMessage(), e); - return null; - } - } + return servlet.toBytecode(); + } catch (InstrumentException e) { + logger.warn("modify fail. Cause:{}", e.getMessage(), e); + return null; + } + } } \ No newline at end of file diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/servlet/HttpServletModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/servlet/HttpServletModifier.java index f169482bf..b1ea5ea63 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/servlet/HttpServletModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/servlet/HttpServletModifier.java @@ -36,34 +36,34 @@ import org.slf4j.LoggerFactory; */ public class HttpServletModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public HttpServletModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public HttpServletModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - public String getTargetClass() { - return "javax/servlet/http/HttpServlet"; - } + public String getTargetClass() { + return "javax/servlet/http/HttpServlet"; + } - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } - try { - InstrumentClass servlet = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + try { + InstrumentClass servlet = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); Interceptor doGetInterceptor = new MethodInterceptor(); - servlet.addInterceptor("doGet", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, doGetInterceptor); + servlet.addInterceptor("doGet", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, doGetInterceptor); Interceptor doPostInterceptor = new MethodInterceptor(); - servlet.addInterceptor("doPost", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, doPostInterceptor); + servlet.addInterceptor("doPost", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, doPostInterceptor); - return servlet.toBytecode(); - } catch (InstrumentException e) { - logger.info("modify fail. Cause:{}", e.getMessage(), e); - return null; - } - } + return servlet.toBytecode(); + } catch (InstrumentException e) { + logger.info("modify fail. Cause:{}", e.getMessage(), e); + return null; + } + } } \ No newline at end of file diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/servlet/SpringFrameworkServletModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/servlet/SpringFrameworkServletModifier.java index 9a0d76639..5b97b34b1 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/servlet/SpringFrameworkServletModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/servlet/SpringFrameworkServletModifier.java @@ -38,23 +38,23 @@ import org.slf4j.LoggerFactory; */ public class SpringFrameworkServletModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public SpringFrameworkServletModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public SpringFrameworkServletModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - public String getTargetClass() { - return "org/springframework/web/servlet/FrameworkServlet"; - } + public String getTargetClass() { + return "org/springframework/web/servlet/FrameworkServlet"; + } - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } - try { - Interceptor doGetInterceptor = new MethodInterceptor(); + try { + Interceptor doGetInterceptor = new MethodInterceptor(); setServiceType(doGetInterceptor, ServiceType.SPRING_MVC); Interceptor doPostInterceptor = new MethodInterceptor(); @@ -62,17 +62,17 @@ public class SpringFrameworkServletModifier extends AbstractModifier { - InstrumentClass servlet = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); - servlet.addInterceptor("doGet", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, doGetInterceptor); + InstrumentClass servlet = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + servlet.addInterceptor("doGet", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, doGetInterceptor); - servlet.addInterceptor("doPost", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, doPostInterceptor); + servlet.addInterceptor("doPost", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, doPostInterceptor); - return servlet.toBytecode(); - } catch (InstrumentException e) { - logger.warn("modify fail. Cause:{}", e.getMessage(), e); - return null; - } - } + return servlet.toBytecode(); + } catch (InstrumentException e) { + logger.warn("modify fail. Cause:{}", e.getMessage(), e); + return null; + } + } private void setServiceType(Interceptor interceptor, ServiceType serviceType) { if (interceptor instanceof ServiceTypeSupport) { diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/servlet/interceptor/HttpServletInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/servlet/interceptor/HttpServletInterceptor.java index 353223531..4ea91a9a8 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/servlet/interceptor/HttpServletInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/servlet/interceptor/HttpServletInterceptor.java @@ -50,27 +50,27 @@ public class HttpServletInterceptor implements SimpleAroundInterceptor, ByteCode /* java.lang.IllegalStateException: already Trace Object exist. - at com.profiler.context.TraceContext.attachTraceObject(TraceContext.java:54) - at HttpServletInterceptor.before(HttpServletInterceptor.java:62) - at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java) // profile method -** at javax.servlet.http.HttpServlet.service(HttpServlet.java:617) // profile method - at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) - at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) - at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) - at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) - at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) - at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) - at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) - at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) - at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) -** at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) // make traceId here - at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) - at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) - at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) - at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859) - at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602) - at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) - at java.lang.Thread.run(Thread.java:680) + at com.profiler.context.TraceContext.attachTraceObject(TraceContext.java:54) + at HttpServletInterceptor.before(HttpServletInterceptor.java:62) + at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java) // profile method +** at javax.servlet.http.HttpServlet.service(HttpServlet.java:617) // profile method + at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) + at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) + at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) + at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) + at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) + at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) + at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) + at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) + at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) +** at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) // make traceId here + at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) + at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) + at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) + at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859) + at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602) + at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) + at java.lang.Thread.run(Thread.java:680) */ @Override public void before(Object target, Object[] args) { @@ -113,10 +113,10 @@ public class HttpServletInterceptor implements SimpleAroundInterceptor, ByteCode } else { trace = traceContext.newTraceObject(); if (!trace.canSampled()){ - if (isDebug) { - logger.debug("TraceID not exist. camSampled is false. skip trace. requestUrl:{}, remoteAddr:{}", new Object[]{requestURL, remoteAddr}); - } - return; + if (isDebug) { + logger.debug("TraceID not exist. camSampled is false. skip trace. requestUrl:{}, remoteAddr:{}", new Object[]{requestURL, remoteAddr}); + } + return; } else { if (isDebug) { logger.debug("TraceID not exist. start new trace. requestUrl:{}, remoteAddr:{}", new Object[]{requestURL, remoteAddr}); diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/spring/orm/ibatis/SqlMapClientTemplateModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/spring/orm/ibatis/SqlMapClientTemplateModifier.java index 3d5ef61b1..a740af180 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/spring/orm/ibatis/SqlMapClientTemplateModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/spring/orm/ibatis/SqlMapClientTemplateModifier.java @@ -45,42 +45,42 @@ import com.navercorp.pinpoint.profiler.modifier.orm.ibatis.interceptor.IbatisSql */ public final class SqlMapClientTemplateModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private static final ServiceType serviceType = ServiceType.SPRING_ORM_IBATIS; - private static final String SCOPE = IbatisScope.SCOPE; - private static final MethodFilter sqlMapClientMethodFilter = new SqlMapClientMethodFilter(); + private static final ServiceType serviceType = ServiceType.SPRING_ORM_IBATIS; + private static final String SCOPE = IbatisScope.SCOPE; + private static final MethodFilter sqlMapClientMethodFilter = new SqlMapClientMethodFilter(); - public static final String TARGET_CLASS_NAME = "org/springframework/orm/ibatis/SqlMapClientTemplate"; + public static final String TARGET_CLASS_NAME = "org/springframework/orm/ibatis/SqlMapClientTemplate"; - public SqlMapClientTemplateModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public SqlMapClientTemplateModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - @Override - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (this.logger.isInfoEnabled()) { - this.logger.info("Modifying. {}", javassistClassName); - } - try { - InstrumentClass sqlMapClientTemplate = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); - List declaredMethods = sqlMapClientTemplate.getDeclaredMethods(sqlMapClientMethodFilter); - - for (MethodInfo method : declaredMethods) { - Interceptor sqlMapClientTemplateInterceptor = new IbatisSqlMapOperationInterceptor(serviceType); - sqlMapClientTemplate.addScopeInterceptor(method.getName(), method.getParameterTypes(), sqlMapClientTemplateInterceptor, SCOPE); - } - - return sqlMapClientTemplate.toBytecode(); - } catch (Throwable e) { - this.logger.warn("{} modifier error. Cause:{}", javassistClassName, e.getMessage(), e); - return null; - } - } + @Override + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (this.logger.isInfoEnabled()) { + this.logger.info("Modifying. {}", javassistClassName); + } + try { + InstrumentClass sqlMapClientTemplate = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + List declaredMethods = sqlMapClientTemplate.getDeclaredMethods(sqlMapClientMethodFilter); - @Override - public String getTargetClass() { - return TARGET_CLASS_NAME; - } + for (MethodInfo method : declaredMethods) { + Interceptor sqlMapClientTemplateInterceptor = new IbatisSqlMapOperationInterceptor(serviceType); + sqlMapClientTemplate.addScopeInterceptor(method.getName(), method.getParameterTypes(), sqlMapClientTemplateInterceptor, SCOPE); + } + + return sqlMapClientTemplate.toBytecode(); + } catch (Throwable e) { + this.logger.warn("{} modifier error. Cause:{}", javassistClassName, e.getMessage(), e); + return null; + } + } + + @Override + public String getTargetClass() { + return TARGET_CLASS_NAME; + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/RequestFacadeModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/RequestFacadeModifier.java index e372bc7a0..33f490276 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/RequestFacadeModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/RequestFacadeModifier.java @@ -32,29 +32,29 @@ import java.security.ProtectionDomain; */ public class RequestFacadeModifier extends AbstractModifier { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public RequestFacadeModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { - super(byteCodeInstrumentor, agent); - } + public RequestFacadeModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { + super(byteCodeInstrumentor, agent); + } - public String getTargetClass() { - return "org/apache/catalina/connector/RequestFacade"; - } + public String getTargetClass() { + return "org/apache/catalina/connector/RequestFacade"; + } - public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { - if (logger.isInfoEnabled()) { - logger.info("Modifing. {}", javassistClassName); - } + public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { + if (logger.isInfoEnabled()) { + logger.info("Modifing. {}", javassistClassName); + } - try { - InstrumentClass requestFacade = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); - requestFacade.weaving("com.navercorp.pinpoint.profiler.modifier.tomcat.aspect.RequestFacadeAspect"); - return requestFacade.toBytecode(); - } catch (InstrumentException e) { - logger.warn("modify fail. Cause:" + e.getMessage(), e); - return null; - } - } + try { + InstrumentClass requestFacade = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + requestFacade.weaving("com.navercorp.pinpoint.profiler.modifier.tomcat.aspect.RequestFacadeAspect"); + return requestFacade.toBytecode(); + } catch (InstrumentException e) { + logger.warn("modify fail. Cause:" + e.getMessage(), e); + return null; + } + } } \ No newline at end of file diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/StandardServiceModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/StandardServiceModifier.java index beaa1258b..70f38a211 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/StandardServiceModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/StandardServiceModifier.java @@ -64,13 +64,13 @@ public class StandardServiceModifier extends AbstractModifier { if (standardService.hasDeclaredMethod("start", null) && standardService.hasDeclaredMethod("stop", null)) { standardService.addInterceptor("start", null, standardServiceStartInterceptor); standardService.addInterceptor("stop", null, standardServiceStopInterceptor); - isHooked = true; + isHooked = true; } // Tomcat 7, 8 - org.apache.catalina.core.StandardService.startInternal(), stopInternal() else if (standardService.hasDeclaredMethod("startInternal", null) && standardService.hasDeclaredMethod("stopInternal", null)) { standardService.addInterceptor("startInternal", null, standardServiceStartInterceptor); standardService.addInterceptor("stopInternal", null, standardServiceStopInterceptor); - isHooked = true; + isHooked = true; } if (isHooked) { diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/TomcatConnectorModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/TomcatConnectorModifier.java index f0bcbf6fe..e58809adc 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/TomcatConnectorModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/TomcatConnectorModifier.java @@ -50,19 +50,19 @@ public class TomcatConnectorModifier extends AbstractModifier { } try { - // Get protocol and port by intercepting initialize() - Interceptor interceptor = byteCodeInstrumentor.newInterceptor(classLoader, protectedDomain, + // Get protocol and port by intercepting initialize() + Interceptor interceptor = byteCodeInstrumentor.newInterceptor(classLoader, protectedDomain, "com.navercorp.pinpoint.profiler.modifier.tomcat.interceptor.ConnectorInitializeInterceptor", null, null); - InstrumentClass connector = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); + InstrumentClass connector = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); - // Tomcat 6 - if (connector.hasDeclaredMethod("initialize", null)) { - connector.addInterceptor("initialize", null, interceptor); - } - // Tomcat 7 - else if (connector.hasDeclaredMethod("initInternal", null)) { - connector.addInterceptor("initInternal", null, interceptor); - } + // Tomcat 6 + if (connector.hasDeclaredMethod("initialize", null)) { + connector.addInterceptor("initialize", null, interceptor); + } + // Tomcat 7 + else if (connector.hasDeclaredMethod("initInternal", null)) { + connector.addInterceptor("initInternal", null, interceptor); + } if (this.logger.isInfoEnabled()) { this.logger.info("{} class is converted.", javassistClassName); diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/WebappLoaderModifier.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/WebappLoaderModifier.java index b37ea575b..d8ac0ffc3 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/WebappLoaderModifier.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/WebappLoaderModifier.java @@ -57,12 +57,12 @@ public class WebappLoaderModifier extends AbstractModifier { // Tomcat 6 - org.apache.catalina.loader.WebappLoader.start() if (webappLoader.hasDeclaredMethod("start", null)) { webappLoader.addInterceptor("start", null, webappLoaderStartInterceptor); - isHooked = true; + isHooked = true; } // Tomcat 7, 8 - org.apache.catalina.loader.WebappLoader.startInternal() else if (webappLoader.hasDeclaredMethod("startInternal", null)) { webappLoader.addInterceptor("startInternal", null, webappLoaderStartInterceptor); - isHooked = true; + isHooked = true; } if (isHooked) { diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/aspect/RequestFacadeAspect.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/aspect/RequestFacadeAspect.java index 1f96bec89..b34f95886 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/aspect/RequestFacadeAspect.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/aspect/RequestFacadeAspect.java @@ -30,38 +30,38 @@ import java.util.Enumeration; @Aspect public abstract class RequestFacadeAspect { - @PointCut - public String getHeader(String name) { - if (Header.hasHeader(name)) { - return null; - } - return __getHeader(name); - } + @PointCut + public String getHeader(String name) { + if (Header.hasHeader(name)) { + return null; + } + return __getHeader(name); + } - @JointPoint - abstract String __getHeader(String name); + @JointPoint + abstract String __getHeader(String name); - @PointCut - public Enumeration getHeaders(String name) { - final Enumeration headers = Header.getHeaders(name); - if (headers != null) { - return headers; - } - return __getHeaders(name); - } + @PointCut + public Enumeration getHeaders(String name) { + final Enumeration headers = Header.getHeaders(name); + if (headers != null) { + return headers; + } + return __getHeaders(name); + } - @JointPoint - abstract Enumeration __getHeaders(String name); + @JointPoint + abstract Enumeration __getHeaders(String name); - @PointCut - public Enumeration getHeaderNames() { - final Enumeration enumeration = __getHeaderNames(); - return Header.filteredHeaderNames(enumeration); - } + @PointCut + public Enumeration getHeaderNames() { + final Enumeration enumeration = __getHeaderNames(); + return Header.filteredHeaderNames(enumeration); + } - @JointPoint - abstract Enumeration __getHeaderNames(); + @JointPoint + abstract Enumeration __getHeaderNames(); } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/interceptor/StandardHostValveInvokeInterceptor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/interceptor/StandardHostValveInvokeInterceptor.java index c5904e041..346641bfb 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/interceptor/StandardHostValveInvokeInterceptor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/tomcat/interceptor/StandardHostValveInvokeInterceptor.java @@ -37,8 +37,8 @@ import javax.servlet.http.HttpServletRequest; */ public class StandardHostValveInvokeInterceptor extends SpanSimpleAroundInterceptor implements TargetClassLoader { - private final boolean isTrace = logger.isTraceEnabled(); - private Filter excludeUrlFilter; + private final boolean isTrace = logger.isTraceEnabled(); + private Filter excludeUrlFilter; public StandardHostValveInvokeInterceptor() { super(StandardHostValveInvokeInterceptor.class); @@ -127,7 +127,7 @@ public class StandardHostValveInvokeInterceptor extends SpanSimpleAroundIntercep - private void recordParentInfo(RecordableTrace trace, HttpServletRequest request) { + private void recordParentInfo(RecordableTrace trace, HttpServletRequest request) { String parentApplicationName = request.getHeader(Header.HTTP_PARENT_APPLICATION_NAME.toString()); if (parentApplicationName != null) { trace.recordAcceptorHost(NetworkUtils.getHostFromURL(request.getRequestURL().toString())); @@ -211,12 +211,12 @@ public class StandardHostValveInvokeInterceptor extends SpanSimpleAroundIntercep return params.toString(); } - @Override - public void setTraceContext(TraceContext traceContext) { - super.setTraceContext(traceContext); + @Override + public void setTraceContext(TraceContext traceContext) { + super.setTraceContext(traceContext); - ProfilerConfig profilerConfig = traceContext.getProfilerConfig(); + ProfilerConfig profilerConfig = traceContext.getProfilerConfig(); - this.excludeUrlFilter = profilerConfig.getTomcatExcludeUrlFilter(); - } + this.excludeUrlFilter = profilerConfig.getTomcatExcludeUrlFilter(); + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/CounterMonitor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/CounterMonitor.java index 6b0910668..ed9134041 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/CounterMonitor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/CounterMonitor.java @@ -18,16 +18,16 @@ package com.navercorp.pinpoint.profiler.monitor; public interface CounterMonitor { - void incr(); + void incr(); - void incr(final long delta); + void incr(final long delta); - void decr(); + void decr(); - void decr(final long delta); - - void reset(); - - long getCount(); + void decr(final long delta); + + void reset(); + + long getCount(); } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/EventRateMonitor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/EventRateMonitor.java index 9db83f448..d6c62453c 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/EventRateMonitor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/EventRateMonitor.java @@ -18,12 +18,12 @@ package com.navercorp.pinpoint.profiler.monitor; public interface EventRateMonitor { - void event(); + void event(); + + void events(final long count); + + long getCount(); + + double getRate(); - void events(final long count); - - long getCount(); - - double getRate(); - } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/HistogramMonitor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/HistogramMonitor.java index c9dd5973b..fc0169d2b 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/HistogramMonitor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/HistogramMonitor.java @@ -18,10 +18,10 @@ package com.navercorp.pinpoint.profiler.monitor; public interface HistogramMonitor { - void reset(); + void reset(); - void update(final long value); - - long getCount(); + void update(final long value); + + long getCount(); } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/MonitorName.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/MonitorName.java index 1db4d852e..91ac28e24 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/MonitorName.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/MonitorName.java @@ -18,18 +18,18 @@ package com.navercorp.pinpoint.profiler.monitor; public class MonitorName { - private final String name; + private final String name; - public MonitorName(String name) { - this.name = name; - } + public MonitorName(String name) { + this.name = name; + } - public String getName() { - return name; - } + public String getName() { + return name; + } + + public String toString() { + return "MonitorName(" + this.name + ")"; + } - public String toString() { - return "MonitorName(" + this.name + ")"; - } - } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/MonitorRegistry.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/MonitorRegistry.java index bbf03b9a1..38c226120 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/MonitorRegistry.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/MonitorRegistry.java @@ -19,10 +19,10 @@ package com.navercorp.pinpoint.profiler.monitor; public interface MonitorRegistry { - HistogramMonitor newHistogramMonitor(final MonitorName monitorName); + HistogramMonitor newHistogramMonitor(final MonitorName monitorName); - EventRateMonitor newEventRateMonitor(final MonitorName monitorName); + EventRateMonitor newEventRateMonitor(final MonitorName monitorName); + + CounterMonitor newCounterMonitor(final MonitorName monitorName); - CounterMonitor newCounterMonitor(final MonitorName monitorName); - } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricCounterMonitor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricCounterMonitor.java index 04907345f..eda012c24 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricCounterMonitor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricCounterMonitor.java @@ -21,45 +21,45 @@ import com.navercorp.pinpoint.profiler.monitor.CounterMonitor; public class MetricCounterMonitor implements CounterMonitor { - final Counter delegate; - - public MetricCounterMonitor(Counter delegate) { - if (delegate == null) { - throw new NullPointerException("Counter delegate is null"); - } - this.delegate = delegate; - } - - public void incr() { - this.delegate.inc(); - } + final Counter delegate; - public void incr(long delta) { - this.delegate.inc(delta); - } + public MetricCounterMonitor(Counter delegate) { + if (delegate == null) { + throw new NullPointerException("Counter delegate is null"); + } + this.delegate = delegate; + } - public void decr() { - this.delegate.dec(); - } + public void incr() { + this.delegate.inc(); + } - public void decr(long delta) { - this.delegate.dec(delta); - } + public void incr(long delta) { + this.delegate.inc(delta); + } - public void reset() { - throw new RuntimeException("Counter reset is not supported in Codahale Metrics 3.x."); - } + public void decr() { + this.delegate.dec(); + } - public long getCount() { - return this.delegate.getCount(); - } - - public Counter getDelegate() { - return this.delegate; - } - - public String toString() { - return "MetricCounterMonitor(delegate=" + this.delegate + ")"; - } + public void decr(long delta) { + this.delegate.dec(delta); + } + + public void reset() { + throw new RuntimeException("Counter reset is not supported in Codahale Metrics 3.x."); + } + + public long getCount() { + return this.delegate.getCount(); + } + + public Counter getDelegate() { + return this.delegate; + } + + public String toString() { + return "MetricCounterMonitor(delegate=" + this.delegate + ")"; + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricEventRateMonitor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricEventRateMonitor.java index 846b502ca..eeb419a18 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricEventRateMonitor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricEventRateMonitor.java @@ -21,37 +21,37 @@ import com.navercorp.pinpoint.profiler.monitor.EventRateMonitor; public class MetricEventRateMonitor implements EventRateMonitor { - final Meter delegate; - - public MetricEventRateMonitor(Meter delegate) { - if (delegate == null) { - throw new NullPointerException("Meter delegate is null"); - } - this.delegate = delegate; - } - - public void event() { - this.delegate.mark(); - } + final Meter delegate; - public void events(long count) { - this.delegate.mark(count); - } - - public long getCount() { - return this.delegate.getCount(); - } - - public double getRate() { - return this.delegate.getMeanRate(); - } - - public Meter getDelegate() { - return this.delegate; - } - - public String toString() { - return "MetricEventRateMonitor(delegate=" + this.delegate + ")"; - } + public MetricEventRateMonitor(Meter delegate) { + if (delegate == null) { + throw new NullPointerException("Meter delegate is null"); + } + this.delegate = delegate; + } + + public void event() { + this.delegate.mark(); + } + + public void events(long count) { + this.delegate.mark(count); + } + + public long getCount() { + return this.delegate.getCount(); + } + + public double getRate() { + return this.delegate.getMeanRate(); + } + + public Meter getDelegate() { + return this.delegate; + } + + public String toString() { + return "MetricEventRateMonitor(delegate=" + this.delegate + ")"; + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricHistogramMonitor.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricHistogramMonitor.java index 61e5ee4c3..7a7fe210a 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricHistogramMonitor.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricHistogramMonitor.java @@ -21,33 +21,33 @@ import com.navercorp.pinpoint.profiler.monitor.HistogramMonitor; public class MetricHistogramMonitor implements HistogramMonitor { - private final Histogram delegate; - - public MetricHistogramMonitor(Histogram delegate) { - if (delegate == null) { - throw new NullPointerException("Histogram delegate is null"); - } - this.delegate = delegate; - } - - public void reset() { - throw new RuntimeException("Histogram reset is not supported in Codahale Metrics 3.x."); - } + private final Histogram delegate; - public void update(long value) { - this.delegate.update(value); - } - - public long getCount() { - return this.delegate.getCount(); - } - - public Histogram getDelegate() { - return this.delegate; - } - - public String toString() { - return "MetricValueDistributionMonitor(delegate=" + this.delegate + ")"; - } + public MetricHistogramMonitor(Histogram delegate) { + if (delegate == null) { + throw new NullPointerException("Histogram delegate is null"); + } + this.delegate = delegate; + } + + public void reset() { + throw new RuntimeException("Histogram reset is not supported in Codahale Metrics 3.x."); + } + + public void update(long value) { + this.delegate.update(value); + } + + public long getCount() { + return this.delegate.getCount(); + } + + public Histogram getDelegate() { + return this.delegate; + } + + public String toString() { + return "MetricValueDistributionMonitor(delegate=" + this.delegate + ")"; + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/metric/DefaultCpuLoadMetricSet.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/metric/DefaultCpuLoadMetricSet.java index 1cb687a01..b77ace438 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/metric/DefaultCpuLoadMetricSet.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/cpu/metric/DefaultCpuLoadMetricSet.java @@ -27,67 +27,67 @@ import com.sun.management.OperatingSystemMXBean; */ public final class DefaultCpuLoadMetricSet extends AbstractCpuLoadMetricSet { - private static final int UNSUPPORTED = -1; - private static final int UNINITIALIZED = -1; - private static final Double UNSUPPORTED_CPU_LOAD_METRIC = -1.0D; + private static final int UNSUPPORTED = -1; + private static final int UNINITIALIZED = -1; + private static final Double UNSUPPORTED_CPU_LOAD_METRIC = -1.0D; - private final RuntimeMXBean runtimeMXBean; + private final RuntimeMXBean runtimeMXBean; - public DefaultCpuLoadMetricSet() { - this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); - } + public DefaultCpuLoadMetricSet() { + this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); + } - @Override - protected Gauge getJvmCpuLoadGauge(final OperatingSystemMXBean operatingSystemMXBean) { - return new Gauge() { + @Override + protected Gauge getJvmCpuLoadGauge(final OperatingSystemMXBean operatingSystemMXBean) { + return new Gauge() { - private long lastCpuTimeNS = UNINITIALIZED; - private long lastUpTimeMS = UNINITIALIZED; + private long lastCpuTimeNS = UNINITIALIZED; + private long lastUpTimeMS = UNINITIALIZED; - @Override - public Double getValue() { - - final long cpuTimeNS = operatingSystemMXBean.getProcessCpuTime(); - if (cpuTimeNS == UNSUPPORTED) { - return UNSUPPORTED_CPU_LOAD_METRIC; - } - final long upTimeMS = runtimeMXBean.getUptime(); - - if (this.lastCpuTimeNS == UNINITIALIZED || this.lastUpTimeMS == UNINITIALIZED) { - this.lastCpuTimeNS = cpuTimeNS; - this.lastUpTimeMS = upTimeMS; - return 0.0D; - } - - final long totalCpuTimeNS = cpuTimeNS - lastCpuTimeNS; - final long diffUpTimeMS = upTimeMS - lastUpTimeMS; - final int numProcessors = Runtime.getRuntime().availableProcessors(); - final long totalUpTimeNS = (diffUpTimeMS * 1000000) * numProcessors; - - final double cpuLoad = totalUpTimeNS > 0 ? - Math.min(100F, totalCpuTimeNS / (float)totalUpTimeNS) : UNSUPPORTED; - - this.lastCpuTimeNS = cpuTimeNS; - this.lastUpTimeMS = upTimeMS; - - return cpuLoad; - } - }; - } + @Override + public Double getValue() { - @Override - protected Gauge getSystemCpuLoadGauge(final OperatingSystemMXBean operatingSystemMXBean) { - return new Gauge() { - @Override - public Double getValue() { - return UNSUPPORTED_CPU_LOAD_METRIC; - } - }; - } + final long cpuTimeNS = operatingSystemMXBean.getProcessCpuTime(); + if (cpuTimeNS == UNSUPPORTED) { + return UNSUPPORTED_CPU_LOAD_METRIC; + } + final long upTimeMS = runtimeMXBean.getUptime(); - @Override - public String toString() { - return "Default CpuLoadMetricSet for Java 1.6"; - } + if (this.lastCpuTimeNS == UNINITIALIZED || this.lastUpTimeMS == UNINITIALIZED) { + this.lastCpuTimeNS = cpuTimeNS; + this.lastUpTimeMS = upTimeMS; + return 0.0D; + } + + final long totalCpuTimeNS = cpuTimeNS - lastCpuTimeNS; + final long diffUpTimeMS = upTimeMS - lastUpTimeMS; + final int numProcessors = Runtime.getRuntime().availableProcessors(); + final long totalUpTimeNS = (diffUpTimeMS * 1000000) * numProcessors; + + final double cpuLoad = totalUpTimeNS > 0 ? + Math.min(100F, totalCpuTimeNS / (float)totalUpTimeNS) : UNSUPPORTED; + + this.lastCpuTimeNS = cpuTimeNS; + this.lastUpTimeMS = upTimeMS; + + return cpuLoad; + } + }; + } + + @Override + protected Gauge getSystemCpuLoadGauge(final OperatingSystemMXBean operatingSystemMXBean) { + return new Gauge() { + @Override + public Double getValue() { + return UNSUPPORTED_CPU_LOAD_METRIC; + } + }; + } + + @Override + public String toString() { + return "Default CpuLoadMetricSet for Java 1.6"; + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/gc/GarbageCollector.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/gc/GarbageCollector.java index 66210263a..2103e9205 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/gc/GarbageCollector.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/gc/GarbageCollector.java @@ -24,8 +24,8 @@ import com.navercorp.pinpoint.thrift.dto.TJvmGc; */ public interface GarbageCollector { - int getTypeCode(); + int getTypeCode(); - TJvmGc collect(); + TJvmGc collect(); } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/CommandDispatcher.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/CommandDispatcher.java index f118a522c..0033233d8 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/CommandDispatcher.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/CommandDispatcher.java @@ -147,5 +147,5 @@ public class CommandDispatcher implements MessageListener, ServerStreamChannelMe private DeserializerFactory wrappedThreadLocalDeserializerFactory(DeserializerFactory deserializerFactory) { return new ThreadLocalHeaderTBaseDeserializerFactory(deserializerFactory); } - + } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/ProfilerCommandService.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/ProfilerCommandService.java index a5ae082de..b3164dc6f 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/ProfilerCommandService.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/ProfilerCommandService.java @@ -23,6 +23,6 @@ import org.apache.thrift.TBase; */ public interface ProfilerCommandService { - Class getCommandClazz(); - + Class getCommandClazz(); + } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/ProfilerCommandServiceLocator.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/ProfilerCommandServiceLocator.java index 446dee943..c98af4dfe 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/ProfilerCommandServiceLocator.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/ProfilerCommandServiceLocator.java @@ -23,12 +23,12 @@ import org.apache.thrift.TBase; */ public interface ProfilerCommandServiceLocator { - ProfilerCommandService getService(TBase tBase); + ProfilerCommandService getService(TBase tBase); - ProfilerSimpleCommandService getSimpleService(TBase tBase); + ProfilerSimpleCommandService getSimpleService(TBase tBase); - ProfilerRequestCommandService getRequestService(TBase tBase); - - ProfilerStreamCommandService getStreamService(TBase tBase); + ProfilerRequestCommandService getRequestService(TBase tBase); + + ProfilerStreamCommandService getStreamService(TBase tBase); } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/ProfilerRequestCommandService.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/ProfilerRequestCommandService.java index bf786f743..a8a3ed035 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/ProfilerRequestCommandService.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/ProfilerRequestCommandService.java @@ -23,6 +23,6 @@ import org.apache.thrift.TBase; */ public interface ProfilerRequestCommandService extends ProfilerCommandService { - TBase requestCommandService(TBase tBase); - + TBase requestCommandService(TBase tBase); + } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/ProfilerSimpleCommandService.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/ProfilerSimpleCommandService.java index 4ab298457..3e2cbf38b 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/ProfilerSimpleCommandService.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/ProfilerSimpleCommandService.java @@ -23,6 +23,6 @@ import org.apache.thrift.TBase; */ public interface ProfilerSimpleCommandService extends ProfilerCommandService { - void simpleCommandService(TBase tbase); - + void simpleCommandService(TBase tbase); + } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/service/EchoService.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/service/EchoService.java index 2909363ef..d94589977 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/service/EchoService.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/receiver/service/EchoService.java @@ -27,19 +27,19 @@ import com.navercorp.pinpoint.thrift.dto.command.TCommandEcho; * @author koo.taejin */ public class EchoService implements ProfilerRequestCommandService { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Override - public TBase requestCommandService(TBase tbase) { - logger.info("{} execute {}.", this, tbase); - - TCommandEcho param = (TCommandEcho) tbase; - return param; - } - - @Override - public Class getCommandClazz() { - return TCommandEcho.class; - } + @Override + public TBase requestCommandService(TBase tbase) { + logger.info("{} execute {}.", this, tbase); + + TCommandEcho param = (TCommandEcho) tbase; + return param; + } + + @Override + public Class getCommandClazz() { + return TCommandEcho.class; + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/AbstractDataSender.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/AbstractDataSender.java index 92339e70a..f9372fb9c 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/AbstractDataSender.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/AbstractDataSender.java @@ -34,28 +34,28 @@ import com.navercorp.pinpoint.thrift.util.SerializationUtils; */ public abstract class AbstractDataSender implements DataSender { - private Logger logger = LoggerFactory.getLogger(this.getClass()); + private Logger logger = LoggerFactory.getLogger(this.getClass()); + + abstract protected void sendPacket(Object dto); - abstract protected void sendPacket(Object dto); - protected void sendPacketN(Collection messageList) { // Cannot use toArray(T[] array) because passed messageList doesn't implement it properly. Object[] dataList = messageList.toArray(); // No need to copy because this runs with single thread. - // Object[] copy = Arrays.copyOf(original, original.length); + // Object[] copy = Arrays.copyOf(original, original.length); - final int size = messageList.size(); - for (int i = 0; i < size; i++) { - try { - sendPacket(dataList[i]); - } catch (Throwable th) { - logger.warn("Unexpected Error. Cause:{}", th.getMessage(), th); - } - } - } + final int size = messageList.size(); + for (int i = 0; i < size; i++) { + try { + sendPacket(dataList[i]); + } catch (Throwable th) { + logger.warn("Unexpected Error. Cause:{}", th.getMessage(), th); + } + } + } - protected AsyncQueueingExecutor createAsyncQueueingExecutor(int queueSize, String executorName) { + protected AsyncQueueingExecutor createAsyncQueueingExecutor(int queueSize, String executorName) { final AsyncQueueingExecutor executor = new AsyncQueueingExecutor(queueSize, executorName); executor.setListener(new AsyncQueueingExecutorListener() { @Override @@ -71,43 +71,43 @@ public abstract class AbstractDataSender implements DataSender { return executor; } - protected byte[] serialize(HeaderTBaseSerializer serializer, TBase tBase) { - return SerializationUtils.serialize(tBase, serializer, null); - } - - protected TBase deserialize(HeaderTBaseDeserializer deserializer, ResponseMessage responseMessage) { - byte[] message = responseMessage.getMessage(); - return SerializationUtils.deserialize(message, deserializer, null); - } - - protected static class RequestMarker { - private final TBase tBase; - private final int retryCount; - private final FutureListener futureListener; + protected byte[] serialize(HeaderTBaseSerializer serializer, TBase tBase) { + return SerializationUtils.serialize(tBase, serializer, null); + } - protected RequestMarker(TBase tBase, int retryCount) { - this.tBase = tBase; - this.retryCount = retryCount; - this.futureListener = null; - } - - protected RequestMarker(TBase tBase, FutureListener futureListener) { - this.tBase = tBase; - this.retryCount = 3; - this.futureListener = futureListener; - } + protected TBase deserialize(HeaderTBaseDeserializer deserializer, ResponseMessage responseMessage) { + byte[] message = responseMessage.getMessage(); + return SerializationUtils.deserialize(message, deserializer, null); + } - protected TBase getTBase() { - return tBase; - } + protected static class RequestMarker { + private final TBase tBase; + private final int retryCount; + private final FutureListener futureListener; + + protected RequestMarker(TBase tBase, int retryCount) { + this.tBase = tBase; + this.retryCount = retryCount; + this.futureListener = null; + } + + protected RequestMarker(TBase tBase, FutureListener futureListener) { + this.tBase = tBase; + this.retryCount = 3; + this.futureListener = futureListener; + } + + protected TBase getTBase() { + return tBase; + } + + protected int getRetryCount() { + return retryCount; + } + + protected FutureListener getFutureListener() { + return futureListener; + } + } - protected int getRetryCount() { - return retryCount; - } - - protected FutureListener getFutureListener() { - return futureListener; - } - } - } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/LoggingDataSender.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/LoggingDataSender.java index 9e6b67e80..2a946b5a5 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/LoggingDataSender.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/LoggingDataSender.java @@ -60,26 +60,26 @@ public class LoggingDataSender implements EnhancedDataSender { } - @Override - public boolean request(TBase data, FutureListener listener) { + @Override + public boolean request(TBase data, FutureListener listener) { logger.info("request tBase:{} FutureListener:{}", data, listener); return false; - } - - @Override - public boolean addReconnectEventListener(PinpointSocketReconnectEventListener eventListener) { - logger.info("addReconnectEventListener eventListener:{}", eventListener); - return false; - } - - @Override - public boolean removeReconnectEventListener(PinpointSocketReconnectEventListener eventListener) { - logger.info("removeReconnectEventListener eventListener:{}", eventListener); - return false; - } + } - @Override - public boolean isNetworkAvailable() { - return true; - } + @Override + public boolean addReconnectEventListener(PinpointSocketReconnectEventListener eventListener) { + logger.info("addReconnectEventListener eventListener:{}", eventListener); + return false; + } + + @Override + public boolean removeReconnectEventListener(PinpointSocketReconnectEventListener eventListener) { + logger.info("removeReconnectEventListener eventListener:{}", eventListener); + return false; + } + + @Override + public boolean isNetworkAvailable() { + return true; + } } 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 72b5155fb..c9cc6a982 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 @@ -70,9 +70,9 @@ public class TcpDataSender extends AbstractDataSender implements EnhancedDataSen private AsyncQueueingExecutor executor; public TcpDataSender(PinpointSocket socket) { - this.socket = socket; - this.timer = createTimer(); - writeFailFutureListener = new WriteFailFutureListener(logger, "io write fail.", "host", -1); + this.socket = socket; + this.timer = createTimer(); + writeFailFutureListener = new WriteFailFutureListener(logger, "io write fail.", "host", -1); this.executor = createAsyncQueueingExecutor(1024 * 5, "Pinpoint-TcpDataExecutor"); } @@ -94,25 +94,25 @@ public class TcpDataSender extends AbstractDataSender implements EnhancedDataSen @Override public boolean request(TBase data, int retryCount) { - RequestMarker message = new RequestMarker(data, retryCount); + RequestMarker message = new RequestMarker(data, retryCount); return executor.execute(message); } - @Override - public boolean request(TBase data, FutureListener listener) { - RequestMarker message = new RequestMarker(data, listener); + @Override + public boolean request(TBase data, FutureListener listener) { + RequestMarker message = new RequestMarker(data, listener); return executor.execute(message); - } + } - @Override - public boolean addReconnectEventListener(PinpointSocketReconnectEventListener eventListener) { - return this.socket.addPinpointSocketReconnectEventListener(eventListener); - } + @Override + public boolean addReconnectEventListener(PinpointSocketReconnectEventListener eventListener) { + return this.socket.addPinpointSocketReconnectEventListener(eventListener); + } - @Override - public boolean removeReconnectEventListener(PinpointSocketReconnectEventListener eventListener) { - return this.socket.removePinpointSocketReconnectEventListener(eventListener); - } + @Override + public boolean removeReconnectEventListener(PinpointSocketReconnectEventListener eventListener) { + return this.socket.removePinpointSocketReconnectEventListener(eventListener); + } @Override public void stop() { @@ -127,32 +127,32 @@ public class TcpDataSender extends AbstractDataSender implements EnhancedDataSen @Override protected void sendPacket(Object message) { try { - if (message instanceof TBase) { - byte[] copy = serialize(serializer, (TBase) message); + if (message instanceof TBase) { + byte[] copy = serialize(serializer, (TBase) message); if (copy == null) { return; } doSend(copy); - } else if (message instanceof RequestMarker) { - RequestMarker requestMarker = (RequestMarker) message; + } else if (message instanceof RequestMarker) { + RequestMarker requestMarker = (RequestMarker) message; - TBase tBase = requestMarker.getTBase(); - int retryCount = requestMarker.getRetryCount(); - FutureListener futureListener = requestMarker.getFutureListener(); - byte[] copy = serialize(serializer, tBase); + TBase tBase = requestMarker.getTBase(); + int retryCount = requestMarker.getRetryCount(); + FutureListener futureListener = requestMarker.getFutureListener(); + byte[] copy = serialize(serializer, tBase); if (copy == null) { return; } if (futureListener != null) { - doRequest(copy, futureListener); + doRequest(copy, futureListener); } else { - doRequest(copy, retryCount, tBase); + doRequest(copy, retryCount, tBase); } - } else { + } else { logger.error("sendPacket fail. invalid dto type:{}", message.getClass()); return; - } + } } catch (Exception e) { logger.warn("tcp send fail. Caused:{}", e.getMessage(), e); } @@ -164,12 +164,12 @@ public class TcpDataSender extends AbstractDataSender implements EnhancedDataSen } private void doRequest(final byte[] requestPacket, final int retryCount, final Object targetClass) { - FutureListener futureListner = (new FutureListener() { + FutureListener futureListner = (new FutureListener() { @Override public void onComplete(Future future) { if (future.isSuccess()) { - // Should cache? - HeaderTBaseDeserializer deserializer = HeaderTBaseDeserializerFactory.DEFAULT_FACTORY.createDeserializer(); + // Should cache? + HeaderTBaseDeserializer deserializer = HeaderTBaseDeserializerFactory.DEFAULT_FACTORY.createDeserializer(); TBase response = deserialize(deserializer, future.getResult()); if (response instanceof TResult) { TResult result = (TResult) response; @@ -191,15 +191,15 @@ public class TcpDataSender extends AbstractDataSender implements EnhancedDataSen } } }); - - doRequest(requestPacket, futureListner); + + doRequest(requestPacket, futureListner); } private void retryRequest(byte[] requestPacket, int retryCount, final String className) { RetryMessage retryMessage = new RetryMessage(retryCount, requestPacket); retryQueue.add(retryMessage); if (fireTimeout()) { - timer.newTimeout(new TimerTask() { + timer.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { while(true) { @@ -235,11 +235,11 @@ public class TcpDataSender extends AbstractDataSender implements EnhancedDataSen fireState.compareAndSet(true, false); } - @Override - public boolean isNetworkAvailable() { - if (this.socket == null) { - return false; - } - return this.socket.isConnected(); - } + @Override + public boolean isNetworkAvailable() { + if (this.socket == null) { + return false; + } + return this.socket.isConnected(); + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/UdpDataSender.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/UdpDataSender.java index 98955e4a6..ef6d93549 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/UdpDataSender.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/sender/UdpDataSender.java @@ -38,7 +38,7 @@ import org.slf4j.LoggerFactory; */ public class UdpDataSender extends AbstractDataSender implements DataSender { - protected final Logger logger = LoggerFactory.getLogger(this.getClass()); + protected final Logger logger = LoggerFactory.getLogger(this.getClass()); protected final boolean isTrace = logger.isTraceEnabled(); protected final boolean isDebug = logger.isDebugEnabled(); @@ -49,10 +49,10 @@ public class UdpDataSender extends AbstractDataSender implements DataSender { // Caution. not thread safe protected DatagramPacket reusePacket = new DatagramPacket(new byte[1], 1); - protected final DatagramSocket udpSocket; + protected final DatagramSocket udpSocket; // Caution. not thread safe - private final HeaderTBaseSerializer serializer = new HeaderTBaseSerializerFactory(false, HeaderTBaseSerializerFactory.DEFAULT_UDP_STREAM_MAX_SIZE).createSerializer(); + private final HeaderTBaseSerializer serializer = new HeaderTBaseSerializerFactory(false, HeaderTBaseSerializerFactory.DEFAULT_UDP_STREAM_MAX_SIZE).createSerializer(); private AsyncQueueingExecutor executor; @@ -60,7 +60,7 @@ public class UdpDataSender extends AbstractDataSender implements DataSender { this(host, port, threadName, queueSize, SOCKET_TIMEOUT, SEND_BUFFER_SIZE); } - public UdpDataSender(String host, int port, String threadName, int queueSize, int timeout, int sendBufferSize) { + public UdpDataSender(String host, int port, String threadName, int queueSize, int timeout, int sendBufferSize) { if (host == null ) { throw new NullPointerException("host must not be null"); } @@ -79,15 +79,15 @@ public class UdpDataSender extends AbstractDataSender implements DataSender { // TODO If fail to create socket, stop agent start logger.info("UdpDataSender initialized. host={}, port={}", host, port); - this.udpSocket = createSocket(host, port, timeout, sendBufferSize); + this.udpSocket = createSocket(host, port, timeout, sendBufferSize); + + this.executor = createAsyncQueueingExecutor(queueSize, threadName); + } - this.executor = createAsyncQueueingExecutor(queueSize, threadName); - } - @Override - public boolean send(TBase data) { - return executor.execute(data); - } + public boolean send(TBase data) { + return executor.execute(data); + } @Override public void stop() { @@ -95,10 +95,10 @@ public class UdpDataSender extends AbstractDataSender implements DataSender { } public boolean isNetworkAvailable() { - NetworkAvailabilityCheckPacket dto = new NetworkAvailabilityCheckPacket(); + NetworkAvailabilityCheckPacket dto = new NetworkAvailabilityCheckPacket(); try { byte[] interBufferData = serialize(serializer, dto); - int interBufferSize = serializer.getInterBufferSize(); + int interBufferSize = serializer.getInterBufferSize(); reusePacket.setData(interBufferData, 0, interBufferSize); udpSocket.send(reusePacket); @@ -106,15 +106,15 @@ public class UdpDataSender extends AbstractDataSender implements DataSender { logger.trace("Data sent. {}", dto); } - byte[] receiveData = new byte[NetworkAvailabilityCheckPacket.DATA_OK.length]; - DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); - udpSocket.receive(receivePacket); - - if (isTrace) { - logger.trace("Data received. {}", Arrays.toString(receivePacket.getData())); - } - - return Arrays.equals(NetworkAvailabilityCheckPacket.DATA_OK , receiveData); + byte[] receiveData = new byte[NetworkAvailabilityCheckPacket.DATA_OK.length]; + DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); + udpSocket.receive(receivePacket); + + if (isTrace) { + logger.trace("Data received. {}", Arrays.toString(receivePacket.getData())); + } + + return Arrays.equals(NetworkAvailabilityCheckPacket.DATA_OK , receiveData); } catch (IOException e) { logger.warn("packet send error {}", dto, e); return false; @@ -122,10 +122,10 @@ public class UdpDataSender extends AbstractDataSender implements DataSender { } private DatagramSocket createSocket(String host, int port, int timeout, int sendBufferSize) { - try { + try { DatagramSocket datagramSocket = new DatagramSocket(); - datagramSocket.setSoTimeout(timeout); + datagramSocket.setSoTimeout(timeout); datagramSocket.setSendBufferSize(sendBufferSize); if (logger.isWarnEnabled()) { final int checkSendBufferSize = datagramSocket.getSendBufferSize(); @@ -134,17 +134,17 @@ public class UdpDataSender extends AbstractDataSender implements DataSender { } } - InetSocketAddress serverAddress = new InetSocketAddress(host, port); - datagramSocket.connect(serverAddress); - return datagramSocket; - } catch (SocketException e) { - throw new IllegalStateException("DatagramSocket create fail. Cause" + e.getMessage(), e); - } - } + InetSocketAddress serverAddress = new InetSocketAddress(host, port); + datagramSocket.connect(serverAddress); + return datagramSocket; + } catch (SocketException e) { + throw new IllegalStateException("DatagramSocket create fail. Cause" + e.getMessage(), e); + } + } - protected void sendPacket(Object message) { - if (message instanceof TBase) { - final TBase dto = (TBase) message; + protected void sendPacket(Object message) { + if (message instanceof TBase) { + final TBase dto = (TBase) message; // do not copy bytes because it's single threaded final byte[] internalBufferData = serialize(this.serializer, dto); if (internalBufferData == null) { @@ -169,11 +169,11 @@ public class UdpDataSender extends AbstractDataSender implements DataSender { } catch (IOException e) { logger.warn("packet send error. size:{}, {}", internalBufferSize, dto, e); } - } else { - logger.warn("sendPacket fail. invalid type:{}", message != null ? message.getClass() : null); - return; - } - } + } else { + logger.warn("sendPacket fail. invalid type:{}", message != null ? message.getClass() : null); + return; + } + } // for test protected boolean isLimit(int interBufferSize) { diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/tools/NetworkAvailabilityChecker.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/tools/NetworkAvailabilityChecker.java index d122d88cf..2ba124fce 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/tools/NetworkAvailabilityChecker.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/tools/NetworkAvailabilityChecker.java @@ -98,7 +98,7 @@ public class NetworkAvailabilityChecker implements PinpointTools { } } - private static void write(StringBuilder buffer, String protcol, String collectorStatIp, int collectorStatPort, boolean udpSenderResult) { + private static void write(StringBuilder buffer, String protcol, String collectorStatIp, int collectorStatPort, boolean udpSenderResult) { buffer.append(protcol); buffer.append(collectorStatIp); buffer.append(":"); @@ -108,7 +108,7 @@ public class NetworkAvailabilityChecker implements PinpointTools { buffer.append("\n"); } - private static void closeDataSender(DataSender dataSender) { + private static void closeDataSender(DataSender dataSender) { if (dataSender != null) { dataSender.stop(); } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/ApiUtils.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/ApiUtils.java index 65026e1ce..2f3f070b8 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/ApiUtils.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/ApiUtils.java @@ -23,45 +23,45 @@ import java.util.Arrays; */ public final class ApiUtils { - private final static String EMPTY_ARRAY = "()"; + private final static String EMPTY_ARRAY = "()"; - private ApiUtils() { - } + private ApiUtils() { + } - public static String mergeParameterVariableNameDescription(String[] parameterType, String[] variableName) { - if (parameterType == null && variableName == null) { - return EMPTY_ARRAY; - } - if (variableName != null && parameterType != null) { - if (parameterType.length != variableName.length) { - throw new IllegalArgumentException("args size not equal"); - } - if (parameterType.length == 0) { - return EMPTY_ARRAY; - } - StringBuilder sb = new StringBuilder(64); - sb.append('('); - int end = parameterType.length - 1; - for (int i = 0; i < parameterType.length; i++) { - sb.append(parameterType[i]); - sb.append(' '); - sb.append(variableName[i]); - if (i < end) { - sb.append(", "); - } - } - sb.append(')'); - return sb.toString(); - } - throw new IllegalArgumentException("invalid null pair parameterType:" + Arrays.toString(parameterType) + ", variableName:" + Arrays.toString(variableName)); - } + public static String mergeParameterVariableNameDescription(String[] parameterType, String[] variableName) { + if (parameterType == null && variableName == null) { + return EMPTY_ARRAY; + } + if (variableName != null && parameterType != null) { + if (parameterType.length != variableName.length) { + throw new IllegalArgumentException("args size not equal"); + } + if (parameterType.length == 0) { + return EMPTY_ARRAY; + } + StringBuilder sb = new StringBuilder(64); + sb.append('('); + int end = parameterType.length - 1; + for (int i = 0; i < parameterType.length; i++) { + sb.append(parameterType[i]); + sb.append(' '); + sb.append(variableName[i]); + if (i < end) { + sb.append(", "); + } + } + sb.append(')'); + return sb.toString(); + } + throw new IllegalArgumentException("invalid null pair parameterType:" + Arrays.toString(parameterType) + ", variableName:" + Arrays.toString(variableName)); + } - public static String mergeApiDescriptor(String className, String methodName, String parameterDescriptor) { - StringBuilder buffer = new StringBuilder(256); - buffer.append(className); - buffer.append("."); - buffer.append(methodName); - buffer.append(parameterDescriptor); - return buffer.toString(); - } + public static String mergeApiDescriptor(String className, String methodName, String parameterDescriptor) { + StringBuilder buffer = new StringBuilder(256); + buffer.append(className); + buffer.append("."); + buffer.append(methodName); + buffer.append(parameterDescriptor); + return buffer.toString(); + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/QueryStringUtil.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/QueryStringUtil.java index fe452219a..113916334 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/QueryStringUtil.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/QueryStringUtil.java @@ -28,7 +28,7 @@ public final class QueryStringUtil { } public static String removeCarriageReturn(String query) { -// query.replaceAll(regex, replacement) +// query.replaceAll(regex, replacement) String result = query.replaceAll("[\r\n]", " "); return result; } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/StackTraceUtil.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/StackTraceUtil.java index fb3557a6b..5d0114b38 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/StackTraceUtil.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/StackTraceUtil.java @@ -32,11 +32,11 @@ public class StackTraceUtil { return; } - StackTraceElement[] stackList = Thread.currentThread().getStackTrace(); - int length = stackList.length; - for (int loop = 2; loop < length; loop++) { - logger.info("***" + stackList[loop].toString()); - } - } + StackTraceElement[] stackList = Thread.currentThread().getStackTrace(); + int length = stackList.length; + for (int loop = 2; loop < length; loop++) { + logger.info("***" + stackList[loop].toString()); + } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/bindvalue/converter/BytesConverter.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/bindvalue/converter/BytesConverter.java index 5753de2a2..e9b899dfe 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/bindvalue/converter/BytesConverter.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/bindvalue/converter/BytesConverter.java @@ -22,19 +22,19 @@ import com.navercorp.pinpoint.profiler.util.ArrayUtils; * @author emeroad */ public class BytesConverter implements Converter { - @Override - public String convert(Object[] args) { - if (args == null) { - return "null"; - } - if (args.length == 2) { - byte[] bytes = (byte[]) args[1]; - if (bytes == null) { - return "null"; - } else { - return ArrayUtils.dropToString(bytes); - } - } - return "error"; - } + @Override + public String convert(Object[] args) { + if (args == null) { + return "null"; + } + if (args.length == 2) { + byte[] bytes = (byte[]) args[1]; + if (bytes == null) { + return "null"; + } else { + return ArrayUtils.dropToString(bytes); + } + } + return "error"; + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/bindvalue/converter/ObjectConverter.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/bindvalue/converter/ObjectConverter.java index 49695439e..f13e9208d 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/bindvalue/converter/ObjectConverter.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/util/bindvalue/converter/ObjectConverter.java @@ -50,42 +50,42 @@ public class ObjectConverter implements Converter { return "null"; } else { if (param instanceof Byte) { - return dropToString(param); - } else if (param instanceof String) { - return StringUtils.drop((String) param); - } else if (param instanceof BigDecimal) { - return dropToString(param); - } else if (param instanceof Short) { - return dropToString(param); - } else if (param instanceof Integer) { - return dropToString(param); - } else if (param instanceof Long) { - return dropToString(param); - } else if (param instanceof Float) { - return dropToString(param); - } else if (param instanceof Double) { - return dropToString(param); - } else if (param instanceof BigInteger) { - return dropToString(param); - } else if (param instanceof java.sql.Date) { - return dropToString(param); - } else if (param instanceof Time) { - return dropToString(param); - } else if (param instanceof Timestamp) { - return dropToString(param); - } else if (param instanceof Boolean) { - return dropToString(param); - } else if (param instanceof byte[]) { + return dropToString(param); + } else if (param instanceof String) { + return StringUtils.drop((String) param); + } else if (param instanceof BigDecimal) { + return dropToString(param); + } else if (param instanceof Short) { + return dropToString(param); + } else if (param instanceof Integer) { + return dropToString(param); + } else if (param instanceof Long) { + return dropToString(param); + } else if (param instanceof Float) { + return dropToString(param); + } else if (param instanceof Double) { + return dropToString(param); + } else if (param instanceof BigInteger) { + return dropToString(param); + } else if (param instanceof java.sql.Date) { + return dropToString(param); + } else if (param instanceof Time) { + return dropToString(param); + } else if (param instanceof Timestamp) { + return dropToString(param); + } else if (param instanceof Boolean) { + return dropToString(param); + } else if (param instanceof byte[]) { return ArrayUtils.dropToString((byte[]) param); - } else if (param instanceof InputStream) { - return getClassName(param); - } else if (param instanceof java.sql.Blob) { - return getClassName(param); - } else if (param instanceof java.sql.Clob) { - return getClassName(param); - } else { - return getClassName(param); - } + } else if (param instanceof InputStream) { + return getClassName(param); + } else if (param instanceof java.sql.Blob) { + return getClassName(param); + } else if (param instanceof java.sql.Clob) { + return getClassName(param); + } else { + return getClassName(param); + } } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/test/BaseInterceptorTest.java b/profiler/src/main/java/com/navercorp/pinpoint/test/BaseInterceptorTest.java index c3da62d45..35f12f4f6 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/test/BaseInterceptorTest.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/test/BaseInterceptorTest.java @@ -31,41 +31,41 @@ import com.navercorp.pinpoint.profiler.logging.Slf4jLoggerBinder; public class BaseInterceptorTest { - Interceptor interceptor; - MethodDescriptor descriptor; + Interceptor interceptor; + MethodDescriptor descriptor; - public void setInterceptor(Interceptor interceptor) { - this.interceptor = interceptor; - } - - public void setMethodDescriptor(MethodDescriptor methodDescriptor) { - this.descriptor = methodDescriptor; - } - - @BeforeClass - public static void before() { - PLoggerFactory.initialize(new Slf4jLoggerBinder()); - } + public void setInterceptor(Interceptor interceptor) { + this.interceptor = interceptor; + } - @Before - public void beforeEach() { - if (interceptor == null) { - Assert.fail("set the interceptor first."); - } + public void setMethodDescriptor(MethodDescriptor methodDescriptor) { + this.descriptor = methodDescriptor; + } - if (interceptor instanceof TraceContextSupport) { - // sampler + @BeforeClass + public static void before() { + PLoggerFactory.initialize(new Slf4jLoggerBinder()); + } - // trace context - TraceContext traceContext = new MockTraceContextFactory().create(); - ((TraceContextSupport) interceptor).setTraceContext(traceContext); - } - - if (interceptor instanceof ByteCodeMethodDescriptorSupport) { - if (descriptor != null) { - ((ByteCodeMethodDescriptorSupport)interceptor).setMethodDescriptor(descriptor); - } - } - } + @Before + public void beforeEach() { + if (interceptor == null) { + Assert.fail("set the interceptor first."); + } + + if (interceptor instanceof TraceContextSupport) { + // sampler + + // trace context + TraceContext traceContext = new MockTraceContextFactory().create(); + ((TraceContextSupport) interceptor).setTraceContext(traceContext); + } + + if (interceptor instanceof ByteCodeMethodDescriptorSupport) { + if (descriptor != null) { + ((ByteCodeMethodDescriptorSupport)interceptor).setMethodDescriptor(descriptor); + } + } + } } diff --git a/profiler/src/main/java/com/navercorp/pinpoint/test/MockTraceContextFactory.java b/profiler/src/main/java/com/navercorp/pinpoint/test/MockTraceContextFactory.java index d4d620350..ba2e78e5f 100644 --- a/profiler/src/main/java/com/navercorp/pinpoint/test/MockTraceContextFactory.java +++ b/profiler/src/main/java/com/navercorp/pinpoint/test/MockTraceContextFactory.java @@ -26,8 +26,8 @@ import com.navercorp.pinpoint.profiler.context.DefaultTraceContext; public class MockTraceContextFactory { public TraceContext create() { DefaultTraceContext traceContext = new DefaultTraceContext() ; - ProfilerConfig profilerConfig = new ProfilerConfig(); - traceContext.setProfilerConfig(profilerConfig); - return traceContext; + ProfilerConfig profilerConfig = new ProfilerConfig(); + traceContext.setProfilerConfig(profilerConfig); + return traceContext; } } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/DefaultClassFileFilterTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/DefaultClassFileFilterTest.java index 3d4cd2c3b..363678502 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/DefaultClassFileFilterTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/DefaultClassFileFilterTest.java @@ -29,26 +29,26 @@ import java.net.URLClassLoader; public class DefaultClassFileFilterTest { - @Test - public void testDoFilter_Package() throws Exception { - ClassFileFilter filter = new DefaultClassFileFilter(this.getClass().getClassLoader()); + @Test + public void testDoFilter_Package() throws Exception { + ClassFileFilter filter = new DefaultClassFileFilter(this.getClass().getClassLoader()); - Assert.assertTrue(filter.doFilter(null, "java/test", null, null, null)); - Assert.assertTrue(filter.doFilter(null, "javax/test", null, null, null)); - Assert.assertTrue(filter.doFilter(null, "com/navercorp/pinpoint/", null, null, null)); + Assert.assertTrue(filter.doFilter(null, "java/test", null, null, null)); + Assert.assertTrue(filter.doFilter(null, "javax/test", null, null, null)); + Assert.assertTrue(filter.doFilter(null, "com/navercorp/pinpoint/", null, null, null)); - Assert.assertFalse(filter.doFilter(null, "test", null, null, null)); - } + Assert.assertFalse(filter.doFilter(null, "test", null, null, null)); + } - @Test - public void testDoFilter_ClassLoader() throws Exception { - ClassFileFilter filter = new DefaultClassFileFilter(this.getClass().getClassLoader()); + @Test + public void testDoFilter_ClassLoader() throws Exception { + ClassFileFilter filter = new DefaultClassFileFilter(this.getClass().getClassLoader()); - Assert.assertTrue(filter.doFilter(this.getClass().getClassLoader(), "test", null, null, null)); + Assert.assertTrue(filter.doFilter(this.getClass().getClassLoader(), "test", null, null, null)); - URLClassLoader classLoader = new URLClassLoader(new URL[]{}); - Assert.assertFalse(filter.doFilter(classLoader, "test", null, null, null)); - } + URLClassLoader classLoader = new URLClassLoader(new URL[]{}); + Assert.assertFalse(filter.doFilter(classLoader, "test", null, null, null)); + } } \ No newline at end of file diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/HeaderTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/HeaderTest.java index 0f38afb2c..aa0ee4502 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/HeaderTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/HeaderTest.java @@ -38,45 +38,45 @@ public class HeaderTest { } - @Test - public void isHeaderKey() throws Exception { - Assert.assertTrue(Header.hasHeader(Header.HTTP_FLAGS.toString())); + @Test + public void isHeaderKey() throws Exception { + Assert.assertTrue(Header.hasHeader(Header.HTTP_FLAGS.toString())); - Assert.assertFalse(Header.hasHeader("Not_Exist")); + Assert.assertFalse(Header.hasHeader("Not_Exist")); - Assert.assertFalse(Header.hasHeader(null)); - } + Assert.assertFalse(Header.hasHeader(null)); + } - @Test - public void getHeaders() { - Enumeration enumeration = Header.getHeaders(Header.HTTP_FLAGS.toString()); + @Test + public void getHeaders() { + Enumeration enumeration = Header.getHeaders(Header.HTTP_FLAGS.toString()); - Assert.assertFalse(enumeration.hasMoreElements()); - Assert.assertNull(enumeration.nextElement()); + Assert.assertFalse(enumeration.hasMoreElements()); + Assert.assertNull(enumeration.nextElement()); - Enumeration needNull = Header.getHeaders("test"); - Assert.assertNull(needNull); + Enumeration needNull = Header.getHeaders("test"); + Assert.assertNull(needNull); - } + } - @Test - public void filteredHeaderNames() throws Exception { - Hashtable hashtable = new Hashtable(); - hashtable.put("a", "aa"); - hashtable.put("b", Header.HTTP_FLAGS.toString()); - hashtable.put("c", "cc"); - Enumeration elements = hashtable.elements(); + @Test + public void filteredHeaderNames() throws Exception { + Hashtable hashtable = new Hashtable(); + hashtable.put("a", "aa"); + hashtable.put("b", Header.HTTP_FLAGS.toString()); + hashtable.put("c", "cc"); + Enumeration elements = hashtable.elements(); - Enumeration enumeration = Header.filteredHeaderNames(elements); - int count = 0; - while(enumeration.hasMoreElements()) { - count++; - Assert.assertFalse(Header.hasHeader((String) enumeration.nextElement())); - } - Assert.assertEquals(count, 2); + Enumeration enumeration = Header.filteredHeaderNames(elements); + int count = 0; + while(enumeration.hasMoreElements()) { + count++; + Assert.assertFalse(Header.hasHeader((String) enumeration.nextElement())); + } + Assert.assertEquals(count, 2); - } + } } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/AspectWeaverClassTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/AspectWeaverClassTest.java index dc753ed57..be2325189 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/AspectWeaverClassTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/AspectWeaverClassTest.java @@ -27,193 +27,193 @@ import java.lang.reflect.Method; public class AspectWeaverClassTest { - private final String ORIGINAL = "com.navercorp.pinpoint.profiler.interceptor.bci.mock.Original"; - private final String ORIGINAL_SUB = "com.navercorp.pinpoint.profiler.interceptor.bci.mock.OriginalSub"; + private final String ORIGINAL = "com.navercorp.pinpoint.profiler.interceptor.bci.mock.Original"; + private final String ORIGINAL_SUB = "com.navercorp.pinpoint.profiler.interceptor.bci.mock.OriginalSub"; - private final String ASPECT = "com.navercorp.pinpoint.profiler.interceptor.bci.mock.TestAspect"; - private final String ASPECT_NO_EXTENTS = "com.navercorp.pinpoint.profiler.interceptor.bci.mock.TestAspect_NoExtents"; - private final String ASPECT_EXTENTS_SUB = "com.navercorp.pinpoint.profiler.interceptor.bci.mock.TestAspect_ExtentsSub"; + private final String ASPECT = "com.navercorp.pinpoint.profiler.interceptor.bci.mock.TestAspect"; + private final String ASPECT_NO_EXTENTS = "com.navercorp.pinpoint.profiler.interceptor.bci.mock.TestAspect_NoExtents"; + private final String ASPECT_EXTENTS_SUB = "com.navercorp.pinpoint.profiler.interceptor.bci.mock.TestAspect_ExtentsSub"; - private final String ERROR_ASPECT1 = "com.navercorp.pinpoint.profiler.interceptor.bci.mock.ErrorAspect"; - private final String ERROR_ASPECT2 = "com.navercorp.pinpoint.profiler.interceptor.bci.mock.ErrorAspect2"; + private final String ERROR_ASPECT1 = "com.navercorp.pinpoint.profiler.interceptor.bci.mock.ErrorAspect"; + private final String ERROR_ASPECT2 = "com.navercorp.pinpoint.profiler.interceptor.bci.mock.ErrorAspect2"; - private final String ERROR_ASPECT_INVALID_EXTENTS= "com.navercorp.pinpoint.profiler.interceptor.bci.mock.ErrorAspect_InvalidExtents"; + private final String ERROR_ASPECT_INVALID_EXTENTS= "com.navercorp.pinpoint.profiler.interceptor.bci.mock.ErrorAspect_InvalidExtents"; - public Object createAspect(String originalName, String aspectName) { - try { - ClassPool classPool = new ClassPool(true); - Loader loader = getLoader(classPool); + public Object createAspect(String originalName, String aspectName) { + try { + ClassPool classPool = new ClassPool(true); + Loader loader = getLoader(classPool); - CtClass ctOriginal = classPool.get(originalName); - CtClass ctAdvice = classPool.get(aspectName); + CtClass ctOriginal = classPool.get(originalName); + CtClass ctAdvice = classPool.get(aspectName); - AspectWeaverClass weaver = new AspectWeaverClass(); + AspectWeaverClass weaver = new AspectWeaverClass(); - weaver.weaving(ctOriginal, ctAdvice); + weaver.weaving(ctOriginal, ctAdvice); - Class aClass = loader.loadClass(originalName); - return aClass.newInstance(); - } catch (Exception e) { - throw new RuntimeException(e.getMessage(), e); - } - } + Class aClass = loader.loadClass(originalName); + return aClass.newInstance(); + } catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); + } + } private Loader getLoader(ClassPool pool) { return LoaderUtils.createLoader(pool); } - private Object createDefaultAspect() { - return createAspect(ORIGINAL, ASPECT); - } + private Object createDefaultAspect() { + return createAspect(ORIGINAL, ASPECT); + } - @Test - public void testVoid() throws Exception { + @Test + public void testVoid() throws Exception { - Object aspectObject = createDefaultAspect(); + Object aspectObject = createDefaultAspect(); - invoke(aspectObject, "testVoid"); - assertBeforeTouchCount(aspectObject, 1); - assertAfterTouchCount(aspectObject, 1); + invoke(aspectObject, "testVoid"); + assertBeforeTouchCount(aspectObject, 1); + assertAfterTouchCount(aspectObject, 1); - } + } - @Test - public void testInt() throws Exception { + @Test + public void testInt() throws Exception { - Object aspectObject = createDefaultAspect(); + Object aspectObject = createDefaultAspect(); - int returnValue = (Integer)invoke(aspectObject, "testInt"); - Assert.assertEquals(1, returnValue); + int returnValue = (Integer)invoke(aspectObject, "testInt"); + Assert.assertEquals(1, returnValue); - assertBeforeTouchCount(aspectObject, 1); - assertAfterTouchCount(aspectObject, 1); - } + assertBeforeTouchCount(aspectObject, 1); + assertAfterTouchCount(aspectObject, 1); + } - @Test - public void testString() throws Exception { + @Test + public void testString() throws Exception { - Object aspectObject = createDefaultAspect(); + Object aspectObject = createDefaultAspect(); - String returnValue = (String) invoke(aspectObject, "testString"); - Assert.assertEquals(returnValue, "testString"); + String returnValue = (String) invoke(aspectObject, "testString"); + Assert.assertEquals(returnValue, "testString"); - assertBeforeTouchCount(aspectObject, 1); - assertAfterTouchCount(aspectObject, 1); - } + assertBeforeTouchCount(aspectObject, 1); + assertAfterTouchCount(aspectObject, 1); + } - @Test - public void testUtilMethod() throws Exception { + @Test + public void testUtilMethod() throws Exception { - Object aspectObject = createDefaultAspect(); + Object aspectObject = createDefaultAspect(); - int returnValue = (Integer)invoke(aspectObject, "testUtilMethod"); - Assert.assertEquals(1, returnValue); + int returnValue = (Integer)invoke(aspectObject, "testUtilMethod"); + Assert.assertEquals(1, returnValue); - assertBeforeTouchCount(aspectObject, 1); - assertAfterTouchCount(aspectObject, 1); - } + assertBeforeTouchCount(aspectObject, 1); + assertAfterTouchCount(aspectObject, 1); + } - @Test - public void testNoTouch() throws Exception { + @Test + public void testNoTouch() throws Exception { - Object aspectObject = createDefaultAspect(); + Object aspectObject = createDefaultAspect(); - Object returnValue = invoke(aspectObject, "testNoTouch"); - Assert.assertEquals(null, returnValue); + Object returnValue = invoke(aspectObject, "testNoTouch"); + Assert.assertEquals(null, returnValue); - assertBeforeTouchCount(aspectObject, 0); - assertAfterTouchCount(aspectObject, 0); - } + assertBeforeTouchCount(aspectObject, 0); + assertAfterTouchCount(aspectObject, 0); + } - @Test - public void testInternalMethod() throws Exception { + @Test + public void testInternalMethod() throws Exception { - Object aspectObject = createDefaultAspect(); + Object aspectObject = createDefaultAspect(); - Object returnValue = invoke(aspectObject, "testInternalMethod"); - Assert.assertEquals(null, returnValue); + Object returnValue = invoke(aspectObject, "testInternalMethod"); + Assert.assertEquals(null, returnValue); - assertBeforeTouchCount(aspectObject, 1); - assertAfterTouchCount(aspectObject, 1); - } + assertBeforeTouchCount(aspectObject, 1); + assertAfterTouchCount(aspectObject, 1); + } - @Test - public void testMethodCall() throws Exception { + @Test + public void testMethodCall() throws Exception { - Object aspectObject = createDefaultAspect(); + Object aspectObject = createDefaultAspect(); - invoke(aspectObject, "testMethodCall"); + invoke(aspectObject, "testMethodCall"); - } + } - @Test(expected = Exception.class) - public void testSignatureMiss() throws Exception { - createAspect(ORIGINAL, ERROR_ASPECT1); - } + @Test(expected = Exception.class) + public void testSignatureMiss() throws Exception { + createAspect(ORIGINAL, ERROR_ASPECT1); + } - @Test(expected = Exception.class) - public void testInternalTypeMiss() throws Exception { + @Test(expected = Exception.class) + public void testInternalTypeMiss() throws Exception { - createAspect(ORIGINAL, ERROR_ASPECT2); + createAspect(ORIGINAL, ERROR_ASPECT2); - } + } - @Test - public void testNo_extents() throws Exception { + @Test + public void testNo_extents() throws Exception { - Object aspectObject = createAspect(ORIGINAL, ASPECT_NO_EXTENTS); + Object aspectObject = createAspect(ORIGINAL, ASPECT_NO_EXTENTS); - Object returnValue = invoke(aspectObject, "testVoid"); - Assert.assertEquals(null, returnValue); + Object returnValue = invoke(aspectObject, "testVoid"); + Assert.assertEquals(null, returnValue); - } + } - @Test - public void testExtents_Sub() throws Exception { + @Test + public void testExtents_Sub() throws Exception { - Object aspectObject = createAspect(ORIGINAL_SUB, ASPECT_EXTENTS_SUB); + Object aspectObject = createAspect(ORIGINAL_SUB, ASPECT_EXTENTS_SUB); - Object returnValue = invoke(aspectObject, "testVoid"); - Assert.assertEquals(null, returnValue); + Object returnValue = invoke(aspectObject, "testVoid"); + Assert.assertEquals(null, returnValue); - } + } - @Test(expected = Exception.class) - public void testInvalid_extents() throws Exception { + @Test(expected = Exception.class) + public void testInvalid_extents() throws Exception { - Object aspectObject = createAspect(ORIGINAL, ERROR_ASPECT_INVALID_EXTENTS); + Object aspectObject = createAspect(ORIGINAL, ERROR_ASPECT_INVALID_EXTENTS); - Object returnValue = invoke(aspectObject, "testVoid"); - Assert.assertEquals(null, returnValue); + Object returnValue = invoke(aspectObject, "testVoid"); + Assert.assertEquals(null, returnValue); - } + } - private Object invoke(Object o, String methodName, Object... args) { - try { - Class clazz = o.getClass(); - Method method = clazz.getMethod(methodName); - return method.invoke(o, args); - } catch (Exception e) { - throw new RuntimeException(e.getMessage(), e); - } - } + private Object invoke(Object o, String methodName, Object... args) { + try { + Class clazz = o.getClass(); + Method method = clazz.getMethod(methodName); + return method.invoke(o, args); + } catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); + } + } - private void assertBeforeTouchCount(Object aspectObject, int count) { - int touchCount = (Integer)invoke(aspectObject, "getTouchBefore"); - Assert.assertEquals(touchCount, count); - } + private void assertBeforeTouchCount(Object aspectObject, int count) { + int touchCount = (Integer)invoke(aspectObject, "getTouchBefore"); + Assert.assertEquals(touchCount, count); + } - private void assertAfterTouchCount(Object aspectObject, int count) { - int touchCount = (Integer)invoke(aspectObject, "getTouchAfter"); - Assert.assertEquals(touchCount, count); - } + private void assertAfterTouchCount(Object aspectObject, int count) { + int touchCount = (Integer)invoke(aspectObject, "getTouchAfter"); + Assert.assertEquals(touchCount, count); + } } \ No newline at end of file diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/JavaAssistTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/JavaAssistTest.java index 8949f6788..f195eb783 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/JavaAssistTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/JavaAssistTest.java @@ -117,7 +117,7 @@ public class JavaAssistTest { logger.debug("callA:{}", callA); callA.addLocalVariable("__test", object); String inti = "__test = \"abc\";"; -// callA.insertBefore("__test = \"abc\";); +// callA.insertBefore("__test = \"abc\";); callA.insertBefore("{com.navercorp.pinpoint.profiler.interceptor.bci.TestObject.before();}"); callA.insertAfter("{com.navercorp.pinpoint.profiler.interceptor.bci.TestObject.after();}"); callA.addCatch("{ com.navercorp.pinpoint.profiler.interceptor.bci.TestObject.callCatch(); throw $e; }", pool.get("java.lang.Throwable")); diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/TestObject.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/TestObject.java index 31217261f..b09e4bef0 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/TestObject.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/TestObject.java @@ -26,41 +26,41 @@ public class TestObject { private Logger logger = LoggerFactory.getLogger(this.getClass().getName()); private int callA; - private boolean isthrow = false; - private int returnCode = 1; + private boolean isthrow = false; + private int returnCode = 1; - public void setIsthrow(boolean isthrow) { - this.isthrow = isthrow; - } - - public void setReturnCode(int returnCode) { - this.returnCode = returnCode; - } - - public int callA() { - logger.info("callA"); - int i = callA++; - if (isthrow) { - throw new RuntimeException("ddd"); - } - System.out.println("callA"); - if(returnCode == 1) { - return 1; - } if (returnCode == 10){ - return -1; - } - return 0; + public void setIsthrow(boolean isthrow) { + this.isthrow = isthrow; } - public static void before() { - System.out.println("before"); - } - public static void after() { - System.out.println("after"); - } - public static void callCatch() { - System.out.println("callCatch"); - } + public void setReturnCode(int returnCode) { + this.returnCode = returnCode; + } + + public int callA() { + logger.info("callA"); + int i = callA++; + if (isthrow) { + throw new RuntimeException("ddd"); + } + System.out.println("callA"); + if(returnCode == 1) { + return 1; + } if (returnCode == 10){ + return -1; + } + return 0; + } + + public static void before() { + System.out.println("before"); + } + public static void after() { + System.out.println("after"); + } + public static void callCatch() { + System.out.println("callCatch"); + } public String hello(String a) { System.out.println("a:" + a); diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/ErrorAspect.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/ErrorAspect.java index 2d02e428f..b9e4a73f4 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/ErrorAspect.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/ErrorAspect.java @@ -26,13 +26,13 @@ import com.navercorp.pinpoint.profiler.interceptor.aspect.PointCut; @Aspect public abstract class ErrorAspect { - @PointCut - public void testSignatureMiss() { - __testVoid(); - } + @PointCut + public void testSignatureMiss() { + __testVoid(); + } - @JointPoint - abstract void __testVoid(); + @JointPoint + abstract void __testVoid(); diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/ErrorAspect2.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/ErrorAspect2.java index f9c1a0d72..bfa660720 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/ErrorAspect2.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/ErrorAspect2.java @@ -26,14 +26,14 @@ import com.navercorp.pinpoint.profiler.interceptor.aspect.PointCut; @Aspect public abstract class ErrorAspect2 { - @PointCut - public int testInternalTypeMiss() { - __testVoid(); - return 0; - } + @PointCut + public int testInternalTypeMiss() { + __testVoid(); + return 0; + } - @JointPoint - abstract void __testVoid(); + @JointPoint + abstract void __testVoid(); diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/ErrorAspect_InvalidExtents.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/ErrorAspect_InvalidExtents.java index c183e4c0b..2c7da9c10 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/ErrorAspect_InvalidExtents.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/ErrorAspect_InvalidExtents.java @@ -26,13 +26,13 @@ import com.navercorp.pinpoint.profiler.interceptor.aspect.PointCut; @Aspect public abstract class ErrorAspect_InvalidExtents extends Thread { - @PointCut - public void testVoid() { - __testVoid(); - } + @PointCut + public void testVoid() { + __testVoid(); + } - @JointPoint - abstract void __testVoid(); + @JointPoint + abstract void __testVoid(); diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/Original.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/Original.java index 98a130615..6573cae2f 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/Original.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/Original.java @@ -24,87 +24,87 @@ import java.util.Map; */ public class Original { - public int touchVoid = 0; - public int touchInt = 0; - public int touchUtil = 0; + public int touchVoid = 0; + public int touchInt = 0; + public int touchUtil = 0; - public int touchBefore; - public int touchAfter; + public int touchBefore; + public int touchAfter; - public void testVoid() { - touchVoid++; - } + public void testVoid() { + touchVoid++; + } - public int getTouchVoid() { - return touchVoid; - } + public int getTouchVoid() { + return touchVoid; + } - public int testInt() { - return ++touchInt; - } + public int testInt() { + return ++touchInt; + } - public int getTouchInt() { - return touchInt; - } + public int getTouchInt() { + return touchInt; + } - public String testString() { - return "testString"; - } + public String testString() { + return "testString"; + } - public int testUtilMethod() { - return ++touchUtil; - } + public int testUtilMethod() { + return ++touchUtil; + } - void touchBefore() { - touchBefore++; - } + void touchBefore() { + touchBefore++; + } - public int getTouchBefore() { - return touchBefore; - } + public int getTouchBefore() { + return touchBefore; + } - void touchAfter() { - touchAfter++; - } + void touchAfter() { + touchAfter++; + } - public int getTouchAfter() { - return touchAfter; - } + public int getTouchAfter() { + return touchAfter; + } - public void testNoTouch() { + public void testNoTouch() { - } + } - public void methodA() { - System.out.println("---a"); - } + public void methodA() { + System.out.println("---a"); + } - public void methodB() { - System.out.println("---b"); - } + public void methodB() { + System.out.println("---b"); + } - public void testInternalMethod() { - touchBefore(); - touchAfter(); - //super - String s = toString(); - } + public void testInternalMethod() { + touchBefore(); + touchAfter(); + //super + String s = toString(); + } - public int testSignatureMiss() { - return -1; - } + public int testSignatureMiss() { + return -1; + } - public void testMethodCall() { - } + public void testMethodCall() { + } - public Map testGeneric() { - return Collections.emptyMap(); - } + public Map testGeneric() { + return Collections.emptyMap(); + } } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/OriginalSub.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/OriginalSub.java index a0dcf5998..a0819e535 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/OriginalSub.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/OriginalSub.java @@ -20,7 +20,7 @@ package com.navercorp.pinpoint.profiler.interceptor.bci.mock; * @author emeroad */ public class OriginalSub extends Original { - @Override - public void testVoid() { - } + @Override + public void testVoid() { + } } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/TestAspect.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/TestAspect.java index b87bc3ee2..78d91d139 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/TestAspect.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/TestAspect.java @@ -29,75 +29,75 @@ import java.util.Map; @Aspect public abstract class TestAspect extends Original { - @PointCut - public void testVoid() { - touchBefore(); - __testVoid(); - touchAfter(); - } + @PointCut + public void testVoid() { + touchBefore(); + __testVoid(); + touchAfter(); + } - @JointPoint - abstract void __testVoid(); + @JointPoint + abstract void __testVoid(); - @PointCut - public int testInt() { - touchBefore(); - final int result = __testInt(); - touchAfter(); - return result; - } + @PointCut + public int testInt() { + touchBefore(); + final int result = __testInt(); + touchAfter(); + return result; + } - @JointPoint - abstract int __testInt(); + @JointPoint + abstract int __testInt(); - @PointCut - public String testString() { - touchBefore(); - String s = __testString(); - touchAfter(); - return s; - } + @PointCut + public String testString() { + touchBefore(); + String s = __testString(); + touchAfter(); + return s; + } - @JointPoint - abstract String __testString(); + @JointPoint + abstract String __testString(); - @PointCut - public int testUtilMethod() { - touchBefore(); - int result = __testInt(); - utilMethod(); - touchAfter(); - return result; - } + @PointCut + public int testUtilMethod() { + touchBefore(); + int result = __testInt(); + utilMethod(); + touchAfter(); + return result; + } - private String utilMethod() { - return "Util"; - } + private String utilMethod() { + return "Util"; + } - @PointCut - public void testNoTouch() { - __testVoid(); - } + @PointCut + public void testNoTouch() { + __testVoid(); + } - @PointCut - public void testInternalMethod() { - __testVoid(); - } + @PointCut + public void testInternalMethod() { + __testVoid(); + } - @PointCut - public void testMethodCall() { - BytesUtils.toBytes("test"); - __testMethodCall(); - } + @PointCut + public void testMethodCall() { + BytesUtils.toBytes("test"); + __testMethodCall(); + } - @JointPoint - abstract void __testMethodCall(); + @JointPoint + abstract void __testMethodCall(); - @PointCut - public Map testGeneric() { - return null; - } + @PointCut + public Map testGeneric() { + return null; + } } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/TestAspect_ExtentsSub.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/TestAspect_ExtentsSub.java index 9ea78c58a..460247ee0 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/TestAspect_ExtentsSub.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/TestAspect_ExtentsSub.java @@ -26,15 +26,15 @@ import com.navercorp.pinpoint.profiler.interceptor.aspect.PointCut; @Aspect public abstract class TestAspect_ExtentsSub extends OriginalSub { - @PointCut - public void testVoid() { - touchBefore(); - __testVoid(); - touchAfter(); - } + @PointCut + public void testVoid() { + touchBefore(); + __testVoid(); + touchAfter(); + } - @JointPoint - abstract void __testVoid(); + @JointPoint + abstract void __testVoid(); diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/TestAspect_NoExtents.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/TestAspect_NoExtents.java index 26409a3f5..aa3892c5f 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/TestAspect_NoExtents.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/mock/TestAspect_NoExtents.java @@ -27,13 +27,13 @@ import com.navercorp.pinpoint.profiler.interceptor.aspect.PointCut; @Aspect public abstract class TestAspect_NoExtents { - @PointCut - public void testVoid() { - __testVoid(); - } + @PointCut + public void testVoid() { + __testVoid(); + } - @JointPoint - abstract void __testVoid(); + @JointPoint + abstract void __testVoid(); diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/ApiInterceptorTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/ApiInterceptorTest.java index 00e03641b..085cd7664 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/ApiInterceptorTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/ApiInterceptorTest.java @@ -38,43 +38,43 @@ import org.slf4j.LoggerFactory; public class ApiInterceptorTest extends BaseInterceptorTest { - static final Logger logger = LoggerFactory.getLogger(ApiInterceptorTest.class); + static final Logger logger = LoggerFactory.getLogger(ApiInterceptorTest.class); - ApiInterceptor interceptor = new ApiInterceptor(); - MemcachedClient client = mock(MockMemcachedClient.class); + ApiInterceptor interceptor = new ApiInterceptor(); + MemcachedClient client = mock(MockMemcachedClient.class); - @Before - public void beforeEach() { - setInterceptor(interceptor); - MethodDescriptor methodDescriptor = new DefaultMethodDescriptor( - MockMemcachedClient.class.getName(), "set", new String[] { - "java.lang.String", "int", "java.lang.Object" }, - new String[] { "key", "exptime", "value" }); - /* FIXME NPE. Skip for now. - setMethodDescriptor(methodDescriptor); - */ - super.beforeEach(); - } + @Before + public void beforeEach() { + setInterceptor(interceptor); + MethodDescriptor methodDescriptor = new DefaultMethodDescriptor( + MockMemcachedClient.class.getName(), "set", new String[] { + "java.lang.String", "int", "java.lang.Object" }, + new String[] { "key", "exptime", "value" }); + /* FIXME NPE. Skip for now. + setMethodDescriptor(methodDescriptor); + */ + super.beforeEach(); + } - @Test - public void testAround() { - Object[] args = new Object[] {"key", 10, "my_value"}; - interceptor.before(client, args); - interceptor.after(client, args, null, null); - } + @Test + public void testAround() { + Object[] args = new Object[] {"key", 10, "my_value"}; + interceptor.before(client, args); + interceptor.after(client, args, null, null); + } - /** - * Fake MemcachedClient - */ - class MockMemcachedClient extends MemcachedClient { - public MockMemcachedClient(ConnectionFactory cf, - List addrs) throws IOException { - super(cf, addrs); - } + /** + * Fake MemcachedClient + */ + class MockMemcachedClient extends MemcachedClient { + public MockMemcachedClient(ConnectionFactory cf, + List addrs) throws IOException { + super(cf, addrs); + } - public String __getServiceCode() { - return "MEMCACHED"; - } - } + public String __getServiceCode() { + return "MEMCACHED"; + } + } } \ No newline at end of file diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureGetInterceptorTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureGetInterceptorTest.java index 9e743be61..5a1d69c1b 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureGetInterceptorTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/arcus/interceptor/FutureGetInterceptorTest.java @@ -49,38 +49,38 @@ import org.slf4j.LoggerFactory; public class FutureGetInterceptorTest extends BaseInterceptorTest { - private final Logger logger = LoggerFactory.getLogger(FutureGetInterceptorTest.class); + private final Logger logger = LoggerFactory.getLogger(FutureGetInterceptorTest.class); - FutureGetInterceptor interceptor = new FutureGetInterceptor(); + FutureGetInterceptor interceptor = new FutureGetInterceptor(); - @Before - public void beforeEach() { - setInterceptor(interceptor); - super.beforeEach(); - } + @Before + public void beforeEach() { + setInterceptor(interceptor); + super.beforeEach(); + } - @Test - public void testSuccessful() { - Long timeout = 1000L; - TimeUnit unit = TimeUnit.MILLISECONDS; - - MockOperationFuture future = mock(MockOperationFuture.class); - MockOperation operation = mock(MockOperation.class); - - try { - when(operation.getException()).thenReturn(null); - when(operation.isCancelled()).thenReturn(false); - when(future.__getOperation()).thenReturn(operation); + @Test + public void testSuccessful() { + Long timeout = 1000L; + TimeUnit unit = TimeUnit.MILLISECONDS; + + MockOperationFuture future = mock(MockOperationFuture.class); + MockOperation operation = mock(MockOperation.class); + + try { + when(operation.getException()).thenReturn(null); + when(operation.isCancelled()).thenReturn(false); + when(future.__getOperation()).thenReturn(operation); MemcachedNode node = getMockMemcachedNode(); - when(operation.getHandlingNode()).thenReturn(node); - - interceptor.before(future, new Object[] { timeout, unit }); - interceptor.after(future, new Object[] { timeout, unit }, null, null); - } catch (Exception e) { - fail(e.getMessage()); - } - } + when(operation.getHandlingNode()).thenReturn(node); + + interceptor.before(future, new Object[] { timeout, unit }); + interceptor.after(future, new Object[] { timeout, unit }, null, null); + } catch (Exception e) { + fail(e.getMessage()); + } + } private MemcachedNode getMockMemcachedNode() throws IOException { java.nio.channels.SocketChannel socketChannel = java.nio.channels.SocketChannel.open(); @@ -92,97 +92,97 @@ public class FutureGetInterceptorTest extends BaseInterceptorTest { } @Test - public void testTimeoutException() { - Long timeout = 1000L; - TimeUnit unit = TimeUnit.MILLISECONDS; - - MockOperationFuture future = mock(MockOperationFuture.class); - MockOperation operation = mock(MockOperation.class); - - try { - OperationException exception = new OperationException(OperationErrorType.GENERAL, "timed out"); - when(operation.getException()).thenReturn(exception); - when(operation.isCancelled()).thenReturn(true); - when(future.__getOperation()).thenReturn(operation); - - MemcachedNode node = getMockMemcachedNode(); - when(operation.getHandlingNode()).thenReturn(node); - - interceptor.before(future, new Object[] { timeout, unit }); - interceptor.after(future, new Object[] { timeout, unit }, null, null); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - class MockOperationFuture extends OperationFuture { - public MockOperationFuture(CountDownLatch l, AtomicReference oref, - long opTimeout) { - super(l, oref, opTimeout); - } - - public String __getServiceCode() { - return "MEMCACHED"; - } - - public Operation __getOperation() { - return null; - } - } - - class MockOperation implements Operation { + public void testTimeoutException() { + Long timeout = 1000L; + TimeUnit unit = TimeUnit.MILLISECONDS; - public String __getServiceCode() { - return "MEMCACHED"; - } - - public void cancel() { - } + MockOperationFuture future = mock(MockOperationFuture.class); + MockOperation operation = mock(MockOperation.class); - public ByteBuffer getBuffer() { - return null; - } + try { + OperationException exception = new OperationException(OperationErrorType.GENERAL, "timed out"); + when(operation.getException()).thenReturn(exception); + when(operation.isCancelled()).thenReturn(true); + when(future.__getOperation()).thenReturn(operation); - public OperationCallback getCallback() { - return null; - } + MemcachedNode node = getMockMemcachedNode(); + when(operation.getHandlingNode()).thenReturn(node); - public OperationException getException() { - return null; - } + interceptor.before(future, new Object[] { timeout, unit }); + interceptor.after(future, new Object[] { timeout, unit }, null, null); + } catch (Exception e) { + fail(e.getMessage()); + } + } - public MemcachedNode getHandlingNode() { - return null; - } + class MockOperationFuture extends OperationFuture { + public MockOperationFuture(CountDownLatch l, AtomicReference oref, + long opTimeout) { + super(l, oref, opTimeout); + } - public OperationState getState() { - return null; - } + public String __getServiceCode() { + return "MEMCACHED"; + } - public void handleRead(ByteBuffer arg0) { - - } + public Operation __getOperation() { + return null; + } + } - public boolean hasErrored() { - return false; - } + class MockOperation implements Operation { - public void initialize() { - } + public String __getServiceCode() { + return "MEMCACHED"; + } - public boolean isCancelled() { - return false; - } + public void cancel() { + } - public void readFromBuffer(ByteBuffer arg0) throws IOException { - } + public ByteBuffer getBuffer() { + return null; + } - public void setHandlingNode(MemcachedNode arg0) { - } + public OperationCallback getCallback() { + return null; + } - public void writeComplete() { - } - - } + public OperationException getException() { + return null; + } + + public MemcachedNode getHandlingNode() { + return null; + } + + public OperationState getState() { + return null; + } + + public void handleRead(ByteBuffer arg0) { + + } + + public boolean hasErrored() { + return false; + } + + public void initialize() { + } + + public boolean isCancelled() { + return false; + } + + public void readFromBuffer(ByteBuffer arg0) throws IOException { + } + + public void setHandlingNode(MemcachedNode arg0) { + } + + public void writeComplete() { + } + + } } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/SqlMapClientImplModifierTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/SqlMapClientImplModifierTest.java index 99d249380..4ee74cadf 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/SqlMapClientImplModifierTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/SqlMapClientImplModifierTest.java @@ -43,261 +43,261 @@ import com.navercorp.pinpoint.test.junit4.BasePinpointTest; */ public class SqlMapClientImplModifierTest extends BasePinpointTest { - public class MockSqlMapExecutorDelegate extends SqlMapExecutorDelegate { - @Override - public SessionScope beginSessionScope() { - return mockSessionScope; - } - } + public class MockSqlMapExecutorDelegate extends SqlMapExecutorDelegate { + @Override + public SessionScope beginSessionScope() { + return mockSessionScope; + } + } - @Mock - private MockSqlMapExecutorDelegate mockSqlMapExecutorDelegate; - @Mock - private SessionScope mockSessionScope; + @Mock + private MockSqlMapExecutorDelegate mockSqlMapExecutorDelegate; + @Mock + private SessionScope mockSessionScope; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - when(this.mockSqlMapExecutorDelegate.beginSessionScope()).thenReturn(this.mockSessionScope); - } - - @Test - public void exceptionsThrownShouldBeTraced() throws Exception { - // Given - when(this.mockSqlMapExecutorDelegate.beginSessionScope()).thenReturn(null); - SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); - // When - try { - sqlMapClient.insert("insertShouldThrowNPE"); - fail("sqlMapClient.insert should throw NullPointerException"); - } catch (NullPointerException e) { - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(1)); - final SpanEventBo exceptionSpanEventBo = spanEvents.get(0); - assertThat(exceptionSpanEventBo.hasException(), is(true)); - assertThat(exceptionSpanEventBo.getExceptionId(), not(0)); - } - } - - @Test(expected=NullPointerException.class) - public void test() throws SQLException { + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + when(this.mockSqlMapExecutorDelegate.beginSessionScope()).thenReturn(this.mockSessionScope); + } + + @Test + public void exceptionsThrownShouldBeTraced() throws Exception { + // Given + when(this.mockSqlMapExecutorDelegate.beginSessionScope()).thenReturn(null); + SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); + // When + try { + sqlMapClient.insert("insertShouldThrowNPE"); + fail("sqlMapClient.insert should throw NullPointerException"); + } catch (NullPointerException e) { + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(1)); + final SpanEventBo exceptionSpanEventBo = spanEvents.get(0); + assertThat(exceptionSpanEventBo.hasException(), is(true)); + assertThat(exceptionSpanEventBo.getExceptionId(), not(0)); + } + } + + @Test(expected=NullPointerException.class) + public void test() throws SQLException { // Given when(this.mockSqlMapExecutorDelegate.beginSessionScope()).thenReturn(null); SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); // When sqlMapClient.insert("insertShouldThrowNPE"); - } - - @Test - public void nullParametersShouldNotBeTraced() throws Exception { - // Given - SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); - // When - sqlMapClient.insert(null); - sqlMapClient.queryForList(null); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(2)); - - // Check Method - final SpanEventBo insertSpanEventBo = spanEvents.get(0); - final SpanEventBo queryForListSpanEventBo = spanEvents.get(1); - assertThat(insertSpanEventBo.getApiId(), not(0)); - assertThat(queryForListSpanEventBo.getApiId(), not(0)); - assertThat(insertSpanEventBo.getApiId(), not(queryForListSpanEventBo.getApiId())); - - // Check Parameter - assertNull(insertSpanEventBo.getAnnotationBoList()); - assertNull(queryForListSpanEventBo.getAnnotationBoList()); - } - - @Test - public void sameApiCallsShouldHaveTheSameApiId() throws Exception { - // Given - SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); - // When - sqlMapClient.insert("insertA"); - sqlMapClient.insert("insertB"); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(2)); - - // Check Method - final SpanEventBo insertASpanEventBo = spanEvents.get(0); - final SpanEventBo insertBSpanEventBo = spanEvents.get(1); - assertThat(insertASpanEventBo.getApiId(), not(0)); - assertThat(insertBSpanEventBo.getApiId(), not(0)); - assertThat(insertASpanEventBo.getApiId(), is(insertBSpanEventBo.getApiId())); - - } - - @Test - public void insertShouldBeTraced() throws Exception { - // Given - SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); - // When - sqlMapClient.insert("insertId"); - sqlMapClient.insert("insertId", new Object()); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(2)); + } - // Check Method - final SpanEventBo insertWith1ArgSpanEventBo = spanEvents.get(0); - final SpanEventBo insertWith2ArgSpanEventBo = spanEvents.get(1); - assertThat(insertWith1ArgSpanEventBo.getApiId(), not(0)); - assertThat(insertWith2ArgSpanEventBo.getApiId(), not(0)); - assertThat(insertWith1ArgSpanEventBo.getApiId(), not(insertWith2ArgSpanEventBo.getApiId())); + @Test + public void nullParametersShouldNotBeTraced() throws Exception { + // Given + SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); + // When + sqlMapClient.insert(null); + sqlMapClient.queryForList(null); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(2)); - // Check Parameter - final List insertWith1ArgAnnotations = insertWith1ArgSpanEventBo.getAnnotationBoList(); - assertThat(insertWith1ArgAnnotations.size(), is(1)); - final AnnotationBo insertWith1ArgParameterAnnotation = insertWith1ArgAnnotations.get(0); - assertThat(insertWith1ArgParameterAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - - final List insertWith2ArgAnnotations = insertWith2ArgSpanEventBo.getAnnotationBoList(); - assertThat(insertWith2ArgAnnotations.size(), is(1)); - final AnnotationBo insertWith2ArgAnnotation = insertWith2ArgAnnotations.get(0); - assertThat(insertWith2ArgAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - - } - - @Test - public void deleteShouldBeTraced() throws Exception { - // Given - SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); - // When - sqlMapClient.delete("deleteId"); - sqlMapClient.delete("deleteId", new Object()); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(2)); + // Check Method + final SpanEventBo insertSpanEventBo = spanEvents.get(0); + final SpanEventBo queryForListSpanEventBo = spanEvents.get(1); + assertThat(insertSpanEventBo.getApiId(), not(0)); + assertThat(queryForListSpanEventBo.getApiId(), not(0)); + assertThat(insertSpanEventBo.getApiId(), not(queryForListSpanEventBo.getApiId())); - // Check Method - final SpanEventBo deleteWith1ArgSpanEvent = spanEvents.get(0); - final SpanEventBo deleteWith2ArgSpanEvent = spanEvents.get(1); - assertThat(deleteWith1ArgSpanEvent.getApiId(), not(0)); - assertThat(deleteWith2ArgSpanEvent.getApiId(), not(0)); - assertThat(deleteWith1ArgSpanEvent.getApiId(), not(deleteWith2ArgSpanEvent.getApiId())); + // Check Parameter + assertNull(insertSpanEventBo.getAnnotationBoList()); + assertNull(queryForListSpanEventBo.getAnnotationBoList()); + } - // Check Parameter - final List deleteWith1ArgAnnotations = deleteWith1ArgSpanEvent.getAnnotationBoList(); - assertThat(deleteWith1ArgAnnotations.size(), is(1)); - final AnnotationBo deleteWith1ArgParameterAnnotation = deleteWith1ArgAnnotations.get(0); - assertThat(deleteWith1ArgParameterAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - - final List deleteWith2ArgAnnotations = deleteWith2ArgSpanEvent.getAnnotationBoList(); - assertThat(deleteWith2ArgAnnotations.size(), is(1)); - final AnnotationBo deleteWith2ArgAnnotation = deleteWith2ArgAnnotations.get(0); - assertThat(deleteWith2ArgAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - } - - @Test - public void updateShouldBeTraced() throws Exception { - // Given - SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); - // When - sqlMapClient.update("updateId"); - sqlMapClient.update("updateId", new Object()); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(2)); + @Test + public void sameApiCallsShouldHaveTheSameApiId() throws Exception { + // Given + SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); + // When + sqlMapClient.insert("insertA"); + sqlMapClient.insert("insertB"); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(2)); - // Check Method - final SpanEventBo updateWith1ArgSpanEvent = spanEvents.get(0); - final SpanEventBo updateWith2ArgSpanEvent = spanEvents.get(1); - assertThat(updateWith1ArgSpanEvent.getApiId(), not(0)); - assertThat(updateWith2ArgSpanEvent.getApiId(), not(0)); - assertThat(updateWith1ArgSpanEvent.getApiId(), not(updateWith2ArgSpanEvent.getApiId())); + // Check Method + final SpanEventBo insertASpanEventBo = spanEvents.get(0); + final SpanEventBo insertBSpanEventBo = spanEvents.get(1); + assertThat(insertASpanEventBo.getApiId(), not(0)); + assertThat(insertBSpanEventBo.getApiId(), not(0)); + assertThat(insertASpanEventBo.getApiId(), is(insertBSpanEventBo.getApiId())); - // Check Parameter - final List updateWith1ArgAnnotations = updateWith1ArgSpanEvent.getAnnotationBoList(); - assertThat(updateWith1ArgAnnotations.size(), is(1)); - final AnnotationBo updateWith1ArgParameterAnnotation = updateWith1ArgAnnotations.get(0); - assertThat(updateWith1ArgParameterAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - - final List updateWith2ArgAnnotations = updateWith2ArgSpanEvent.getAnnotationBoList(); - assertThat(updateWith2ArgAnnotations.size(), is(1)); - final AnnotationBo updateWith2ArgAnnotation = updateWith2ArgAnnotations.get(0); - assertThat(updateWith2ArgAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - - } + } - @Test - public void queryForListShouldBeTraced() throws Exception { - // Given - SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); - // When - sqlMapClient.queryForList("abc"); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(1)); + @Test + public void insertShouldBeTraced() throws Exception { + // Given + SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); + // When + sqlMapClient.insert("insertId"); + sqlMapClient.insert("insertId", new Object()); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(2)); - // Check Method - final SpanEventBo apiCallSpanEventBo = spanEvents.get(0); - assertThat(apiCallSpanEventBo.getApiId(), not(0)); + // Check Method + final SpanEventBo insertWith1ArgSpanEventBo = spanEvents.get(0); + final SpanEventBo insertWith2ArgSpanEventBo = spanEvents.get(1); + assertThat(insertWith1ArgSpanEventBo.getApiId(), not(0)); + assertThat(insertWith2ArgSpanEventBo.getApiId(), not(0)); + assertThat(insertWith1ArgSpanEventBo.getApiId(), not(insertWith2ArgSpanEventBo.getApiId())); - // Check Parameter - final List annotationBoList = apiCallSpanEventBo.getAnnotationBoList(); - assertThat(annotationBoList.size(), is(1)); + // Check Parameter + final List insertWith1ArgAnnotations = insertWith1ArgSpanEventBo.getAnnotationBoList(); + assertThat(insertWith1ArgAnnotations.size(), is(1)); + final AnnotationBo insertWith1ArgParameterAnnotation = insertWith1ArgAnnotations.get(0); + assertThat(insertWith1ArgParameterAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - final AnnotationBo parameterAnnotationBo = annotationBoList.get(0); - assertThat(parameterAnnotationBo.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - } + final List insertWith2ArgAnnotations = insertWith2ArgSpanEventBo.getAnnotationBoList(); + assertThat(insertWith2ArgAnnotations.size(), is(1)); + final AnnotationBo insertWith2ArgAnnotation = insertWith2ArgAnnotations.get(0); + assertThat(insertWith2ArgAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - @Test - public void queryForObjectShouldBeTraced() throws Exception { - // Given - SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); - // When - sqlMapClient.queryForObject("abrgrgfdaghertah", new Object()); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(1)); + } - // Check Method - final SpanEventBo apiCallSpanEventBo = spanEvents.get(0); - assertThat(apiCallSpanEventBo.getApiId(), not(0)); + @Test + public void deleteShouldBeTraced() throws Exception { + // Given + SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); + // When + sqlMapClient.delete("deleteId"); + sqlMapClient.delete("deleteId", new Object()); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(2)); - // Check Parameter - final List annotationBoList = apiCallSpanEventBo.getAnnotationBoList(); - assertThat(annotationBoList.size(), is(1)); + // Check Method + final SpanEventBo deleteWith1ArgSpanEvent = spanEvents.get(0); + final SpanEventBo deleteWith2ArgSpanEvent = spanEvents.get(1); + assertThat(deleteWith1ArgSpanEvent.getApiId(), not(0)); + assertThat(deleteWith2ArgSpanEvent.getApiId(), not(0)); + assertThat(deleteWith1ArgSpanEvent.getApiId(), not(deleteWith2ArgSpanEvent.getApiId())); - final AnnotationBo parameterAnnotationBo = annotationBoList.get(0); - assertThat(parameterAnnotationBo.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - } - - @Ignore // Changed to trace only query operations - @Test - public void transactionsShouldBeTraced() throws Exception { - // Given - SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); - // When - sqlMapClient.startTransaction(); - sqlMapClient.commitTransaction(); - sqlMapClient.endTransaction(); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(3)); - - // Check Method - final SpanEventBo startTransactionSpanEventBo = spanEvents.get(0); - final SpanEventBo commitTransactionSpanEventBo = spanEvents.get(1); - final SpanEventBo endTransactionSpanEventBo = spanEvents.get(2); - - assertThat(startTransactionSpanEventBo.getApiId(), not(0)); - assertThat(commitTransactionSpanEventBo.getApiId(), not(0)); - assertThat(endTransactionSpanEventBo.getApiId(), not(0)); - - assertThat(startTransactionSpanEventBo.getApiId(), not(commitTransactionSpanEventBo.getApiId())); - assertThat(commitTransactionSpanEventBo.getApiId(), not(endTransactionSpanEventBo.getApiId())); - assertThat(endTransactionSpanEventBo.getApiId(), not(startTransactionSpanEventBo.getApiId())); - - // Check Parameter - assertNull(startTransactionSpanEventBo.getAnnotationBoList()); - assertNull(commitTransactionSpanEventBo.getAnnotationBoList()); - assertNull(endTransactionSpanEventBo.getAnnotationBoList()); - } + // Check Parameter + final List deleteWith1ArgAnnotations = deleteWith1ArgSpanEvent.getAnnotationBoList(); + assertThat(deleteWith1ArgAnnotations.size(), is(1)); + final AnnotationBo deleteWith1ArgParameterAnnotation = deleteWith1ArgAnnotations.get(0); + assertThat(deleteWith1ArgParameterAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); + + final List deleteWith2ArgAnnotations = deleteWith2ArgSpanEvent.getAnnotationBoList(); + assertThat(deleteWith2ArgAnnotations.size(), is(1)); + final AnnotationBo deleteWith2ArgAnnotation = deleteWith2ArgAnnotations.get(0); + assertThat(deleteWith2ArgAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); + } + + @Test + public void updateShouldBeTraced() throws Exception { + // Given + SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); + // When + sqlMapClient.update("updateId"); + sqlMapClient.update("updateId", new Object()); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(2)); + + // Check Method + final SpanEventBo updateWith1ArgSpanEvent = spanEvents.get(0); + final SpanEventBo updateWith2ArgSpanEvent = spanEvents.get(1); + assertThat(updateWith1ArgSpanEvent.getApiId(), not(0)); + assertThat(updateWith2ArgSpanEvent.getApiId(), not(0)); + assertThat(updateWith1ArgSpanEvent.getApiId(), not(updateWith2ArgSpanEvent.getApiId())); + + // Check Parameter + final List updateWith1ArgAnnotations = updateWith1ArgSpanEvent.getAnnotationBoList(); + assertThat(updateWith1ArgAnnotations.size(), is(1)); + final AnnotationBo updateWith1ArgParameterAnnotation = updateWith1ArgAnnotations.get(0); + assertThat(updateWith1ArgParameterAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); + + final List updateWith2ArgAnnotations = updateWith2ArgSpanEvent.getAnnotationBoList(); + assertThat(updateWith2ArgAnnotations.size(), is(1)); + final AnnotationBo updateWith2ArgAnnotation = updateWith2ArgAnnotations.get(0); + assertThat(updateWith2ArgAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); + + } + + @Test + public void queryForListShouldBeTraced() throws Exception { + // Given + SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); + // When + sqlMapClient.queryForList("abc"); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(1)); + + // Check Method + final SpanEventBo apiCallSpanEventBo = spanEvents.get(0); + assertThat(apiCallSpanEventBo.getApiId(), not(0)); + + // Check Parameter + final List annotationBoList = apiCallSpanEventBo.getAnnotationBoList(); + assertThat(annotationBoList.size(), is(1)); + + final AnnotationBo parameterAnnotationBo = annotationBoList.get(0); + assertThat(parameterAnnotationBo.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); + } + + @Test + public void queryForObjectShouldBeTraced() throws Exception { + // Given + SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); + // When + sqlMapClient.queryForObject("abrgrgfdaghertah", new Object()); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(1)); + + // Check Method + final SpanEventBo apiCallSpanEventBo = spanEvents.get(0); + assertThat(apiCallSpanEventBo.getApiId(), not(0)); + + // Check Parameter + final List annotationBoList = apiCallSpanEventBo.getAnnotationBoList(); + assertThat(annotationBoList.size(), is(1)); + + final AnnotationBo parameterAnnotationBo = annotationBoList.get(0); + assertThat(parameterAnnotationBo.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); + } + + @Ignore // Changed to trace only query operations + @Test + public void transactionsShouldBeTraced() throws Exception { + // Given + SqlMapClient sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); + // When + sqlMapClient.startTransaction(); + sqlMapClient.commitTransaction(); + sqlMapClient.endTransaction(); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(3)); + + // Check Method + final SpanEventBo startTransactionSpanEventBo = spanEvents.get(0); + final SpanEventBo commitTransactionSpanEventBo = spanEvents.get(1); + final SpanEventBo endTransactionSpanEventBo = spanEvents.get(2); + + assertThat(startTransactionSpanEventBo.getApiId(), not(0)); + assertThat(commitTransactionSpanEventBo.getApiId(), not(0)); + assertThat(endTransactionSpanEventBo.getApiId(), not(0)); + + assertThat(startTransactionSpanEventBo.getApiId(), not(commitTransactionSpanEventBo.getApiId())); + assertThat(commitTransactionSpanEventBo.getApiId(), not(endTransactionSpanEventBo.getApiId())); + assertThat(endTransactionSpanEventBo.getApiId(), not(startTransactionSpanEventBo.getApiId())); + + // Check Parameter + assertNull(startTransactionSpanEventBo.getAnnotationBoList()); + assertNull(commitTransactionSpanEventBo.getAnnotationBoList()); + assertNull(endTransactionSpanEventBo.getAnnotationBoList()); + } } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/SqlMapSessionImplModifierTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/SqlMapSessionImplModifierTest.java index d80790abc..797b0ce5a 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/SqlMapSessionImplModifierTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/ibatis/SqlMapSessionImplModifierTest.java @@ -44,279 +44,279 @@ import com.navercorp.pinpoint.test.junit4.BasePinpointTest; */ public class SqlMapSessionImplModifierTest extends BasePinpointTest { - public class MockSqlMapExecutorDelegate extends SqlMapExecutorDelegate { - @Override - public SessionScope beginSessionScope() { - return mockSessionScope; - } - } - - private SqlMapClientImpl sqlMapClient; + public class MockSqlMapExecutorDelegate extends SqlMapExecutorDelegate { + @Override + public SessionScope beginSessionScope() { + return mockSessionScope; + } + } - @Mock - private MockSqlMapExecutorDelegate mockSqlMapExecutorDelegate; - @Mock - private SessionScope mockSessionScope; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - when(this.mockSqlMapExecutorDelegate.beginSessionScope()).thenReturn(this.mockSessionScope); - this.sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); - } - - @After - public void cleanUp() throws Exception { - this.sqlMapClient = null; - } - - @Test - public void exceptionsThrownShouldBeTraced() throws Exception { - // Given - final String exceptionInsertId = "insertShouldThrowNPE"; - when(this.mockSqlMapExecutorDelegate.insert(mockSessionScope, exceptionInsertId, null)).thenThrow(new NullPointerException()); - SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); - // When - try { - sqlMapSession.insert(exceptionInsertId); - fail("sqlMapSession.insert() should throw NullPointerException"); - } catch (NullPointerException e) { - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(1)); - final SpanEventBo exceptionSpanEventBo = spanEvents.get(0); - assertThat(exceptionSpanEventBo.hasException(), is(true)); - assertThat(exceptionSpanEventBo.getExceptionId(), not(0)); - } - } - - @Test - public void nullParametersShouldNotBeTraced() throws Exception { - // Given - SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); - // When - sqlMapSession.insert(null); - sqlMapSession.queryForList(null); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(2)); - - // Check Method - final SpanEventBo insertSpanEventBo = spanEvents.get(0); - final SpanEventBo queryForListSpanEventBo = spanEvents.get(1); - assertThat(insertSpanEventBo.getApiId(), not(0)); - assertThat(queryForListSpanEventBo.getApiId(), not(0)); - assertThat(insertSpanEventBo.getApiId(), not(queryForListSpanEventBo.getApiId())); - - // Check Parameter - assertNull(insertSpanEventBo.getAnnotationBoList()); - assertNull(queryForListSpanEventBo.getAnnotationBoList()); - } - - @Test - public void sameApiCallsShouldHaveTheSameApiId() throws Exception { - // Given - SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); - // When - sqlMapSession.insert("insertA"); - sqlMapSession.insert("insertB"); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(2)); - - // Check Method - final SpanEventBo insertASpanEventBo = spanEvents.get(0); - final SpanEventBo insertBSpanEventBo = spanEvents.get(1); - assertThat(insertASpanEventBo.getApiId(), not(0)); - assertThat(insertBSpanEventBo.getApiId(), not(0)); - assertThat(insertASpanEventBo.getApiId(), is(insertBSpanEventBo.getApiId())); - - } - - @Test - public void insertShouldBeTraced() throws Exception { - // Given - SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); - // When - sqlMapSession.insert("insertId"); - sqlMapSession.insert("insertId", new Object()); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(2)); + private SqlMapClientImpl sqlMapClient; - // Check Method - final SpanEventBo insertWith1ArgSpanEventBo = spanEvents.get(0); - final SpanEventBo insertWith2ArgSpanEventBo = spanEvents.get(1); - assertThat(insertWith1ArgSpanEventBo.getApiId(), not(0)); - assertThat(insertWith2ArgSpanEventBo.getApiId(), not(0)); - assertThat(insertWith1ArgSpanEventBo.getApiId(), not(insertWith2ArgSpanEventBo.getApiId())); + @Mock + private MockSqlMapExecutorDelegate mockSqlMapExecutorDelegate; + @Mock + private SessionScope mockSessionScope; - // Check Parameter - final List insertWith1ArgAnnotations = insertWith1ArgSpanEventBo.getAnnotationBoList(); - assertThat(insertWith1ArgAnnotations.size(), is(1)); - final AnnotationBo insertWith1ArgParameterAnnotation = insertWith1ArgAnnotations.get(0); - assertThat(insertWith1ArgParameterAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - - final List insertWith2ArgAnnotations = insertWith2ArgSpanEventBo.getAnnotationBoList(); - assertThat(insertWith2ArgAnnotations.size(), is(1)); - final AnnotationBo insertWith2ArgAnnotation = insertWith2ArgAnnotations.get(0); - assertThat(insertWith2ArgAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - - } - - @Test - public void deleteShouldBeTraced() throws Exception { - // Given - SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); - // When - sqlMapSession.delete("deleteId"); - sqlMapSession.delete("deleteId", new Object()); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(2)); + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + when(this.mockSqlMapExecutorDelegate.beginSessionScope()).thenReturn(this.mockSessionScope); + this.sqlMapClient = new SqlMapClientImpl(this.mockSqlMapExecutorDelegate); + } - // Check Method - final SpanEventBo deleteWith1ArgSpanEvent = spanEvents.get(0); - final SpanEventBo deleteWith2ArgSpanEvent = spanEvents.get(1); - assertThat(deleteWith1ArgSpanEvent.getApiId(), not(0)); - assertThat(deleteWith2ArgSpanEvent.getApiId(), not(0)); - assertThat(deleteWith1ArgSpanEvent.getApiId(), not(deleteWith2ArgSpanEvent.getApiId())); + @After + public void cleanUp() throws Exception { + this.sqlMapClient = null; + } - // Check Parameter - final List deleteWith1ArgAnnotations = deleteWith1ArgSpanEvent.getAnnotationBoList(); - assertThat(deleteWith1ArgAnnotations.size(), is(1)); - final AnnotationBo deleteWith1ArgParameterAnnotation = deleteWith1ArgAnnotations.get(0); - assertThat(deleteWith1ArgParameterAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - - final List deleteWith2ArgAnnotations = deleteWith2ArgSpanEvent.getAnnotationBoList(); - assertThat(deleteWith2ArgAnnotations.size(), is(1)); - final AnnotationBo deleteWith2ArgAnnotation = deleteWith2ArgAnnotations.get(0); - assertThat(deleteWith2ArgAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - } - - @Test - public void updateShouldBeTraced() throws Exception { - // Given - SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); - // When - sqlMapSession.update("updateId"); - sqlMapSession.update("updateId", new Object()); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(2)); + @Test + public void exceptionsThrownShouldBeTraced() throws Exception { + // Given + final String exceptionInsertId = "insertShouldThrowNPE"; + when(this.mockSqlMapExecutorDelegate.insert(mockSessionScope, exceptionInsertId, null)).thenThrow(new NullPointerException()); + SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); + // When + try { + sqlMapSession.insert(exceptionInsertId); + fail("sqlMapSession.insert() should throw NullPointerException"); + } catch (NullPointerException e) { + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(1)); + final SpanEventBo exceptionSpanEventBo = spanEvents.get(0); + assertThat(exceptionSpanEventBo.hasException(), is(true)); + assertThat(exceptionSpanEventBo.getExceptionId(), not(0)); + } + } - // Check Method - final SpanEventBo updateWith1ArgSpanEvent = spanEvents.get(0); - final SpanEventBo updateWith2ArgSpanEvent = spanEvents.get(1); - assertThat(updateWith1ArgSpanEvent.getApiId(), not(0)); - assertThat(updateWith2ArgSpanEvent.getApiId(), not(0)); - assertThat(updateWith1ArgSpanEvent.getApiId(), not(updateWith2ArgSpanEvent.getApiId())); + @Test + public void nullParametersShouldNotBeTraced() throws Exception { + // Given + SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); + // When + sqlMapSession.insert(null); + sqlMapSession.queryForList(null); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(2)); - // Check Parameter - final List updateWith1ArgAnnotations = updateWith1ArgSpanEvent.getAnnotationBoList(); - assertThat(updateWith1ArgAnnotations.size(), is(1)); - final AnnotationBo updateWith1ArgParameterAnnotation = updateWith1ArgAnnotations.get(0); - assertThat(updateWith1ArgParameterAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - - final List updateWith2ArgAnnotations = updateWith2ArgSpanEvent.getAnnotationBoList(); - assertThat(updateWith2ArgAnnotations.size(), is(1)); - final AnnotationBo updateWith2ArgAnnotation = updateWith2ArgAnnotations.get(0); - assertThat(updateWith2ArgAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - - } + // Check Method + final SpanEventBo insertSpanEventBo = spanEvents.get(0); + final SpanEventBo queryForListSpanEventBo = spanEvents.get(1); + assertThat(insertSpanEventBo.getApiId(), not(0)); + assertThat(queryForListSpanEventBo.getApiId(), not(0)); + assertThat(insertSpanEventBo.getApiId(), not(queryForListSpanEventBo.getApiId())); - @Test - public void queryForListShouldBeTraced() throws Exception { - // Given - SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); - // When - sqlMapSession.queryForList("abc"); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(1)); + // Check Parameter + assertNull(insertSpanEventBo.getAnnotationBoList()); + assertNull(queryForListSpanEventBo.getAnnotationBoList()); + } - // Check Method - final SpanEventBo apiCallSpanEventBo = spanEvents.get(0); - assertThat(apiCallSpanEventBo.getApiId(), not(0)); + @Test + public void sameApiCallsShouldHaveTheSameApiId() throws Exception { + // Given + SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); + // When + sqlMapSession.insert("insertA"); + sqlMapSession.insert("insertB"); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(2)); - // Check Parameter - final List annotationBoList = apiCallSpanEventBo.getAnnotationBoList(); - assertThat(annotationBoList.size(), is(1)); + // Check Method + final SpanEventBo insertASpanEventBo = spanEvents.get(0); + final SpanEventBo insertBSpanEventBo = spanEvents.get(1); + assertThat(insertASpanEventBo.getApiId(), not(0)); + assertThat(insertBSpanEventBo.getApiId(), not(0)); + assertThat(insertASpanEventBo.getApiId(), is(insertBSpanEventBo.getApiId())); - final AnnotationBo parameterAnnotationBo = annotationBoList.get(0); - assertThat(parameterAnnotationBo.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - } + } - @Test - public void queryForObjectShouldBeTraced() throws Exception { - // Given - SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); - // When - sqlMapSession.queryForObject("abrgrgfdaghertah", new Object()); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(1)); + @Test + public void insertShouldBeTraced() throws Exception { + // Given + SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); + // When + sqlMapSession.insert("insertId"); + sqlMapSession.insert("insertId", new Object()); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(2)); - // Check Method - final SpanEventBo apiCallSpanEventBo = spanEvents.get(0); - assertThat(apiCallSpanEventBo.getApiId(), not(0)); + // Check Method + final SpanEventBo insertWith1ArgSpanEventBo = spanEvents.get(0); + final SpanEventBo insertWith2ArgSpanEventBo = spanEvents.get(1); + assertThat(insertWith1ArgSpanEventBo.getApiId(), not(0)); + assertThat(insertWith2ArgSpanEventBo.getApiId(), not(0)); + assertThat(insertWith1ArgSpanEventBo.getApiId(), not(insertWith2ArgSpanEventBo.getApiId())); - // Check Parameter - final List annotationBoList = apiCallSpanEventBo.getAnnotationBoList(); - assertThat(annotationBoList.size(), is(1)); + // Check Parameter + final List insertWith1ArgAnnotations = insertWith1ArgSpanEventBo.getAnnotationBoList(); + assertThat(insertWith1ArgAnnotations.size(), is(1)); + final AnnotationBo insertWith1ArgParameterAnnotation = insertWith1ArgAnnotations.get(0); + assertThat(insertWith1ArgParameterAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - final AnnotationBo parameterAnnotationBo = annotationBoList.get(0); - assertThat(parameterAnnotationBo.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - } + final List insertWith2ArgAnnotations = insertWith2ArgSpanEventBo.getAnnotationBoList(); + assertThat(insertWith2ArgAnnotations.size(), is(1)); + final AnnotationBo insertWith2ArgAnnotation = insertWith2ArgAnnotations.get(0); + assertThat(insertWith2ArgAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - @Ignore // Changed to trace only query operations - @Test - public void transactionsShouldBeTraced() throws Exception { - // Given - SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); - // When - sqlMapSession.startTransaction(); - sqlMapSession.commitTransaction(); - sqlMapSession.endTransaction(); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(3)); - - // Check Method - final SpanEventBo startTransactionSpanEventBo = spanEvents.get(0); - final SpanEventBo commitTransactionSpanEventBo = spanEvents.get(1); - final SpanEventBo endTransactionSpanEventBo = spanEvents.get(2); - - assertThat(startTransactionSpanEventBo.getApiId(), not(0)); - assertThat(commitTransactionSpanEventBo.getApiId(), not(0)); - assertThat(endTransactionSpanEventBo.getApiId(), not(0)); - - assertThat(startTransactionSpanEventBo.getApiId(), not(commitTransactionSpanEventBo.getApiId())); - assertThat(commitTransactionSpanEventBo.getApiId(), not(endTransactionSpanEventBo.getApiId())); - assertThat(endTransactionSpanEventBo.getApiId(), not(startTransactionSpanEventBo.getApiId())); - - // Check Parameter - assertNull(startTransactionSpanEventBo.getAnnotationBoList()); - assertNull(commitTransactionSpanEventBo.getAnnotationBoList()); - assertNull(endTransactionSpanEventBo.getAnnotationBoList()); - } + } - @Ignore // Changed to trace only query operations - @Test - public void closeShouldBeTraced() throws Exception { - // Given - SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); - // When - sqlMapSession.close(); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(1)); - - // Check Method - final SpanEventBo closeSpanEventBo = spanEvents.get(0); - assertThat(closeSpanEventBo.getApiId(), not(0)); - - // Check Parameter - assertNull(closeSpanEventBo.getAnnotationBoList()); - } + @Test + public void deleteShouldBeTraced() throws Exception { + // Given + SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); + // When + sqlMapSession.delete("deleteId"); + sqlMapSession.delete("deleteId", new Object()); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(2)); + + // Check Method + final SpanEventBo deleteWith1ArgSpanEvent = spanEvents.get(0); + final SpanEventBo deleteWith2ArgSpanEvent = spanEvents.get(1); + assertThat(deleteWith1ArgSpanEvent.getApiId(), not(0)); + assertThat(deleteWith2ArgSpanEvent.getApiId(), not(0)); + assertThat(deleteWith1ArgSpanEvent.getApiId(), not(deleteWith2ArgSpanEvent.getApiId())); + + // Check Parameter + final List deleteWith1ArgAnnotations = deleteWith1ArgSpanEvent.getAnnotationBoList(); + assertThat(deleteWith1ArgAnnotations.size(), is(1)); + final AnnotationBo deleteWith1ArgParameterAnnotation = deleteWith1ArgAnnotations.get(0); + assertThat(deleteWith1ArgParameterAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); + + final List deleteWith2ArgAnnotations = deleteWith2ArgSpanEvent.getAnnotationBoList(); + assertThat(deleteWith2ArgAnnotations.size(), is(1)); + final AnnotationBo deleteWith2ArgAnnotation = deleteWith2ArgAnnotations.get(0); + assertThat(deleteWith2ArgAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); + } + + @Test + public void updateShouldBeTraced() throws Exception { + // Given + SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); + // When + sqlMapSession.update("updateId"); + sqlMapSession.update("updateId", new Object()); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(2)); + + // Check Method + final SpanEventBo updateWith1ArgSpanEvent = spanEvents.get(0); + final SpanEventBo updateWith2ArgSpanEvent = spanEvents.get(1); + assertThat(updateWith1ArgSpanEvent.getApiId(), not(0)); + assertThat(updateWith2ArgSpanEvent.getApiId(), not(0)); + assertThat(updateWith1ArgSpanEvent.getApiId(), not(updateWith2ArgSpanEvent.getApiId())); + + // Check Parameter + final List updateWith1ArgAnnotations = updateWith1ArgSpanEvent.getAnnotationBoList(); + assertThat(updateWith1ArgAnnotations.size(), is(1)); + final AnnotationBo updateWith1ArgParameterAnnotation = updateWith1ArgAnnotations.get(0); + assertThat(updateWith1ArgParameterAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); + + final List updateWith2ArgAnnotations = updateWith2ArgSpanEvent.getAnnotationBoList(); + assertThat(updateWith2ArgAnnotations.size(), is(1)); + final AnnotationBo updateWith2ArgAnnotation = updateWith2ArgAnnotations.get(0); + assertThat(updateWith2ArgAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); + + } + + @Test + public void queryForListShouldBeTraced() throws Exception { + // Given + SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); + // When + sqlMapSession.queryForList("abc"); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(1)); + + // Check Method + final SpanEventBo apiCallSpanEventBo = spanEvents.get(0); + assertThat(apiCallSpanEventBo.getApiId(), not(0)); + + // Check Parameter + final List annotationBoList = apiCallSpanEventBo.getAnnotationBoList(); + assertThat(annotationBoList.size(), is(1)); + + final AnnotationBo parameterAnnotationBo = annotationBoList.get(0); + assertThat(parameterAnnotationBo.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); + } + + @Test + public void queryForObjectShouldBeTraced() throws Exception { + // Given + SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); + // When + sqlMapSession.queryForObject("abrgrgfdaghertah", new Object()); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(1)); + + // Check Method + final SpanEventBo apiCallSpanEventBo = spanEvents.get(0); + assertThat(apiCallSpanEventBo.getApiId(), not(0)); + + // Check Parameter + final List annotationBoList = apiCallSpanEventBo.getAnnotationBoList(); + assertThat(annotationBoList.size(), is(1)); + + final AnnotationBo parameterAnnotationBo = annotationBoList.get(0); + assertThat(parameterAnnotationBo.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); + } + + @Ignore // Changed to trace only query operations + @Test + public void transactionsShouldBeTraced() throws Exception { + // Given + SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); + // When + sqlMapSession.startTransaction(); + sqlMapSession.commitTransaction(); + sqlMapSession.endTransaction(); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(3)); + + // Check Method + final SpanEventBo startTransactionSpanEventBo = spanEvents.get(0); + final SpanEventBo commitTransactionSpanEventBo = spanEvents.get(1); + final SpanEventBo endTransactionSpanEventBo = spanEvents.get(2); + + assertThat(startTransactionSpanEventBo.getApiId(), not(0)); + assertThat(commitTransactionSpanEventBo.getApiId(), not(0)); + assertThat(endTransactionSpanEventBo.getApiId(), not(0)); + + assertThat(startTransactionSpanEventBo.getApiId(), not(commitTransactionSpanEventBo.getApiId())); + assertThat(commitTransactionSpanEventBo.getApiId(), not(endTransactionSpanEventBo.getApiId())); + assertThat(endTransactionSpanEventBo.getApiId(), not(startTransactionSpanEventBo.getApiId())); + + // Check Parameter + assertNull(startTransactionSpanEventBo.getAnnotationBoList()); + assertNull(commitTransactionSpanEventBo.getAnnotationBoList()); + assertNull(endTransactionSpanEventBo.getAnnotationBoList()); + } + + @Ignore // Changed to trace only query operations + @Test + public void closeShouldBeTraced() throws Exception { + // Given + SqlMapSession sqlMapSession = new SqlMapSessionImpl(this.sqlMapClient); + // When + sqlMapSession.close(); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(1)); + + // Check Method + final SpanEventBo closeSpanEventBo = spanEvents.get(0); + assertThat(closeSpanEventBo.getApiId(), not(0)); + + // Check Parameter + assertNull(closeSpanEventBo.getAnnotationBoList()); + } } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/DefaultSqlSessionModifierTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/DefaultSqlSessionModifierTest.java index 816bf8127..ad547f2f0 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/DefaultSqlSessionModifierTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/DefaultSqlSessionModifierTest.java @@ -32,28 +32,28 @@ import org.mockito.Mock; */ public class DefaultSqlSessionModifierTest extends MyBatisClientModifierTest { - @Mock - private Configuration configuration; - @Mock - private Executor executor; - - @Override - protected SqlSession getSqlSession() { - return new DefaultSqlSession(this.configuration, this.executor); - } + @Mock + private Configuration configuration; + @Mock + private Executor executor; - @Override - @Test - public void selectMapShouldBeTraced() throws Exception { - ObjectFactory objectFactory = mock(ObjectFactory.class); - when(this.configuration.getObjectFactory()).thenReturn(objectFactory); - super.selectMapShouldBeTraced(); - } + @Override + protected SqlSession getSqlSession() { + return new DefaultSqlSession(this.configuration, this.executor); + } - @Override - @Test - public void getConnectionShouldBeTraced() throws Exception { - Transaction mockTransaction = mock(Transaction.class); - when(this.executor.getTransaction()).thenReturn(mockTransaction); - } + @Override + @Test + public void selectMapShouldBeTraced() throws Exception { + ObjectFactory objectFactory = mock(ObjectFactory.class); + when(this.configuration.getObjectFactory()).thenReturn(objectFactory); + super.selectMapShouldBeTraced(); + } + + @Override + @Test + public void getConnectionShouldBeTraced() throws Exception { + Transaction mockTransaction = mock(Transaction.class); + when(this.executor.getTransaction()).thenReturn(mockTransaction); + } } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/MyBatisClientModifierTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/MyBatisClientModifierTest.java index 6cdbd0e9c..9556a2507 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/MyBatisClientModifierTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/MyBatisClientModifierTest.java @@ -42,251 +42,251 @@ import com.navercorp.pinpoint.test.junit4.BasePinpointTest; */ public abstract class MyBatisClientModifierTest extends BasePinpointTest { - public static final int NOT_CACHED = 0; - - protected abstract SqlSession getSqlSession(); - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - } - - @After - public void cleanUp() throws Exception { - getSqlSession().close(); - } + public static final int NOT_CACHED = 0; - @Test - public void nullParameterShouldNotBeTraced() throws Exception { - // When - getSqlSession().insert(null); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(1)); - - // Check Method - final SpanEventBo insertSpanEventBo = spanEvents.get(0); - assertThat(insertSpanEventBo.getApiId(), not(NOT_CACHED)); - - // Check Parameter - assertNull(insertSpanEventBo.getAnnotationBoList()); - } + protected abstract SqlSession getSqlSession(); - @Test - public void selectOneShouldBeTraced() throws Exception { - // When - getSqlSession().selectOne("selectOne"); - getSqlSession().selectOne("selectOne", null); - // Then - assertNOperations(2); - } + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } - @Test - public void selectListShouldBeTraced() throws Exception { - // When - getSqlSession().selectList("selectList"); - getSqlSession().selectList("selectList", null); - getSqlSession().selectList("selectList", null, null); - // Then - assertNOperations(3); - } - - @Test - public void selectMapShouldBeTraced() throws Exception { - // Given - // When - getSqlSession().selectMap("selectMap", null); - getSqlSession().selectMap("selectMap", null, null); - getSqlSession().selectMap("selectMap", null, null, null); - // Then - assertNOperations(3); - } + @After + public void cleanUp() throws Exception { + getSqlSession().close(); + } - @Test - public void selectShouldBeTraced() throws Exception { - // When - getSqlSession().select("select", null); - getSqlSession().select("select", null, null); - getSqlSession().select("select", null, null, null); - // Then - assertNOperations(3); - } - - @Test - public void insertShouldBeTraced() throws Exception { - // When - getSqlSession().insert("insert"); - getSqlSession().insert("insert", new Object()); - // Then - assertNOperations(2); - } - - @Test - public void updateShouldBeTraced() throws Exception { - // When - getSqlSession().update("update"); - getSqlSession().update("update", new Object()); - // Then - assertNOperations(2); - } - - @Test - public void deleteShouldBeTraced() throws Exception { - // When - getSqlSession().delete("delete"); - getSqlSession().delete("delete", new Object()); - // Then - assertNOperations(2); - } + @Test + public void nullParameterShouldNotBeTraced() throws Exception { + // When + getSqlSession().insert(null); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(1)); - @Ignore // Changed to trace only query operations - @Test - public void commitShouldBeTraced() throws Exception { - // When - getSqlSession().commit(); - getSqlSession().commit(true); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(2)); - - // Check MethodInfo - final SpanEventBo commitWith0ArgSpanEvent = spanEvents.get(0); - final SpanEventBo commitWith1ArgSpanEvent = spanEvents.get(1); - assertThat(commitWith0ArgSpanEvent.getApiId(), not(NOT_CACHED)); - assertThat(commitWith1ArgSpanEvent.getApiId(), not(NOT_CACHED)); - assertThat(commitWith0ArgSpanEvent.getApiId(), not(commitWith1ArgSpanEvent.getApiId())); - - // Check Parameter - assertNull(commitWith0ArgSpanEvent.getAnnotationBoList()); - assertThat(commitWith1ArgSpanEvent.getAnnotationBoList().get(0).getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - } + // Check Method + final SpanEventBo insertSpanEventBo = spanEvents.get(0); + assertThat(insertSpanEventBo.getApiId(), not(NOT_CACHED)); - @Ignore // Changed to trace only query operations - @Test - public void rollbackShouldBeTraced() throws Exception { - // When - getSqlSession().rollback(); - getSqlSession().rollback(true); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(2)); - - // Check MethodInfo - final SpanEventBo rollbackWith0ArgSpanEvent = spanEvents.get(0); - final SpanEventBo rollbackWith1ArgSpanEvent = spanEvents.get(1); - assertThat(rollbackWith0ArgSpanEvent.getApiId(), not(NOT_CACHED)); - assertThat(rollbackWith1ArgSpanEvent.getApiId(), not(NOT_CACHED)); - assertThat(rollbackWith0ArgSpanEvent.getApiId(), not(rollbackWith1ArgSpanEvent.getApiId())); - - // Check Parameter - assertNull(rollbackWith0ArgSpanEvent.getAnnotationBoList()); - assertThat(rollbackWith1ArgSpanEvent.getAnnotationBoList().get(0).getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - } + // Check Parameter + assertNull(insertSpanEventBo.getAnnotationBoList()); + } - @Ignore // Changed to trace only query operations - @Test - public void flushStatementsShouldBeTraced() throws Exception { - // When - getSqlSession().flushStatements(); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(1)); - - // Check MethodInfo - final SpanEventBo flushStatementsSpanEvent = spanEvents.get(0); - assertThat(flushStatementsSpanEvent.getApiId(), not(NOT_CACHED)); + @Test + public void selectOneShouldBeTraced() throws Exception { + // When + getSqlSession().selectOne("selectOne"); + getSqlSession().selectOne("selectOne", null); + // Then + assertNOperations(2); + } - // Check Parameter - assertNull(flushStatementsSpanEvent.getAnnotationBoList()); - } + @Test + public void selectListShouldBeTraced() throws Exception { + // When + getSqlSession().selectList("selectList"); + getSqlSession().selectList("selectList", null); + getSqlSession().selectList("selectList", null, null); + // Then + assertNOperations(3); + } - @Ignore // Changed to trace only query operations - @Test - public void closeShouldBeTraced() throws Exception { - // When - getSqlSession().close(); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(1)); - - // Check MethodInfo - final SpanEventBo closeSpanEvent = spanEvents.get(0); - assertThat(closeSpanEvent.getApiId(), not(NOT_CACHED)); - - // Check Parameter - assertNull(closeSpanEvent.getAnnotationBoList()); - } + @Test + public void selectMapShouldBeTraced() throws Exception { + // Given + // When + getSqlSession().selectMap("selectMap", null); + getSqlSession().selectMap("selectMap", null, null); + getSqlSession().selectMap("selectMap", null, null, null); + // Then + assertNOperations(3); + } - @Ignore // Changed to trace only query operations - @Test - public void getConfigurationShouldBeTraced() throws Exception { - // When - getSqlSession().getConfiguration(); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(1)); - - // Check MethodInfo - final SpanEventBo getConfigurationSpanEvent = spanEvents.get(0); - assertThat(getConfigurationSpanEvent.getApiId(), not(NOT_CACHED)); - - // Check Parameter - assertNull(getConfigurationSpanEvent.getAnnotationBoList()); - } + @Test + public void selectShouldBeTraced() throws Exception { + // When + getSqlSession().select("select", null); + getSqlSession().select("select", null, null); + getSqlSession().select("select", null, null, null); + // Then + assertNOperations(3); + } - @Ignore // Changed to trace only query operations - @Test - public void getMapperShouldBeTraced() throws Exception { - // Given - class SomeBean {} - // When - getSqlSession().getMapper(SomeBean.class); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(1)); - - // Check MethodInfo - final SpanEventBo getConnectionSpanEvent = spanEvents.get(0); - assertThat(getConnectionSpanEvent.getApiId(), not(NOT_CACHED)); - - // Check Parameter - assertThat(getConnectionSpanEvent.getAnnotationBoList().get(0).getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - } + @Test + public void insertShouldBeTraced() throws Exception { + // When + getSqlSession().insert("insert"); + getSqlSession().insert("insert", new Object()); + // Then + assertNOperations(2); + } + + @Test + public void updateShouldBeTraced() throws Exception { + // When + getSqlSession().update("update"); + getSqlSession().update("update", new Object()); + // Then + assertNOperations(2); + } + + @Test + public void deleteShouldBeTraced() throws Exception { + // When + getSqlSession().delete("delete"); + getSqlSession().delete("delete", new Object()); + // Then + assertNOperations(2); + } + + @Ignore // Changed to trace only query operations + @Test + public void commitShouldBeTraced() throws Exception { + // When + getSqlSession().commit(); + getSqlSession().commit(true); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(2)); + + // Check MethodInfo + final SpanEventBo commitWith0ArgSpanEvent = spanEvents.get(0); + final SpanEventBo commitWith1ArgSpanEvent = spanEvents.get(1); + assertThat(commitWith0ArgSpanEvent.getApiId(), not(NOT_CACHED)); + assertThat(commitWith1ArgSpanEvent.getApiId(), not(NOT_CACHED)); + assertThat(commitWith0ArgSpanEvent.getApiId(), not(commitWith1ArgSpanEvent.getApiId())); + + // Check Parameter + assertNull(commitWith0ArgSpanEvent.getAnnotationBoList()); + assertThat(commitWith1ArgSpanEvent.getAnnotationBoList().get(0).getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); + } + + @Ignore // Changed to trace only query operations + @Test + public void rollbackShouldBeTraced() throws Exception { + // When + getSqlSession().rollback(); + getSqlSession().rollback(true); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(2)); + + // Check MethodInfo + final SpanEventBo rollbackWith0ArgSpanEvent = spanEvents.get(0); + final SpanEventBo rollbackWith1ArgSpanEvent = spanEvents.get(1); + assertThat(rollbackWith0ArgSpanEvent.getApiId(), not(NOT_CACHED)); + assertThat(rollbackWith1ArgSpanEvent.getApiId(), not(NOT_CACHED)); + assertThat(rollbackWith0ArgSpanEvent.getApiId(), not(rollbackWith1ArgSpanEvent.getApiId())); + + // Check Parameter + assertNull(rollbackWith0ArgSpanEvent.getAnnotationBoList()); + assertThat(rollbackWith1ArgSpanEvent.getAnnotationBoList().get(0).getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); + } + + @Ignore // Changed to trace only query operations + @Test + public void flushStatementsShouldBeTraced() throws Exception { + // When + getSqlSession().flushStatements(); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(1)); + + // Check MethodInfo + final SpanEventBo flushStatementsSpanEvent = spanEvents.get(0); + assertThat(flushStatementsSpanEvent.getApiId(), not(NOT_CACHED)); + + // Check Parameter + assertNull(flushStatementsSpanEvent.getAnnotationBoList()); + } + + @Ignore // Changed to trace only query operations + @Test + public void closeShouldBeTraced() throws Exception { + // When + getSqlSession().close(); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(1)); + + // Check MethodInfo + final SpanEventBo closeSpanEvent = spanEvents.get(0); + assertThat(closeSpanEvent.getApiId(), not(NOT_CACHED)); + + // Check Parameter + assertNull(closeSpanEvent.getAnnotationBoList()); + } + + @Ignore // Changed to trace only query operations + @Test + public void getConfigurationShouldBeTraced() throws Exception { + // When + getSqlSession().getConfiguration(); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(1)); + + // Check MethodInfo + final SpanEventBo getConfigurationSpanEvent = spanEvents.get(0); + assertThat(getConfigurationSpanEvent.getApiId(), not(NOT_CACHED)); + + // Check Parameter + assertNull(getConfigurationSpanEvent.getAnnotationBoList()); + } + + @Ignore // Changed to trace only query operations + @Test + public void getMapperShouldBeTraced() throws Exception { + // Given + class SomeBean {} + // When + getSqlSession().getMapper(SomeBean.class); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(1)); + + // Check MethodInfo + final SpanEventBo getConnectionSpanEvent = spanEvents.get(0); + assertThat(getConnectionSpanEvent.getApiId(), not(NOT_CACHED)); + + // Check Parameter + assertThat(getConnectionSpanEvent.getAnnotationBoList().get(0).getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); + } + + @Ignore // Changed to trace only query operations + @Test + public void getConnectionShouldBeTraced() throws Exception { + // When + getSqlSession().getConnection(); + // Then + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(1)); + + // Check MethodInfo + final SpanEventBo getConnectionSpanEvent = spanEvents.get(0); + assertThat(getConnectionSpanEvent.getApiId(), not(NOT_CACHED)); + + // Check Parameter + assertNull(getConnectionSpanEvent.getAnnotationBoList()); + } + + private void assertNOperations(int numOperations) { + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(numOperations)); + + final Set uniqueApiIds = new HashSet(); + for (int n = 0; n < numOperations; ++n) { + final SpanEventBo apiSpanEvent = spanEvents.get(n); + uniqueApiIds.add(apiSpanEvent.getApiId()); + // Check MethodInfo + assertThat(apiSpanEvent.getApiId(), not(NOT_CACHED)); + // Check Parameter + final List apiAnnotations = apiSpanEvent.getAnnotationBoList(); + assertThat(apiAnnotations.size(), is(1)); + final AnnotationBo apiParameterAnnotation = apiAnnotations.get(0); + assertThat(apiParameterAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); + } + assertThat(uniqueApiIds.size(), is(numOperations)); + } - @Ignore // Changed to trace only query operations - @Test - public void getConnectionShouldBeTraced() throws Exception { - // When - getSqlSession().getConnection(); - // Then - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(1)); - - // Check MethodInfo - final SpanEventBo getConnectionSpanEvent = spanEvents.get(0); - assertThat(getConnectionSpanEvent.getApiId(), not(NOT_CACHED)); - - // Check Parameter - assertNull(getConnectionSpanEvent.getAnnotationBoList()); - } - - private void assertNOperations(int numOperations) { - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(numOperations)); - - final Set uniqueApiIds = new HashSet(); - for (int n = 0; n < numOperations; ++n) { - final SpanEventBo apiSpanEvent = spanEvents.get(n); - uniqueApiIds.add(apiSpanEvent.getApiId()); - // Check MethodInfo - assertThat(apiSpanEvent.getApiId(), not(NOT_CACHED)); - // Check Parameter - final List apiAnnotations = apiSpanEvent.getAnnotationBoList(); - assertThat(apiAnnotations.size(), is(1)); - final AnnotationBo apiParameterAnnotation = apiAnnotations.get(0); - assertThat(apiParameterAnnotation.getKey(), is(AnnotationKey.CACHE_ARGS0.getCode())); - } - assertThat(uniqueApiIds.size(), is(numOperations)); - } - } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/SqlSessionTemplateModifierTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/SqlSessionTemplateModifierTest.java index 0acdbb8f5..a18014ec6 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/SqlSessionTemplateModifierTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/orm/mybatis/SqlSessionTemplateModifierTest.java @@ -45,95 +45,95 @@ import com.navercorp.pinpoint.common.bo.SpanEventBo; */ public class SqlSessionTemplateModifierTest extends MyBatisClientModifierTest { - private static final ExecutorType executorType = ExecutorType.SIMPLE; - - private SqlSessionTemplate sqlSessionTemplate; - - @Mock - private SqlSessionFactory sqlSessionFactory; - - @Mock - private SqlSession sqlSession; - - @Override - protected SqlSession getSqlSession() { - return this.sqlSessionTemplate; - } - - @Override - @Before - public void setUp() throws Exception { - super.setUp(); - setUpSqlSessionFactory(); - setUpSqlSession(); - this.sqlSessionTemplate = new SqlSessionTemplate(this.sqlSessionFactory, executorType); - } - - private void setUpSqlSessionFactory() throws Exception { - Configuration configuration = mock(Configuration.class); - TransactionFactory transactionFactory = mock(TransactionFactory.class); - DataSource dataSource = mock(DataSource.class); - Environment environment = new Environment("test", transactionFactory, dataSource); - when(this.sqlSessionFactory.getConfiguration()).thenReturn(configuration); - when(configuration.getEnvironment()).thenReturn(environment); - } - - private void setUpSqlSession() throws Exception { - when(this.sqlSessionFactory.openSession(executorType)).thenReturn(this.sqlSession); - } + private static final ExecutorType executorType = ExecutorType.SIMPLE; - @Override - @After - public void cleanUp() throws Exception { - // Should not manually close SqlSessionTemplate - } + private SqlSessionTemplate sqlSessionTemplate; - @Ignore // Changed to trace only query operations - @Override - @Test - public void commitShouldBeTraced() throws Exception { - try { - super.commitShouldBeTraced(); - fail("SqlSessionTemplate cannot manually call commit."); - } catch (UnsupportedOperationException e) { - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(1)); - final SpanEventBo commitSpanEventBo = spanEvents.get(0); - assertThat(commitSpanEventBo.hasException(), is(true)); - assertThat(commitSpanEventBo.getExceptionId(), not(NOT_CACHED)); - } - } + @Mock + private SqlSessionFactory sqlSessionFactory; + + @Mock + private SqlSession sqlSession; + + @Override + protected SqlSession getSqlSession() { + return this.sqlSessionTemplate; + } + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + setUpSqlSessionFactory(); + setUpSqlSession(); + this.sqlSessionTemplate = new SqlSessionTemplate(this.sqlSessionFactory, executorType); + } + + private void setUpSqlSessionFactory() throws Exception { + Configuration configuration = mock(Configuration.class); + TransactionFactory transactionFactory = mock(TransactionFactory.class); + DataSource dataSource = mock(DataSource.class); + Environment environment = new Environment("test", transactionFactory, dataSource); + when(this.sqlSessionFactory.getConfiguration()).thenReturn(configuration); + when(configuration.getEnvironment()).thenReturn(environment); + } + + private void setUpSqlSession() throws Exception { + when(this.sqlSessionFactory.openSession(executorType)).thenReturn(this.sqlSession); + } + + @Override + @After + public void cleanUp() throws Exception { + // Should not manually close SqlSessionTemplate + } + + @Ignore // Changed to trace only query operations + @Override + @Test + public void commitShouldBeTraced() throws Exception { + try { + super.commitShouldBeTraced(); + fail("SqlSessionTemplate cannot manually call commit."); + } catch (UnsupportedOperationException e) { + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(1)); + final SpanEventBo commitSpanEventBo = spanEvents.get(0); + assertThat(commitSpanEventBo.hasException(), is(true)); + assertThat(commitSpanEventBo.getExceptionId(), not(NOT_CACHED)); + } + } + + @Ignore // Changed to trace only query operations + @Override + @Test + public void rollbackShouldBeTraced() throws Exception { + try { + super.rollbackShouldBeTraced(); + fail("SqlSessionTemplate cannot manually call rollback."); + } catch (UnsupportedOperationException e) { + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(1)); + final SpanEventBo rollbackSpanEventBo = spanEvents.get(0); + assertThat(rollbackSpanEventBo.hasException(), is(true)); + assertThat(rollbackSpanEventBo.getExceptionId(), not(NOT_CACHED)); + } + } + + @Ignore // Changed to trace only query operations + @Override + @Test + public void closeShouldBeTraced() throws Exception { + try { + super.closeShouldBeTraced(); + } catch (UnsupportedOperationException e) { + final List spanEvents = getCurrentSpanEvents(); + assertThat(spanEvents.size(), is(1)); + final SpanEventBo closeSpanEventBo = spanEvents.get(0); + assertThat(closeSpanEventBo.hasException(), is(true)); + assertThat(closeSpanEventBo.getExceptionId(), not(NOT_CACHED)); + } + } - @Ignore // Changed to trace only query operations - @Override - @Test - public void rollbackShouldBeTraced() throws Exception { - try { - super.rollbackShouldBeTraced(); - fail("SqlSessionTemplate cannot manually call rollback."); - } catch (UnsupportedOperationException e) { - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(1)); - final SpanEventBo rollbackSpanEventBo = spanEvents.get(0); - assertThat(rollbackSpanEventBo.hasException(), is(true)); - assertThat(rollbackSpanEventBo.getExceptionId(), not(NOT_CACHED)); - } - } - @Ignore // Changed to trace only query operations - @Override - @Test - public void closeShouldBeTraced() throws Exception { - try { - super.closeShouldBeTraced(); - } catch (UnsupportedOperationException e) { - final List spanEvents = getCurrentSpanEvents(); - assertThat(spanEvents.size(), is(1)); - final SpanEventBo closeSpanEventBo = spanEvents.get(0); - assertThat(closeSpanEventBo.hasException(), is(true)); - assertThat(closeSpanEventBo.getExceptionId(), not(NOT_CACHED)); - } - } - - } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/tomcat/aspect/RequestFacadeAspectTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/tomcat/aspect/RequestFacadeAspectTest.java index f682c576c..31df29086 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/tomcat/aspect/RequestFacadeAspectTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/modifier/tomcat/aspect/RequestFacadeAspectTest.java @@ -30,63 +30,63 @@ import java.util.Hashtable; public class RequestFacadeAspectTest { - public static class RequestFacadeAspectMock extends RequestFacadeAspect { - @Override - String __getHeader(String name) { - return "header"; - } + public static class RequestFacadeAspectMock extends RequestFacadeAspect { + @Override + String __getHeader(String name) { + return "header"; + } - @Override - Enumeration __getHeaders(String name) { - Hashtable hashtable = new Hashtable(); - hashtable.put("a", "aa"); - hashtable.put("b", "bb"); - return hashtable.elements(); - } + @Override + Enumeration __getHeaders(String name) { + Hashtable hashtable = new Hashtable(); + hashtable.put("a", "aa"); + hashtable.put("b", "bb"); + return hashtable.elements(); + } - @Override - Enumeration __getHeaderNames() { - Hashtable hashtable = new Hashtable (); - hashtable.put("b", "bb"); - hashtable.put("c", "cc"); - hashtable.put("d", Header.HTTP_SPAN_ID.toString()); - return hashtable.elements(); - } - } + @Override + Enumeration __getHeaderNames() { + Hashtable hashtable = new Hashtable (); + hashtable.put("b", "bb"); + hashtable.put("c", "cc"); + hashtable.put("d", Header.HTTP_SPAN_ID.toString()); + return hashtable.elements(); + } + } - @Test - public void getHeader() { - RequestFacadeAspect mock = new RequestFacadeAspectMock(); + @Test + public void getHeader() { + RequestFacadeAspect mock = new RequestFacadeAspectMock(); - String isNull = mock.getHeader(Header.HTTP_SPAN_ID.toString()); - Assert.assertNull(isNull); + String isNull = mock.getHeader(Header.HTTP_SPAN_ID.toString()); + Assert.assertNull(isNull); - String header = mock.getHeader("test"); - Assert.assertEquals(header, "header"); - } + String header = mock.getHeader("test"); + Assert.assertEquals(header, "header"); + } - @Test - public void getHeaders() { - RequestFacadeAspect mock = new RequestFacadeAspectMock(); - Enumeration isNull = mock.getHeaders(Header.HTTP_SPAN_ID.toString()); + @Test + public void getHeaders() { + RequestFacadeAspect mock = new RequestFacadeAspectMock(); + Enumeration isNull = mock.getHeaders(Header.HTTP_SPAN_ID.toString()); - ArrayList list = Collections.list(isNull); - Assert.assertEquals(list.size(), 0); + ArrayList list = Collections.list(isNull); + Assert.assertEquals(list.size(), 0); - Enumeration header = mock.getHeaders("test"); - Assert.assertEquals(Collections.list(header).size(), 2); - } + Enumeration header = mock.getHeaders("test"); + Assert.assertEquals(Collections.list(header).size(), 2); + } - @Test - public void getHeaderNames() { - RequestFacadeAspect mock = new RequestFacadeAspectMock(); - Enumeration isNull = mock.getHeaderNames(); + @Test + public void getHeaderNames() { + RequestFacadeAspect mock = new RequestFacadeAspectMock(); + Enumeration isNull = mock.getHeaderNames(); - ArrayList list = Collections.list(isNull); - Assert.assertEquals(list.size(), 2); - } + ArrayList list = Collections.list(isNull); + Assert.assertEquals(list.size(), 2); + } } \ No newline at end of file diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricMonitorRegistryTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricMonitorRegistryTest.java index 54a4a9ce7..fff888e05 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricMonitorRegistryTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/codahale/MetricMonitorRegistryTest.java @@ -46,105 +46,105 @@ public class MetricMonitorRegistryTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); - MetricMonitorRegistry registry = new MetricMonitorRegistry(); + MetricMonitorRegistry registry = new MetricMonitorRegistry(); - @Test - public void counter() { - CounterMonitor counter = registry.newCounterMonitor(new MonitorName("test.counter")); + @Test + public void counter() { + CounterMonitor counter = registry.newCounterMonitor(new MonitorName("test.counter")); - assertEquals(0, counter.getCount()); - counter.incr(); - assertEquals(1, counter.getCount()); - counter.incr(10); - assertEquals(11, counter.getCount()); - counter.decr(); - assertEquals(10, counter.getCount()); - counter.decr(10); - assertEquals(0, counter.getCount()); - } + assertEquals(0, counter.getCount()); + counter.incr(); + assertEquals(1, counter.getCount()); + counter.incr(10); + assertEquals(11, counter.getCount()); + counter.decr(); + assertEquals(10, counter.getCount()); + counter.decr(10); + assertEquals(0, counter.getCount()); + } - @Test - public void eventRate() { - EventRateMonitor eventRate = registry - .newEventRateMonitor(new MonitorName("test.eventrate")); + @Test + public void eventRate() { + EventRateMonitor eventRate = registry + .newEventRateMonitor(new MonitorName("test.eventrate")); - assertEquals(0, eventRate.getCount()); - eventRate.event(); - assertEquals(1, eventRate.getCount()); - eventRate.events(100); - assertEquals(101, eventRate.getCount()); - } + assertEquals(0, eventRate.getCount()); + eventRate.event(); + assertEquals(1, eventRate.getCount()); + eventRate.events(100); + assertEquals(101, eventRate.getCount()); + } - @Test - public void histogram() { - HistogramMonitor histogram = registry - .newHistogramMonitor(new MonitorName("test.histogram")); + @Test + public void histogram() { + HistogramMonitor histogram = registry + .newHistogramMonitor(new MonitorName("test.histogram")); - histogram.update(1); - histogram.update(10); - histogram.update(100); - assertEquals(3, histogram.getCount()); + histogram.update(1); + histogram.update(10); + histogram.update(100); + assertEquals(3, histogram.getCount()); - Histogram h = ((MetricHistogramMonitor) histogram).getDelegate(); - Snapshot snapshot = h.getSnapshot(); - assertEquals(100, snapshot.getMax()); - assertEquals(1, snapshot.getMin()); - assertTrue(10.0 == snapshot.getMedian()); - } + Histogram h = ((MetricHistogramMonitor) histogram).getDelegate(); + Snapshot snapshot = h.getSnapshot(); + assertEquals(100, snapshot.getMax()); + assertEquals(1, snapshot.getMin()); + assertTrue(10.0 == snapshot.getMedian()); + } - @Test - public void jvm() { - registry.registerJvmMemoryMonitor(new MonitorName("jvm.memory")); - registry.registerJvmGcMonitor(new MonitorName("jvm.gc")); - registry.registerJvmAttributeMonitor(new MonitorName("jvm.vm")); - registry.registerJvmThreadStatesMonitor(new MonitorName("jvm.thread")); + @Test + public void jvm() { + registry.registerJvmMemoryMonitor(new MonitorName("jvm.memory")); + registry.registerJvmGcMonitor(new MonitorName("jvm.gc")); + registry.registerJvmAttributeMonitor(new MonitorName("jvm.vm")); + registry.registerJvmThreadStatesMonitor(new MonitorName("jvm.thread")); - boolean hasMemory = false; - boolean hasGc = false; - boolean hasVm = false; - boolean hasThread = false; - - for (String each : registry.getRegistry().getNames()) { - if (each.startsWith("jvm.gc")) { - hasGc = true; - } else if (each.startsWith("jvm.memory")) { - hasMemory = true; - } else if (each.startsWith("jvm.vm")) { - hasVm = true; - } else if (each.startsWith("jvm.thread")) { - hasThread = true; - } - } - - assertTrue(hasMemory); - assertTrue(hasGc); - assertTrue(hasVm); - assertTrue(hasThread); - } + boolean hasMemory = false; + boolean hasGc = false; + boolean hasVm = false; + boolean hasThread = false; - String toMetricName(String name) { - return name.toLowerCase().replace("non_", "non-").replace("_", "."); - } - - @Test - public void mapper() { - TAgentStat agentStat = new TAgentStat(); - - MetricRegistry r = registry.getRegistry(); - Map map = r.getGauges(); -// for (Entry each : map.entrySet()) { -// logger.debug(each.getKey() + " : " + each.getValue().getValue().getClass()); -// } -// - for (Entry<_Fields, FieldMetaData> each : TAgentStat.metaDataMap.entrySet()) { - logger.debug(toMetricName(each.getKey().name())); - Gauge value = map.get(toMetricName(each.getKey().name())); - if (value != null) { - agentStat.setFieldValue(each.getKey(), value.getValue()); - } - } + for (String each : registry.getRegistry().getNames()) { + if (each.startsWith("jvm.gc")) { + hasGc = true; + } else if (each.startsWith("jvm.memory")) { + hasMemory = true; + } else if (each.startsWith("jvm.vm")) { + hasVm = true; + } else if (each.startsWith("jvm.thread")) { + hasThread = true; + } + } + + assertTrue(hasMemory); + assertTrue(hasGc); + assertTrue(hasVm); + assertTrue(hasThread); + } + + String toMetricName(String name) { + return name.toLowerCase().replace("non_", "non-").replace("_", "."); + } + + @Test + public void mapper() { + TAgentStat agentStat = new TAgentStat(); + + MetricRegistry r = registry.getRegistry(); + Map map = r.getGauges(); +// for (Entry each : map.entrySet()) { +// logger.debug(each.getKey() + " : " + each.getValue().getValue().getClass()); +// } +// + for (Entry<_Fields, FieldMetaData> each : TAgentStat.metaDataMap.entrySet()) { + logger.debug(toMetricName(each.getKey().name())); + Gauge value = map.get(toMetricName(each.getKey().name())); + if (value != null) { + agentStat.setFieldValue(each.getKey(), value.getValue()); + } + } logger.debug("{}", agentStat); - } - + } + } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/codahale/gc/GarbageCollectorFactoryTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/codahale/gc/GarbageCollectorFactoryTest.java index 0a3198f0b..802c08933 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/codahale/gc/GarbageCollectorFactoryTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/codahale/gc/GarbageCollectorFactoryTest.java @@ -28,8 +28,8 @@ public class GarbageCollectorFactoryTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Test - public void test() { + @Test + public void test() { GarbageCollector collector = new AgentStatCollectorFactory().getGarbageCollector(); logger.debug("collector.getType():{}", collector); diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/TcpDataSenderReconnectTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/TcpDataSenderReconnectTest.java index 6ea6433e0..c8d27e52c 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/TcpDataSenderReconnectTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/TcpDataSenderReconnectTest.java @@ -63,10 +63,10 @@ public class TcpDataSenderReconnectTest { logger.info("handleRequest:{}", requestPacket); } - @Override - public HandshakeResponseCode handleHandshake(Map properties) { - return HandshakeResponseType.Success.DUPLEX_COMMUNICATION; - } + @Override + public HandshakeResponseCode handleHandshake(Map properties) { + return HandshakeResponseType.Success.DUPLEX_COMMUNICATION; + } }); server.bind(HOST, PORT); return server; @@ -102,28 +102,28 @@ public class TcpDataSenderReconnectTest { } private PinpointSocketFactory createPinpointSocketFactory() { - PinpointSocketFactory pinpointSocketFactory = new PinpointSocketFactory(); + PinpointSocketFactory pinpointSocketFactory = new PinpointSocketFactory(); pinpointSocketFactory.setTimeoutMillis(1000 * 5); pinpointSocketFactory.setProperties(Collections.EMPTY_MAP); return pinpointSocketFactory; - } + } private PinpointSocket createPinpointSocket(String host, int port, PinpointSocketFactory factory) { - PinpointSocket socket = null; - for (int i = 0; i < 3; i++) { + PinpointSocket socket = null; + for (int i = 0; i < 3; i++) { try { socket = factory.connect(host, port); logger.info("tcp connect success:{}/{}", host, port); return socket; } catch (PinpointSocketException e) { - logger.warn("tcp connect fail:{}/{} try reconnect, retryCount:{}", host, port, i); + logger.warn("tcp connect fail:{}/{} try reconnect, retryCount:{}", host, port, i); } } - logger.warn("change background tcp connect mode {}/{} ", host, port); + logger.warn("change background tcp connect mode {}/{} ", host, port); socket = factory.scheduledConnect(host, port); - + return socket; } } diff --git a/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/TcpDataSenderTest.java b/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/TcpDataSenderTest.java index b00f64a47..3a188d69f 100644 --- a/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/TcpDataSenderTest.java +++ b/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/TcpDataSenderTest.java @@ -108,37 +108,37 @@ public class TcpDataSenderTest { sender.stop(); if (socket != null) { - socket.close(); + socket.close(); } if (socketFactory != null) { - socketFactory.release(); + socketFactory.release(); } } } private PinpointSocketFactory createPinpointSocketFactory() { - PinpointSocketFactory pinpointSocketFactory = new PinpointSocketFactory(); + PinpointSocketFactory pinpointSocketFactory = new PinpointSocketFactory(); pinpointSocketFactory.setTimeoutMillis(1000 * 5); pinpointSocketFactory.setProperties(Collections.EMPTY_MAP); return pinpointSocketFactory; - } + } private PinpointSocket createPinpointSocket(String host, int port, PinpointSocketFactory factory) { - PinpointSocket socket = null; - for (int i = 0; i < 3; i++) { + PinpointSocket socket = null; + for (int i = 0; i < 3; i++) { try { socket = factory.connect(host, port); logger.info("tcp connect success:{}/{}", host, port); return socket; } catch (PinpointSocketException e) { - logger.warn("tcp connect fail:{}/{} try reconnect, retryCount:{}", host, port, i); + logger.warn("tcp connect fail:{}/{} try reconnect, retryCount:{}", host, port, i); } } - logger.warn("change background tcp connect mode {}/{} ", host, port); + logger.warn("change background tcp connect mode {}/{} ", host, port); socket = factory.scheduledConnect(host, port); - + return socket; } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/DefaultFuture.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/DefaultFuture.java index a2859d6ef..d30286f21 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/DefaultFuture.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/DefaultFuture.java @@ -202,28 +202,28 @@ public class DefaultFuture implements TimerTask, Future { } boolean interrupted = false; - try { - synchronized (this) { - if (ready) { - return true; - } + try { + synchronized (this) { + if (ready) { + return true; + } - try { - this.waiters++; - wait(timeoutMillis); - } catch (InterruptedException e) { - interrupted = true; - } finally { - this.waiters--; - } + try { + this.waiters++; + wait(timeoutMillis); + } catch (InterruptedException e) { + interrupted = true; + } finally { + this.waiters--; + } - return ready; - } - } finally { - if (interrupted) { - Thread.currentThread().interrupt(); - } - } + return ready; + } + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/RequestResponseServerMessageListener.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/RequestResponseServerMessageListener.java index c8a6ad3c7..30d77d474 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/RequestResponseServerMessageListener.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/RequestResponseServerMessageListener.java @@ -49,10 +49,10 @@ public class RequestResponseServerMessageListener implements ServerMessageListen channel.sendResponseMessage(requestPacket, requestPacket.getPayload()); } - @Override - public HandshakeResponseCode handleHandshake(Map properties) { + @Override + public HandshakeResponseCode handleHandshake(Map properties) { logger.info("handle handShake {}", properties); return HandshakeResponseType.Success.DUPLEX_COMMUNICATION; - } + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/DummyPinpointSocketReconnectEventListener.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/DummyPinpointSocketReconnectEventListener.java index 0b40fa3f6..948ce1271 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/DummyPinpointSocketReconnectEventListener.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/DummyPinpointSocketReconnectEventListener.java @@ -18,9 +18,9 @@ package com.navercorp.pinpoint.rpc.client; public class DummyPinpointSocketReconnectEventListener implements PinpointSocketReconnectEventListener { - @Override - public void reconnectPerformed(PinpointSocket socket) { - - } + @Override + public void reconnectPerformed(PinpointSocket socket) { + + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/MessageListener.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/MessageListener.java index fc7e5759c..5b353af5c 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/MessageListener.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/MessageListener.java @@ -26,8 +26,8 @@ import com.navercorp.pinpoint.rpc.packet.SendPacket; */ public interface MessageListener { - void handleSend(SendPacket sendPacket, Channel channel); + void handleSend(SendPacket sendPacket, Channel channel); - void handleRequest(RequestPacket requestPacket, Channel channel); + void handleRequest(RequestPacket requestPacket, Channel channel); } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocket.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocket.java index 37c37d8ef..7c74b9c2c 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocket.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocket.java @@ -48,13 +48,13 @@ public class PinpointSocket { private List reconnectEventListeners = new CopyOnWriteArrayList(); public PinpointSocket() { - this(new ReconnectStateSocketHandler()); + this(new ReconnectStateSocketHandler()); } public PinpointSocket(SocketHandler socketHandler) { AssertUtils.assertNotNull(socketHandler, "socketHandler"); - socketHandler.doHandshake(); - + socketHandler.doHandshake(); + this.socketHandler = socketHandler; socketHandler.setPinpointSocket(this); } @@ -83,26 +83,26 @@ public class PinpointSocket { guarantee it is not null. */ public boolean addPinpointSocketReconnectEventListener(PinpointSocketReconnectEventListener eventListener) { - if (eventListener == null) { - return false; - } - - return this.reconnectEventListeners.add(eventListener); + if (eventListener == null) { + return false; + } + + return this.reconnectEventListeners.add(eventListener); } public boolean removePinpointSocketReconnectEventListener(PinpointSocketReconnectEventListener eventListener) { - if (eventListener == null) { - return false; - } + if (eventListener == null) { + return false; + } - return this.reconnectEventListeners.remove(eventListener); + return this.reconnectEventListeners.remove(eventListener); } private void notifyReconnectEvent() { - for (PinpointSocketReconnectEventListener eachListener : this.reconnectEventListeners) { - eachListener.reconnectPerformed(this); - } - } + for (PinpointSocketReconnectEventListener eachListener : this.reconnectEventListeners) { + eachListener.reconnectPerformed(this); + } + } public void sendSync(byte[] bytes) { ensureOpen(); @@ -136,8 +136,8 @@ public class PinpointSocket { public StreamChannelContext findStreamChannel(int streamChannelId) { - ensureOpen(); - return socketHandler.findStreamChannel(streamChannelId); + ensureOpen(); + return socketHandler.findStreamChannel(streamChannelId); } private Future returnFailureFuture() { @@ -183,7 +183,7 @@ public class PinpointSocket { return closed; } - public boolean isConnected() { - return this.socketHandler.isConnected(); - } + public boolean isConnected() { + return this.socketHandler.isConnected(); + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocketFactory.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocketFactory.java index 03fcffc43..7aa5a681c 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocketFactory.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocketFactory.java @@ -61,9 +61,9 @@ public class PinpointSocketFactory { public static final String CONNECT_TIMEOUT_MILLIS = "connectTimeoutMillis"; private static final int DEFAULT_CONNECT_TIMEOUT = 5000; - private static final long DEFAULT_TIMEOUTMILLIS = 3 * 1000; + private static final long DEFAULT_TIMEOUTMILLIS = 3 * 1000; private static final long DEFAULT_PING_DELAY = 60 * 1000 * 5; - private static final long DEFAULT_ENABLE_WORKER_PACKET_DELAY = 60 * 1000 * 1; + private static final long DEFAULT_ENABLE_WORKER_PACKET_DELAY = 60 * 1000 * 1; private volatile boolean released; @@ -164,16 +164,16 @@ public class PinpointSocketFactory { this.pingDelay = pingDelay; } - public long getEnableWorkerPacketDelay() { - return enableWorkerPacketDelay; - } + public long getEnableWorkerPacketDelay() { + return enableWorkerPacketDelay; + } - public void setEnableWorkerPacketDelay(long enableWorkerPacketDelay) { + public void setEnableWorkerPacketDelay(long enableWorkerPacketDelay) { if (enableWorkerPacketDelay < 0) { throw new IllegalArgumentException("EnableWorkerPacketDelay cannot be a negative number"); } - this.enableWorkerPacketDelay = enableWorkerPacketDelay; - } + this.enableWorkerPacketDelay = enableWorkerPacketDelay; + } public long getTimeoutMillis() { return timeoutMillis; @@ -213,7 +213,7 @@ public class PinpointSocketFactory { } public PinpointSocket reconnect(String host, int port) throws PinpointSocketException { - SocketAddress address = new InetSocketAddress(host, port); + SocketAddress address = new InetSocketAddress(host, port); ChannelFuture connectFuture = bootstrap.connect(address); SocketHandler socketHandler = getSocketHandler(connectFuture, address); @@ -385,34 +385,34 @@ public class PinpointSocketFactory { // stop, cancel something? } - Map getProperties() { - return properties; - } + Map getProperties() { + return properties; + } - public void setProperties(Map agentProperties) { - AssertUtils.assertNotNull(properties, "agentProperties must not be null"); + public void setProperties(Map agentProperties) { + AssertUtils.assertNotNull(properties, "agentProperties must not be null"); - this.properties = Collections.unmodifiableMap(agentProperties); - } + this.properties = Collections.unmodifiableMap(agentProperties); + } - public MessageListener getMessageListener() { - return messageListener; - } + public MessageListener getMessageListener() { + return messageListener; + } - public void setMessageListener(MessageListener messageListener) { - AssertUtils.assertNotNull(messageListener, "messageListener must not be null"); - - this.messageListener = messageListener; - } + public void setMessageListener(MessageListener messageListener) { + AssertUtils.assertNotNull(messageListener, "messageListener must not be null"); - public ServerStreamChannelMessageListener getServerStreamChannelMessageListener() { - return serverStreamChannelMessageListener; - } + this.messageListener = messageListener; + } - public void setServerStreamChannelMessageListener(ServerStreamChannelMessageListener serverStreamChannelMessageListener) { - AssertUtils.assertNotNull(messageListener, "messageListener must not be null"); + public ServerStreamChannelMessageListener getServerStreamChannelMessageListener() { + return serverStreamChannelMessageListener; + } - this.serverStreamChannelMessageListener = serverStreamChannelMessageListener; - } + public void setServerStreamChannelMessageListener(ServerStreamChannelMessageListener serverStreamChannelMessageListener) { + AssertUtils.assertNotNull(messageListener, "messageListener must not be null"); + + this.serverStreamChannelMessageListener = serverStreamChannelMessageListener; + } } 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 a1ded1207..7b718319b 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 @@ -106,7 +106,7 @@ public class PinpointSocketHandler extends SimpleChannelHandler implements Socke private final ChannelFutureListener handShakeFailFutureListener = new WriteFailFutureListener(this.logger, "HandShakePacket write fail.", "HandShakePacket write success."); public PinpointSocketHandler(PinpointSocketFactory pinpointSocketFactory) { - this(pinpointSocketFactory, DEFAULT_PING_DELAY, DEFAULT_ENABLE_WORKER_PACKET_DELAY, DEFAULT_TIMEOUTMILLIS); + this(pinpointSocketFactory, DEFAULT_PING_DELAY, DEFAULT_ENABLE_WORKER_PACKET_DELAY, DEFAULT_TIMEOUTMILLIS); } public PinpointSocketHandler(PinpointSocketFactory pinpointSocketFactory, long pingDelay, long enableWorkerPacketDelay, long timeoutMillis) { @@ -462,8 +462,8 @@ public class PinpointSocketHandler extends SimpleChannelHandler implements Socke case PacketType.APPLICATION_STREAM_RESPONSE: case PacketType.APPLICATION_STREAM_PING: case PacketType.APPLICATION_STREAM_PONG: - SocketHandlerContext context = getChannelContext(channel); - context.getStreamChannelManager().messageReceived((StreamPacket) message); + SocketHandlerContext context = getChannelContext(channel); + context.getStreamChannelManager().messageReceived((StreamPacket) message); return; case PacketType.CONTROL_SERVER_CLOSE: messageReceivedServerClosed(e.getChannel()); diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocketReconnectEventListener.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocketReconnectEventListener.java index fc0d196cc..62835e8cf 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocketReconnectEventListener.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/PinpointSocketReconnectEventListener.java @@ -18,10 +18,10 @@ package com.navercorp.pinpoint.rpc.client; public interface PinpointSocketReconnectEventListener { - /* - there is no event except "reconnect" currently. - when additional events are needed, it will be useful to pass with Event - */ - void reconnectPerformed(PinpointSocket socket); - + /* + there is no event except "reconnect" currently. + when additional events are needed, it will be useful to pass with Event + */ + void reconnectPerformed(PinpointSocket socket); + } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/ReconnectStateSocketHandler.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/ReconnectStateSocketHandler.java index b0b927340..7bf480c66 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/ReconnectStateSocketHandler.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/ReconnectStateSocketHandler.java @@ -86,31 +86,31 @@ public class ReconnectStateSocketHandler implements SocketHandler { @Override public ClientStreamChannelContext createStreamChannel(byte[] payload, ClientStreamChannelMessageListener clientStreamChannelMessageListener) { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException(); } @Override public StreamChannelContext findStreamChannel(int streamChannelId) { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException(); } @Override public void sendPing() { } - @Override - public boolean isConnected() { - return false; - } - - @Override - public boolean isSupportServerMode() { - return false; - } - - @Override - public void doHandshake() { + @Override + public boolean isConnected() { + return false; + } + + @Override + public boolean isSupportServerMode() { + return false; + } + + @Override + public void doHandshake() { // throw new UnsupportedOperationException(); - } - + } + } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/SimpleLoggingMessageListener.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/SimpleLoggingMessageListener.java index c60f3c6cc..12713c453 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/SimpleLoggingMessageListener.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/SimpleLoggingMessageListener.java @@ -26,19 +26,19 @@ import com.navercorp.pinpoint.rpc.packet.SendPacket; public class SimpleLoggingMessageListener implements MessageListener { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); public static final SimpleLoggingMessageListener LISTENER = new SimpleLoggingMessageListener(); - @Override - public void handleSend(SendPacket sendPacket, Channel channel) { + @Override + public void handleSend(SendPacket sendPacket, Channel channel) { logger.info("handlerSend {} {}", sendPacket, channel); - } + } - @Override - public void handleRequest(RequestPacket requestPacket, Channel channel) { - channel.write(new ResponsePacket(requestPacket.getRequestId(), new byte[0])); + @Override + public void handleRequest(RequestPacket requestPacket, Channel channel) { + channel.write(new ResponsePacket(requestPacket.getRequestId(), new byte[0])); logger.info("handlerRequest {} {}", requestPacket, channel); - } + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/SocketHandler.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/SocketHandler.java index a49cc7aa9..2a9bd8958 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/SocketHandler.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/SocketHandler.java @@ -56,8 +56,8 @@ public interface SocketHandler { boolean isConnected(); - boolean isSupportServerMode(); - - void doHandshake(); - + boolean isSupportServerMode(); + + void doHandshake(); + } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/State.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/State.java index f7797f1d2..8739b70b2 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/State.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/client/State.java @@ -26,11 +26,11 @@ import org.slf4j.LoggerFactory; * @author koo.taejin */ public class State { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); // operations on profiler should be light as much possible - + // 0 : no handshake, 1: running public static final int INIT_RECONNECT = -1; public static final int INIT = 0; @@ -49,8 +49,8 @@ public class State { } public boolean isRun() { - int code = state.get(); - return isRun(code); + int code = state.get(); + return isRun(code); } public boolean isRun(int code) { @@ -62,7 +62,7 @@ public class State { } public boolean changeRun() { - logger.debug("State Will Be Changed {}.", getString(RUN)); + logger.debug("State Will Be Changed {}.", getString(RUN)); final int current = state.get(); if (current == INIT) { return this.state.compareAndSet(INIT, RUN); @@ -73,16 +73,16 @@ public class State { } public boolean changeRunDuplexCommunication() { - logger.debug("State Will Be Changed {}.", getString(RUN_DUPLEX_COMMUNICATION)); + logger.debug("State Will Be Changed {}.", getString(RUN_DUPLEX_COMMUNICATION)); final int current = state.get(); if (current == INIT) { return this.state.compareAndSet(INIT, RUN_DUPLEX_COMMUNICATION); } else if(current == INIT_RECONNECT) { return this.state.compareAndSet(INIT_RECONNECT, RUN_DUPLEX_COMMUNICATION); } else if (current == RUN) { - return this.state.compareAndSet(RUN, RUN_DUPLEX_COMMUNICATION); + return this.state.compareAndSet(RUN, RUN_DUPLEX_COMMUNICATION); } else if (current == RUN_DUPLEX_COMMUNICATION) { - return true; + return true; } throw new IllegalStateException("InvalidState current:" + getString(current) + " change:" + getString(RUN_DUPLEX_COMMUNICATION)); } @@ -104,13 +104,13 @@ public class State { } public boolean changeClosed(int before) { - logger.debug("State Will Be Changed {} -> {}.", getString(before), getString(CLOSED)); + logger.debug("State Will Be Changed {} -> {}.", getString(before), getString(CLOSED)); return this.state.compareAndSet(before, CLOSED); } public boolean changeClosed() { - logger.debug("State Will Be Changed {}.", getString(CLOSED)); - return this.state.compareAndSet(RUN, CLOSED); + logger.debug("State Will Be Changed {}.", getString(CLOSED)); + return this.state.compareAndSet(RUN, CLOSED); } public void setClosed() { @@ -118,7 +118,7 @@ public class State { } public void setState(int state) { - logger.debug("State Will Be Changed {}.", getString(state)); + logger.debug("State Will Be Changed {}.", getString(state)); this.state.set(state); } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/codec/PacketDecoder.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/codec/PacketDecoder.java index 03c9dd9e7..7d318ab81 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/codec/PacketDecoder.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/codec/PacketDecoder.java @@ -77,9 +77,9 @@ public class PacketDecoder extends FrameDecoder { case PacketType.APPLICATION_STREAM_RESPONSE: return readStreamData(packetType, buffer); case PacketType.APPLICATION_STREAM_PING: - return readStreamPing(packetType, buffer); + return readStreamPing(packetType, buffer); case PacketType.APPLICATION_STREAM_PONG: - return readStreamPong(packetType, buffer); + return readStreamPong(packetType, buffer); case PacketType.CONTROL_CLIENT_CLOSE: return readControlClientClose(packetType, buffer); case PacketType.CONTROL_SERVER_CLOSE: @@ -95,16 +95,16 @@ public class PacketDecoder extends FrameDecoder { // just also drop pong. return null; case PacketType.CONTROL_HANDSHAKE: - return readEnableWorker(packetType, buffer); + return readEnableWorker(packetType, buffer); case PacketType.CONTROL_HANDSHAKE_RESPONSE: - return readEnableWorkerConfirm(packetType, buffer); + return readEnableWorkerConfirm(packetType, buffer); } logger.error("invalid packetType received. packetType:{}, channel:{}", packetType, channel); channel.close(); return null; } - private void sendPong(Channel channel) { + private void sendPong(Channel channel) { // a "pong" responds to a "ping" automatically. logger.debug("received ping. sending pong. {}", channel); @@ -162,13 +162,13 @@ public class PacketDecoder extends FrameDecoder { return StreamResponsePacket.readBuffer(packetType, buffer); } - private Object readStreamPong(short packetType, ChannelBuffer buffer) { + private Object readStreamPong(short packetType, ChannelBuffer buffer) { return StreamPongPacket.readBuffer(packetType, buffer); - } + } - private Object readStreamPing(short packetType, ChannelBuffer buffer) { + private Object readStreamPing(short packetType, ChannelBuffer buffer) { return StreamPingPacket.readBuffer(packetType, buffer); - } + } @@ -178,10 +178,10 @@ public class PacketDecoder extends FrameDecoder { private Object readEnableWorker(short packetType, ChannelBuffer buffer) { return ControlHandshakePacket.readBuffer(packetType, buffer); - } + } private Object readEnableWorkerConfirm(short packetType, ChannelBuffer buffer) { return ControlHandshakeResponsePacket.readBuffer(packetType, buffer); - } + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/control/ControlMessageDecoder.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/control/ControlMessageDecoder.java index a729108ca..399b3aae5 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/control/ControlMessageDecoder.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/control/ControlMessageDecoder.java @@ -28,83 +28,83 @@ import java.util.Map; */ public class ControlMessageDecoder { - private Charset charset; + private Charset charset; - public ControlMessageDecoder() { - this.charset = Charset.forName("UTF-8"); - } + public ControlMessageDecoder() { + this.charset = Charset.forName("UTF-8"); + } - public Object decode(byte[] in) throws ProtocolException { - return decode(ByteBuffer.wrap(in)); - } - - public Object decode(ByteBuffer in) throws ProtocolException { - byte type = in.get(); - switch (type) { - case ControlMessageProtocolConstant.TYPE_CHARACTER_NULL: - return null; - case ControlMessageProtocolConstant.TYPE_CHARACTER_BOOL_TRUE: - return Boolean.TRUE; - case ControlMessageProtocolConstant.TYPE_CHARACTER_BOOL_FALSE: - return Boolean.FALSE; - case ControlMessageProtocolConstant.TYPE_CHARACTER_INT: - return in.getInt(); - case ControlMessageProtocolConstant.TYPE_CHARACTER_LONG: - return in.getLong(); - case ControlMessageProtocolConstant.TYPE_CHARACTER_DOUBLE: - return Double.longBitsToDouble(in.getLong()); - case ControlMessageProtocolConstant.TYPE_CHARACTER_STRING: - return decodeString(in); - case ControlMessageProtocolConstant.CONTROL_CHARACTER_LIST_START: - List answerList = new ArrayList(); - while (!isListFinished(in)) { - answerList.add(decode(in)); - } - in.get(); // Skip the terminator - return answerList; - case ControlMessageProtocolConstant.CONTROL_CHARACTER_MAP_START: - Map answerMap = new LinkedHashMap(); - while (!isMapFinished(in)) { - Object key = decode(in); - Object value = decode(in); - answerMap.put(key, value); - } - in.get(); // Skip the terminator - return answerMap; - default: - throw new ProtocolException("invalid type character: " + (char) type + " (" + "0x" + Integer.toHexString(type) + ")"); - } - } + public Object decode(byte[] in) throws ProtocolException { + return decode(ByteBuffer.wrap(in)); + } - private Object decodeString(ByteBuffer in) { - int length = readStringLength(in); + public Object decode(ByteBuffer in) throws ProtocolException { + byte type = in.get(); + switch (type) { + case ControlMessageProtocolConstant.TYPE_CHARACTER_NULL: + return null; + case ControlMessageProtocolConstant.TYPE_CHARACTER_BOOL_TRUE: + return Boolean.TRUE; + case ControlMessageProtocolConstant.TYPE_CHARACTER_BOOL_FALSE: + return Boolean.FALSE; + case ControlMessageProtocolConstant.TYPE_CHARACTER_INT: + return in.getInt(); + case ControlMessageProtocolConstant.TYPE_CHARACTER_LONG: + return in.getLong(); + case ControlMessageProtocolConstant.TYPE_CHARACTER_DOUBLE: + return Double.longBitsToDouble(in.getLong()); + case ControlMessageProtocolConstant.TYPE_CHARACTER_STRING: + return decodeString(in); + case ControlMessageProtocolConstant.CONTROL_CHARACTER_LIST_START: + List answerList = new ArrayList(); + while (!isListFinished(in)) { + answerList.add(decode(in)); + } + in.get(); // Skip the terminator + return answerList; + case ControlMessageProtocolConstant.CONTROL_CHARACTER_MAP_START: + Map answerMap = new LinkedHashMap(); + while (!isMapFinished(in)) { + Object key = decode(in); + Object value = decode(in); + answerMap.put(key, value); + } + in.get(); // Skip the terminator + return answerMap; + default: + throw new ProtocolException("invalid type character: " + (char) type + " (" + "0x" + Integer.toHexString(type) + ")"); + } + } - byte[] bytesToEncode = new byte[length]; - in.get(bytesToEncode); + private Object decodeString(ByteBuffer in) { + int length = readStringLength(in); - return new String(bytesToEncode, charset); - } + byte[] bytesToEncode = new byte[length]; + in.get(bytesToEncode); - private boolean isMapFinished(ByteBuffer in) { - return in.get(in.position()) == ControlMessageProtocolConstant.CONTROL_CHARACTER_MAP_END; - } + return new String(bytesToEncode, charset); + } - private boolean isListFinished(ByteBuffer in) { - return in.get(in.position()) == ControlMessageProtocolConstant.CONTROL_CHARACTER_LIST_END; - } + private boolean isMapFinished(ByteBuffer in) { + return in.get(in.position()) == ControlMessageProtocolConstant.CONTROL_CHARACTER_MAP_END; + } - private int readStringLength(ByteBuffer in) { - int result = 0; - int shift = 0; + private boolean isListFinished(ByteBuffer in) { + return in.get(in.position()) == ControlMessageProtocolConstant.CONTROL_CHARACTER_LIST_END; + } - while (true) { - byte b = in.get(); - result |= (b & 0x7F) << shift; - if ((b & 0x80) != 128) - break; - shift += 7; - } - return result; - } + private int readStringLength(ByteBuffer in) { + int result = 0; + int shift = 0; + + while (true) { + byte b = in.get(); + result |= (b & 0x7F) << shift; + if ((b & 0x80) != 128) + break; + shift += 7; + } + return result; + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/control/ControlMessageEncoder.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/control/ControlMessageEncoder.java index 8658c4540..ee65f694c 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/control/ControlMessageEncoder.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/control/ControlMessageEncoder.java @@ -35,163 +35,163 @@ import org.jboss.netty.buffer.ChannelBuffers; public class ControlMessageEncoder { - private Charset charset; + private Charset charset; - public ControlMessageEncoder() { - this.charset = Charset.forName("UTF-8"); - } + public ControlMessageEncoder() { + this.charset = Charset.forName("UTF-8"); + } - public byte[] encode(Map value) throws ProtocolException { - ChannelBuffer cb = ChannelBuffers.dynamicBuffer(100); - encode(value, cb); + public byte[] encode(Map value) throws ProtocolException { + ChannelBuffer cb = ChannelBuffers.dynamicBuffer(100); + encode(value, cb); - int writeIndex = cb.writerIndex(); - byte[] result = new byte[writeIndex]; - - cb.readBytes(result); - - return result; - } - - private void encode(Map value, ChannelBuffer cb) throws ProtocolException { - encodeMap(value, cb); - } + int writeIndex = cb.writerIndex(); + byte[] result = new byte[writeIndex]; - private void encode(Object value, ChannelBuffer cb) throws ProtocolException { -// try { - if (value == null) { - encodeNull(cb); - } else if (value instanceof String) { - encodeString((String) value, cb); - } else if (value instanceof Boolean) { - encodeBoolean((Boolean) value, cb); - } else if (value instanceof Short) { - encodeInt((Short) value, cb); - } else if (value instanceof Integer) { - encodeInt((Integer) value, cb); - } else if (value instanceof Long) { - encodeLong((Long) value, cb); - } else if (value instanceof Float) { - encodeDouble(((Float) value).doubleValue(), cb); - } else if (value instanceof Double) { - encodeDouble((Double) value, cb); - } else if (value instanceof Number) { // Other numbers (i.e. - // BigInteger and BigDecimal) - encodeString(value.toString(), cb); - } else if (value instanceof Collection) { - encodeCollection((Collection) value, cb); - } else if (value instanceof Map) { - encodeMap((Map) value, cb); - } else if (value.getClass().isArray()) { - int arraySize = Array.getLength(value); + cb.readBytes(result); - List arrayToList = new ArrayList(arraySize); - for (int i = 0; i < arraySize; i++) { - arrayToList.add(Array.get(value, i)); - } - encodeCollection(arrayToList, cb); - } else { - throw new ProtocolException("Unsupported type : " + value.getClass().getName()); - } -// } catch (Exception e) { -// throw new ProtocolException(e); -// } - } + return result; + } - private void encodeNull(ChannelBuffer out) { - out.writeByte((byte) ControlMessageProtocolConstant.TYPE_CHARACTER_NULL); - } + private void encode(Map value, ChannelBuffer cb) throws ProtocolException { + encodeMap(value, cb); + } - private void encodeString(String value, ChannelBuffer out) { - out.writeByte((byte) ControlMessageProtocolConstant.TYPE_CHARACTER_STRING); - putPrefixedBytes(value.getBytes(charset), out); - } + private void encode(Object value, ChannelBuffer cb) throws ProtocolException { +// try { + if (value == null) { + encodeNull(cb); + } else if (value instanceof String) { + encodeString((String) value, cb); + } else if (value instanceof Boolean) { + encodeBoolean((Boolean) value, cb); + } else if (value instanceof Short) { + encodeInt((Short) value, cb); + } else if (value instanceof Integer) { + encodeInt((Integer) value, cb); + } else if (value instanceof Long) { + encodeLong((Long) value, cb); + } else if (value instanceof Float) { + encodeDouble(((Float) value).doubleValue(), cb); + } else if (value instanceof Double) { + encodeDouble((Double) value, cb); + } else if (value instanceof Number) { // Other numbers (i.e. + // BigInteger and BigDecimal) + encodeString(value.toString(), cb); + } else if (value instanceof Collection) { + encodeCollection((Collection) value, cb); + } else if (value instanceof Map) { + encodeMap((Map) value, cb); + } else if (value.getClass().isArray()) { + int arraySize = Array.getLength(value); - private void encodeBoolean(boolean value, ChannelBuffer out) { - if (value) { - out.writeByte((byte) ControlMessageProtocolConstant.TYPE_CHARACTER_BOOL_TRUE); - } else { - out.writeByte((byte) ControlMessageProtocolConstant.TYPE_CHARACTER_BOOL_FALSE); - } - } + List arrayToList = new ArrayList(arraySize); + for (int i = 0; i < arraySize; i++) { + arrayToList.add(Array.get(value, i)); + } + encodeCollection(arrayToList, cb); + } else { + throw new ProtocolException("Unsupported type : " + value.getClass().getName()); + } +// } catch (Exception e) { +// throw new ProtocolException(e); +// } + } - private void encodeInt(int value, ChannelBuffer out) { - out.writeByte((byte) ControlMessageProtocolConstant.TYPE_CHARACTER_INT); - - out.writeByte((byte) (value >> 24)); - out.writeByte((byte) (value >> 16)); - out.writeByte((byte) (value >> 8)); - out.writeByte((byte) (value)); - } + private void encodeNull(ChannelBuffer out) { + out.writeByte((byte) ControlMessageProtocolConstant.TYPE_CHARACTER_NULL); + } - private void encodeLong(long value, ChannelBuffer out) { - out.writeByte((byte) ControlMessageProtocolConstant.TYPE_CHARACTER_LONG); - - out.writeByte((byte) (value >> 56)); - out.writeByte((byte) (value >> 48)); - out.writeByte((byte) (value >> 40)); - out.writeByte((byte) (value >> 32)); - out.writeByte((byte) (value >> 24)); - out.writeByte((byte) (value >> 16)); - out.writeByte((byte) (value >> 8)); - out.writeByte((byte) (value)); - } + private void encodeString(String value, ChannelBuffer out) { + out.writeByte((byte) ControlMessageProtocolConstant.TYPE_CHARACTER_STRING); + putPrefixedBytes(value.getBytes(charset), out); + } - private void encodeDouble(double value, ChannelBuffer out) { - out.writeByte((byte) ControlMessageProtocolConstant.TYPE_CHARACTER_DOUBLE); + private void encodeBoolean(boolean value, ChannelBuffer out) { + if (value) { + out.writeByte((byte) ControlMessageProtocolConstant.TYPE_CHARACTER_BOOL_TRUE); + } else { + out.writeByte((byte) ControlMessageProtocolConstant.TYPE_CHARACTER_BOOL_FALSE); + } + } - long longValue = Double.doubleToLongBits(value); - - out.writeByte((byte) (longValue >> 56)); - out.writeByte((byte) (longValue >> 48)); - out.writeByte((byte) (longValue >> 40)); - out.writeByte((byte) (longValue >> 32)); - out.writeByte((byte) (longValue >> 24)); - out.writeByte((byte) (longValue >> 16)); - out.writeByte((byte) (longValue >> 8)); - out.writeByte((byte) (longValue)); - } + private void encodeInt(int value, ChannelBuffer out) { + out.writeByte((byte) ControlMessageProtocolConstant.TYPE_CHARACTER_INT); - private void encodeCollection(Collection collection, ChannelBuffer out) throws ProtocolException { - out.writeByte((byte) ControlMessageProtocolConstant.CONTROL_CHARACTER_LIST_START); - for (Object element : collection) { - encode(element, out); - } - out.writeByte((byte) ControlMessageProtocolConstant.CONTROL_CHARACTER_LIST_END); - } + out.writeByte((byte) (value >> 24)); + out.writeByte((byte) (value >> 16)); + out.writeByte((byte) (value >> 8)); + out.writeByte((byte) (value)); + } - private void encodeMap(Map map, ChannelBuffer out) throws ProtocolException { - out.writeByte((byte) ControlMessageProtocolConstant.CONTROL_CHARACTER_MAP_START); - for (Object element : map.entrySet()) { - Map.Entry entry = (Map.Entry) element; - encode(entry.getKey(), out); - encode(entry.getValue(), out); - } - out.writeByte((byte) ControlMessageProtocolConstant.CONTROL_CHARACTER_MAP_END); - } + private void encodeLong(long value, ChannelBuffer out) { + out.writeByte((byte) ControlMessageProtocolConstant.TYPE_CHARACTER_LONG); - private void putPrefixedBytes(byte[] value, ChannelBuffer out) { - int length = value.length; + out.writeByte((byte) (value >> 56)); + out.writeByte((byte) (value >> 48)); + out.writeByte((byte) (value >> 40)); + out.writeByte((byte) (value >> 32)); + out.writeByte((byte) (value >> 24)); + out.writeByte((byte) (value >> 16)); + out.writeByte((byte) (value >> 8)); + out.writeByte((byte) (value)); + } - byte[] lengthBuf = new byte[5]; + private void encodeDouble(double value, ChannelBuffer out) { + out.writeByte((byte) ControlMessageProtocolConstant.TYPE_CHARACTER_DOUBLE); - int idx = 0; - while (true) { - if ((length & 0xFFFFFF80) == 0) { - lengthBuf[(idx++)] = (byte) length; - break; - } + long longValue = Double.doubleToLongBits(value); - lengthBuf[(idx++)] = (byte) (length & 0x7F | 0x80); + out.writeByte((byte) (longValue >> 56)); + out.writeByte((byte) (longValue >> 48)); + out.writeByte((byte) (longValue >> 40)); + out.writeByte((byte) (longValue >> 32)); + out.writeByte((byte) (longValue >> 24)); + out.writeByte((byte) (longValue >> 16)); + out.writeByte((byte) (longValue >> 8)); + out.writeByte((byte) (longValue)); + } - length >>>= 7; - } + private void encodeCollection(Collection collection, ChannelBuffer out) throws ProtocolException { + out.writeByte((byte) ControlMessageProtocolConstant.CONTROL_CHARACTER_LIST_START); + for (Object element : collection) { + encode(element, out); + } + out.writeByte((byte) ControlMessageProtocolConstant.CONTROL_CHARACTER_LIST_END); + } - for (int i = 0; i < idx; i++) { - out.writeByte(lengthBuf[i]); - } + private void encodeMap(Map map, ChannelBuffer out) throws ProtocolException { + out.writeByte((byte) ControlMessageProtocolConstant.CONTROL_CHARACTER_MAP_START); + for (Object element : map.entrySet()) { + Map.Entry entry = (Map.Entry) element; + encode(entry.getKey(), out); + encode(entry.getValue(), out); + } + out.writeByte((byte) ControlMessageProtocolConstant.CONTROL_CHARACTER_MAP_END); + } - out.writeBytes(value); - } + private void putPrefixedBytes(byte[] value, ChannelBuffer out) { + int length = value.length; + + byte[] lengthBuf = new byte[5]; + + int idx = 0; + while (true) { + if ((length & 0xFFFFFF80) == 0) { + lengthBuf[(idx++)] = (byte) length; + break; + } + + lengthBuf[(idx++)] = (byte) (length & 0x7F | 0x80); + + length >>>= 7; + } + + for (int i = 0; i < idx; i++) { + out.writeByte(lengthBuf[i]); + } + + out.writeBytes(value); + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/control/ControlMessageProtocolConstant.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/control/ControlMessageProtocolConstant.java index c23976212..429d2f60f 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/control/ControlMessageProtocolConstant.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/control/ControlMessageProtocolConstant.java @@ -21,26 +21,26 @@ package com.navercorp.pinpoint.rpc.control; */ public class ControlMessageProtocolConstant { - public static final int TYPE_CHARACTER_NULL = 'N'; + public static final int TYPE_CHARACTER_NULL = 'N'; - public static final int TYPE_CHARACTER_BOOL_TRUE = 'T'; + public static final int TYPE_CHARACTER_BOOL_TRUE = 'T'; - public static final int TYPE_CHARACTER_BOOL_FALSE = 'F'; + public static final int TYPE_CHARACTER_BOOL_FALSE = 'F'; - public static final int TYPE_CHARACTER_INT = 'I'; + public static final int TYPE_CHARACTER_INT = 'I'; - public static final int TYPE_CHARACTER_LONG = 'L'; + public static final int TYPE_CHARACTER_LONG = 'L'; - public static final int TYPE_CHARACTER_DOUBLE = 'D'; + public static final int TYPE_CHARACTER_DOUBLE = 'D'; - public static final int TYPE_CHARACTER_STRING = 'S'; + public static final int TYPE_CHARACTER_STRING = 'S'; - public static final int CONTROL_CHARACTER_LIST_START = 'V'; + public static final int CONTROL_CHARACTER_LIST_START = 'V'; - public static final int CONTROL_CHARACTER_LIST_END = 'z'; + public static final int CONTROL_CHARACTER_LIST_END = 'z'; - public static final int CONTROL_CHARACTER_MAP_START = 'M'; + public static final int CONTROL_CHARACTER_MAP_START = 'M'; - public static final int CONTROL_CHARACTER_MAP_END = 'z'; + public static final int CONTROL_CHARACTER_MAP_END = 'z'; } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/ControlHandshakePacket.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/ControlHandshakePacket.java index 5f064b226..4bfda593b 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/ControlHandshakePacket.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/ControlHandshakePacket.java @@ -24,61 +24,61 @@ import org.jboss.netty.buffer.ChannelBuffers; */ public class ControlHandshakePacket extends ControlPacket { - public ControlHandshakePacket(byte[] payload) { - super(payload); - } + public ControlHandshakePacket(byte[] payload) { + super(payload); + } - public ControlHandshakePacket(int requestId, byte[] payload) { - super(payload); - setRequestId(requestId); - } + public ControlHandshakePacket(int requestId, byte[] payload) { + super(payload); + setRequestId(requestId); + } - @Override - public short getPacketType() { - return PacketType.CONTROL_HANDSHAKE; - } + @Override + public short getPacketType() { + return PacketType.CONTROL_HANDSHAKE; + } - @Override - public ChannelBuffer toBuffer() { + @Override + public ChannelBuffer toBuffer() { - ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 4); - header.writeShort(PacketType.CONTROL_HANDSHAKE); - header.writeInt(getRequestId()); + ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 4); + header.writeShort(PacketType.CONTROL_HANDSHAKE); + header.writeInt(getRequestId()); - return PayloadPacket.appendPayload(header, payload); - } + return PayloadPacket.appendPayload(header, payload); + } - public static ControlHandshakePacket readBuffer(short packetType, ChannelBuffer buffer) { - assert packetType == PacketType.CONTROL_HANDSHAKE; + public static ControlHandshakePacket readBuffer(short packetType, ChannelBuffer buffer) { + assert packetType == PacketType.CONTROL_HANDSHAKE; - if (buffer.readableBytes() < 8) { - buffer.resetReaderIndex(); - return null; - } + if (buffer.readableBytes() < 8) { + buffer.resetReaderIndex(); + return null; + } - final int messageId = buffer.readInt(); - final ChannelBuffer payload = PayloadPacket.readPayload(buffer); - if (payload == null) { - return null; - } - final ControlHandshakePacket helloPacket = new ControlHandshakePacket(payload.array()); - helloPacket.setRequestId(messageId); - return helloPacket; - } + final int messageId = buffer.readInt(); + final ChannelBuffer payload = PayloadPacket.readPayload(buffer); + if (payload == null) { + return null; + } + final ControlHandshakePacket helloPacket = new ControlHandshakePacket(payload.array()); + helloPacket.setRequestId(messageId); + return helloPacket; + } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append(this.getClass().getSimpleName()); - sb.append("{requestId=").append(getRequestId()); - sb.append(", "); - if (payload == null) { - sb.append("payload=null"); - } else { - sb.append("payloadLength=").append(payload.length); - } - sb.append('}'); - return sb.toString(); - } + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(); + sb.append(this.getClass().getSimpleName()); + sb.append("{requestId=").append(getRequestId()); + sb.append(", "); + if (payload == null) { + sb.append("payload=null"); + } else { + sb.append("payloadLength=").append(payload.length); + } + sb.append('}'); + return sb.toString(); + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/ControlHandshakeResponsePacket.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/ControlHandshakeResponsePacket.java index fd73d4a6c..0beacc4fa 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/ControlHandshakeResponsePacket.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/ControlHandshakeResponsePacket.java @@ -27,61 +27,61 @@ public class ControlHandshakeResponsePacket extends ControlPacket { public static final String CODE = "code"; public static final String SUB_CODE = "subCode"; - public ControlHandshakeResponsePacket(byte[] payload) { - super(payload); - } + public ControlHandshakeResponsePacket(byte[] payload) { + super(payload); + } - public ControlHandshakeResponsePacket(int requestId, byte[] payload) { - super(payload); - setRequestId(requestId); - } + public ControlHandshakeResponsePacket(int requestId, byte[] payload) { + super(payload); + setRequestId(requestId); + } - @Override - public short getPacketType() { - return PacketType.CONTROL_HANDSHAKE_RESPONSE; - } + @Override + public short getPacketType() { + return PacketType.CONTROL_HANDSHAKE_RESPONSE; + } - @Override - public ChannelBuffer toBuffer() { + @Override + public ChannelBuffer toBuffer() { - ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 4); - header.writeShort(PacketType.CONTROL_HANDSHAKE_RESPONSE); - header.writeInt(getRequestId()); + ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 4); + header.writeShort(PacketType.CONTROL_HANDSHAKE_RESPONSE); + header.writeInt(getRequestId()); - return PayloadPacket.appendPayload(header, payload); - } + return PayloadPacket.appendPayload(header, payload); + } - public static ControlHandshakeResponsePacket readBuffer(short packetType, ChannelBuffer buffer) { - assert packetType == PacketType.CONTROL_HANDSHAKE_RESPONSE; + public static ControlHandshakeResponsePacket readBuffer(short packetType, ChannelBuffer buffer) { + assert packetType == PacketType.CONTROL_HANDSHAKE_RESPONSE; - if (buffer.readableBytes() < 8) { - buffer.resetReaderIndex(); - return null; - } + if (buffer.readableBytes() < 8) { + buffer.resetReaderIndex(); + return null; + } - final int messageId = buffer.readInt(); - final ChannelBuffer payload = PayloadPacket.readPayload(buffer); - if (payload == null) { - return null; - } - final ControlHandshakeResponsePacket helloPacket = new ControlHandshakeResponsePacket(payload.array()); - helloPacket.setRequestId(messageId); - return helloPacket; - } + final int messageId = buffer.readInt(); + final ChannelBuffer payload = PayloadPacket.readPayload(buffer); + if (payload == null) { + return null; + } + final ControlHandshakeResponsePacket helloPacket = new ControlHandshakeResponsePacket(payload.array()); + helloPacket.setRequestId(messageId); + return helloPacket; + } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append(this.getClass().getSimpleName()); - sb.append("{requestId=").append(getRequestId()); - sb.append(", "); - if (payload == null) { - sb.append("payload=null"); - } else { - sb.append("payloadLength=").append(payload.length); - } - sb.append('}'); - return sb.toString(); - } + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(); + sb.append(this.getClass().getSimpleName()); + sb.append("{requestId=").append(getRequestId()); + sb.append(", "); + if (payload == null) { + sb.append("payload=null"); + } else { + sb.append("payloadLength=").append(payload.length); + } + sb.append('}'); + return sb.toString(); + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/ControlPacket.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/ControlPacket.java index 7b05b7cb7..34d2b671b 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/ControlPacket.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/ControlPacket.java @@ -20,19 +20,19 @@ package com.navercorp.pinpoint.rpc.packet; * @author koo.taejin */ public abstract class ControlPacket extends BasicPacket { - - private int requestId; - public ControlPacket(byte[] payload) { - super(payload); - } + private int requestId; - public int getRequestId() { - return requestId; - } + public ControlPacket(byte[] payload) { + super(payload); + } - public void setRequestId(int requestId) { - this.requestId = requestId; - } + public int getRequestId() { + return requestId; + } + + public void setRequestId(int requestId) { + this.requestId = requestId; + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/BasicStreamPacket.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/BasicStreamPacket.java index ab38375f6..8aec61b18 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/BasicStreamPacket.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/BasicStreamPacket.java @@ -21,33 +21,33 @@ package com.navercorp.pinpoint.rpc.packet.stream; */ public abstract class BasicStreamPacket implements StreamPacket { - // Status Code - public static final short SUCCESS = 0; - - public static final short CHANNEL_CLOSE = 100; + // Status Code + public static final short SUCCESS = 0; - public static final short ID_ERROR = 110; - public static final short ID_ILLEGAL = 111; - public static final short ID_DUPLICATED = 112; - public static final short ID_NOT_FOUND = 113; - - public static final short STATE_ERROR = 120; - public static final short STATE_NOT_RUN = 121; - public static final short STATE_ILLEGAL = 129; + public static final short CHANNEL_CLOSE = 100; - public static final short TYPE_ERROR = 130; - public static final short TYPE_SERVER_UNSUPPORT = 131; - public static final short TYPE_CLIENT = 136; - public static final short TYPE_UNKOWN = 139; - - public static final short PACKET_ERROR = 140; - public static final short PACKET_UNKNOWN = 141; - public static final short PACKET_UNSUPPORT = 142; - - public static final short UNKNWON_ERROR = 200; + public static final short ID_ERROR = 110; + public static final short ID_ILLEGAL = 111; + public static final short ID_DUPLICATED = 112; + public static final short ID_NOT_FOUND = 113; - - public static final short ROUTE_TYPE_ERROR = 330; + public static final short STATE_ERROR = 120; + public static final short STATE_NOT_RUN = 121; + public static final short STATE_ILLEGAL = 129; + + public static final short TYPE_ERROR = 130; + public static final short TYPE_SERVER_UNSUPPORT = 131; + public static final short TYPE_CLIENT = 136; + public static final short TYPE_UNKOWN = 139; + + public static final short PACKET_ERROR = 140; + public static final short PACKET_UNKNOWN = 141; + public static final short PACKET_UNSUPPORT = 142; + + public static final short UNKNWON_ERROR = 200; + + + public static final short ROUTE_TYPE_ERROR = 330; public static final short ROUTE_TYPE_SERVER_UNSUPPORT = 331; public static final short ROUTE_TYPE_CLIENT = 336; public static final short ROUTE_TYPE_UNKOWN = 339; @@ -55,41 +55,41 @@ public abstract class BasicStreamPacket implements StreamPacket { public static final short ROUTE_PACKET_ERROR = 340; public static final short ROUTE_PACKET_UNKNOWN = 341; public static final short ROUTE_PACKET_UNSUPPORT = 342; - + public static final short ROUTE_NOT_FOUND = 350; public static final short ROUTE_CONNECTION_ERROR = 360; - - private static final byte[] EMPTY_PAYLOAD = new byte[0]; - private final int streamChannelId; + private static final byte[] EMPTY_PAYLOAD = new byte[0]; - public BasicStreamPacket(int streamChannelId) { - this.streamChannelId = streamChannelId; - } + private final int streamChannelId; - public byte[] getPayload() { - return EMPTY_PAYLOAD; - } + public BasicStreamPacket(int streamChannelId) { + this.streamChannelId = streamChannelId; + } - public int getStreamChannelId() { - return streamChannelId; - } + public byte[] getPayload() { + return EMPTY_PAYLOAD; + } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append(this.getClass().getSimpleName()); - sb.append("{streamChannelId=").append(streamChannelId); - sb.append(", "); - if (getPayload() == null || getPayload() == EMPTY_PAYLOAD) { - sb.append("payload=null"); - } else { - sb.append("payloadLength=").append(getPayload().length); - } - sb.append('}'); - return sb.toString(); - } + public int getStreamChannelId() { + return streamChannelId; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(); + sb.append(this.getClass().getSimpleName()); + sb.append("{streamChannelId=").append(streamChannelId); + sb.append(", "); + if (getPayload() == null || getPayload() == EMPTY_PAYLOAD) { + sb.append("payload=null"); + } else { + sb.append("payloadLength=").append(getPayload().length); + } + sb.append('}'); + return sb.toString(); + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamClosePacket.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamClosePacket.java index 1c8eb1f01..d477ca5d6 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamClosePacket.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamClosePacket.java @@ -26,59 +26,59 @@ import com.navercorp.pinpoint.rpc.packet.PacketType; */ public class StreamClosePacket extends BasicStreamPacket { - private final static short PACKET_TYPE = PacketType.APPLICATION_STREAM_CLOSE; + private final static short PACKET_TYPE = PacketType.APPLICATION_STREAM_CLOSE; - private final short code; + private final short code; - public StreamClosePacket(int streamChannelId, short code) { - super(streamChannelId); + public StreamClosePacket(int streamChannelId, short code) { + super(streamChannelId); - this.code = code; - } + this.code = code; + } - @Override - public short getPacketType() { - return PACKET_TYPE; - } + @Override + public short getPacketType() { + return PACKET_TYPE; + } - @Override - public ChannelBuffer toBuffer() { - ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 2); - header.writeShort(getPacketType()); - header.writeInt(getStreamChannelId()); - header.writeShort(code); + @Override + public ChannelBuffer toBuffer() { + ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 2); + header.writeShort(getPacketType()); + header.writeInt(getStreamChannelId()); + header.writeShort(code); - return header; - } + return header; + } - public static StreamClosePacket readBuffer(short packetType, ChannelBuffer buffer) { - assert packetType == PACKET_TYPE; + public static StreamClosePacket readBuffer(short packetType, ChannelBuffer buffer) { + assert packetType == PACKET_TYPE; - if (buffer.readableBytes() < 6) { - buffer.resetReaderIndex(); - return null; - } + if (buffer.readableBytes() < 6) { + buffer.resetReaderIndex(); + return null; + } - final int streamChannelId = buffer.readInt(); - final short code = buffer.readShort(); + final int streamChannelId = buffer.readInt(); + final short code = buffer.readShort(); - final StreamClosePacket packet = new StreamClosePacket(streamChannelId, code); - return packet; - } + final StreamClosePacket packet = new StreamClosePacket(streamChannelId, code); + return packet; + } - public short getCode() { - return code; - } + public short getCode() { + return code; + } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append(this.getClass().getSimpleName()); - sb.append("{streamChannelId=").append(getStreamChannelId()); - sb.append(", "); - sb.append("code=").append(getCode()); - sb.append('}'); - return sb.toString(); - } + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(); + sb.append(this.getClass().getSimpleName()); + sb.append("{streamChannelId=").append(getStreamChannelId()); + sb.append(", "); + sb.append("code=").append(getCode()); + sb.append('}'); + return sb.toString(); + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamCreateFailPacket.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamCreateFailPacket.java index 1a34c8849..f4512c7de 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamCreateFailPacket.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamCreateFailPacket.java @@ -26,59 +26,59 @@ import com.navercorp.pinpoint.rpc.packet.PacketType; */ public class StreamCreateFailPacket extends BasicStreamPacket { - private final static short PACKET_TYPE = PacketType.APPLICATION_STREAM_CREATE_FAIL; + private final static short PACKET_TYPE = PacketType.APPLICATION_STREAM_CREATE_FAIL; - private final short code; + private final short code; - public StreamCreateFailPacket(int streamChannelId, short code) { - super(streamChannelId); + public StreamCreateFailPacket(int streamChannelId, short code) { + super(streamChannelId); - this.code = code; - } + this.code = code; + } - @Override - public short getPacketType() { - return PACKET_TYPE; - } + @Override + public short getPacketType() { + return PACKET_TYPE; + } - @Override - public ChannelBuffer toBuffer() { - ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 2); - header.writeShort(getPacketType()); - header.writeInt(getStreamChannelId()); - header.writeShort(code); + @Override + public ChannelBuffer toBuffer() { + ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 2); + header.writeShort(getPacketType()); + header.writeInt(getStreamChannelId()); + header.writeShort(code); - return header; - } + return header; + } - public static StreamCreateFailPacket readBuffer(short packetType, ChannelBuffer buffer) { - assert packetType == PACKET_TYPE; + public static StreamCreateFailPacket readBuffer(short packetType, ChannelBuffer buffer) { + assert packetType == PACKET_TYPE; - if (buffer.readableBytes() < 6) { - buffer.resetReaderIndex(); - return null; - } + if (buffer.readableBytes() < 6) { + buffer.resetReaderIndex(); + return null; + } - final int streamChannelId = buffer.readInt(); - final short code = buffer.readShort(); + final int streamChannelId = buffer.readInt(); + final short code = buffer.readShort(); - final StreamCreateFailPacket packet = new StreamCreateFailPacket(streamChannelId, code); - return packet; - } + final StreamCreateFailPacket packet = new StreamCreateFailPacket(streamChannelId, code); + return packet; + } - public short getCode() { - return code; - } + public short getCode() { + return code; + } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append(this.getClass().getSimpleName()); - sb.append("{streamChannelId=").append(getStreamChannelId()); - sb.append(", "); - sb.append("code=").append(getCode()); - sb.append('}'); - return sb.toString(); - } + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(); + sb.append(this.getClass().getSimpleName()); + sb.append("{streamChannelId=").append(getStreamChannelId()); + sb.append(", "); + sb.append("code=").append(getCode()); + sb.append('}'); + return sb.toString(); + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamCreatePacket.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamCreatePacket.java index cf5d4241b..03c9c1769 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamCreatePacket.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamCreatePacket.java @@ -28,52 +28,52 @@ import com.navercorp.pinpoint.rpc.util.AssertUtils; */ public class StreamCreatePacket extends BasicStreamPacket { - private final static short PACKET_TYPE = PacketType.APPLICATION_STREAM_CREATE; + private final static short PACKET_TYPE = PacketType.APPLICATION_STREAM_CREATE; - private final byte[] payload; + private final byte[] payload; - public StreamCreatePacket(int streamChannelId, byte[] payload) { - super(streamChannelId); + public StreamCreatePacket(int streamChannelId, byte[] payload) { + super(streamChannelId); - AssertUtils.assertNotNull(payload); - this.payload = payload; - } + AssertUtils.assertNotNull(payload); + this.payload = payload; + } - @Override - public short getPacketType() { - return PACKET_TYPE; - } + @Override + public short getPacketType() { + return PACKET_TYPE; + } - @Override - public byte[] getPayload() { - return payload; - } + @Override + public byte[] getPayload() { + return payload; + } - @Override - public ChannelBuffer toBuffer() { - ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 4); - header.writeShort(getPacketType()); - header.writeInt(getStreamChannelId()); + @Override + public ChannelBuffer toBuffer() { + ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 4); + header.writeShort(getPacketType()); + header.writeInt(getStreamChannelId()); - return PayloadPacket.appendPayload(header, payload); - } + return PayloadPacket.appendPayload(header, payload); + } - public static StreamCreatePacket readBuffer(short packetType, ChannelBuffer buffer) { - assert packetType == PACKET_TYPE; + public static StreamCreatePacket readBuffer(short packetType, ChannelBuffer buffer) { + assert packetType == PACKET_TYPE; - if (buffer.readableBytes() < 8) { - buffer.resetReaderIndex(); - return null; - } + if (buffer.readableBytes() < 8) { + buffer.resetReaderIndex(); + return null; + } - final int streamChannelId = buffer.readInt(); - final ChannelBuffer payload = PayloadPacket.readPayload(buffer); - if (payload == null) { - return null; - } + final int streamChannelId = buffer.readInt(); + final ChannelBuffer payload = PayloadPacket.readPayload(buffer); + if (payload == null) { + return null; + } - final StreamCreatePacket packet = new StreamCreatePacket(streamChannelId, payload.array()); - return packet; - } + final StreamCreatePacket packet = new StreamCreatePacket(streamChannelId, payload.array()); + return packet; + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamCreateSuccessPacket.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamCreateSuccessPacket.java index 4e82b2be9..7f4d52d90 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamCreateSuccessPacket.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamCreateSuccessPacket.java @@ -26,38 +26,38 @@ import com.navercorp.pinpoint.rpc.packet.PacketType; */ public class StreamCreateSuccessPacket extends BasicStreamPacket { - private final static short PACKET_TYPE = PacketType.APPLICATION_STREAM_CREATE_SUCCESS; + private final static short PACKET_TYPE = PacketType.APPLICATION_STREAM_CREATE_SUCCESS; - public StreamCreateSuccessPacket(int streamChannelId) { - super(streamChannelId); - } + public StreamCreateSuccessPacket(int streamChannelId) { + super(streamChannelId); + } - @Override - public short getPacketType() { - return PACKET_TYPE; - } + @Override + public short getPacketType() { + return PACKET_TYPE; + } - @Override - public ChannelBuffer toBuffer() { - ChannelBuffer header = ChannelBuffers.buffer(2 + 4); - header.writeShort(getPacketType()); - header.writeInt(getStreamChannelId()); + @Override + public ChannelBuffer toBuffer() { + ChannelBuffer header = ChannelBuffers.buffer(2 + 4); + header.writeShort(getPacketType()); + header.writeInt(getStreamChannelId()); - return header; - } + return header; + } - public static StreamCreateSuccessPacket readBuffer(short packetType, ChannelBuffer buffer) { - assert packetType == PACKET_TYPE; + public static StreamCreateSuccessPacket readBuffer(short packetType, ChannelBuffer buffer) { + assert packetType == PACKET_TYPE; - if (buffer.readableBytes() < 4) { - buffer.resetReaderIndex(); - return null; - } + if (buffer.readableBytes() < 4) { + buffer.resetReaderIndex(); + return null; + } - final int streamChannelId = buffer.readInt(); + final int streamChannelId = buffer.readInt(); - final StreamCreateSuccessPacket packet = new StreamCreateSuccessPacket(streamChannelId); - return packet; - } + final StreamCreateSuccessPacket packet = new StreamCreateSuccessPacket(streamChannelId); + return packet; + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamPingPacket.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamPingPacket.java index 6edc0a7e5..4bec6e687 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamPingPacket.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamPingPacket.java @@ -26,58 +26,58 @@ import com.navercorp.pinpoint.rpc.packet.PacketType; */ public class StreamPingPacket extends BasicStreamPacket { - private final static short PACKET_TYPE = PacketType.APPLICATION_STREAM_PING; + private final static short PACKET_TYPE = PacketType.APPLICATION_STREAM_PING; - private final int requestId; - - public StreamPingPacket(int streamChannelId, int requestId) { - super(streamChannelId); - this.requestId = requestId; - } + private final int requestId; - @Override - public short getPacketType() { - return PACKET_TYPE; - } + public StreamPingPacket(int streamChannelId, int requestId) { + super(streamChannelId); + this.requestId = requestId; + } - @Override - public ChannelBuffer toBuffer() { - ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 4); - header.writeShort(getPacketType()); - header.writeInt(getStreamChannelId()); - header.writeInt(requestId); + @Override + public short getPacketType() { + return PACKET_TYPE; + } - return header; - } + @Override + public ChannelBuffer toBuffer() { + ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 4); + header.writeShort(getPacketType()); + header.writeInt(getStreamChannelId()); + header.writeInt(requestId); - public static StreamPingPacket readBuffer(short packetType, ChannelBuffer buffer) { - assert packetType == PACKET_TYPE; + return header; + } - if (buffer.readableBytes() < 4) { - buffer.resetReaderIndex(); - return null; - } + public static StreamPingPacket readBuffer(short packetType, ChannelBuffer buffer) { + assert packetType == PACKET_TYPE; - final int streamChannelId = buffer.readInt(); - final int requestId = buffer.readInt(); + if (buffer.readableBytes() < 4) { + buffer.resetReaderIndex(); + return null; + } - final StreamPingPacket packet = new StreamPingPacket(streamChannelId, requestId); - return packet; - } + final int streamChannelId = buffer.readInt(); + final int requestId = buffer.readInt(); - public int getRequestId() { - return requestId; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append(this.getClass().getSimpleName()); - sb.append("{streamChannelId=").append(getStreamChannelId()); - sb.append(", "); - sb.append("streamChannelId=").append(getRequestId()); - sb.append('}'); - return sb.toString(); - } + final StreamPingPacket packet = new StreamPingPacket(streamChannelId, requestId); + return packet; + } + + public int getRequestId() { + return requestId; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(); + sb.append(this.getClass().getSimpleName()); + sb.append("{streamChannelId=").append(getStreamChannelId()); + sb.append(", "); + sb.append("streamChannelId=").append(getRequestId()); + sb.append('}'); + return sb.toString(); + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamPongPacket.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamPongPacket.java index cb6814320..37d8aec8b 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamPongPacket.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamPongPacket.java @@ -26,58 +26,58 @@ import com.navercorp.pinpoint.rpc.packet.PacketType; */ public class StreamPongPacket extends BasicStreamPacket { - private final static short PACKET_TYPE = PacketType.APPLICATION_STREAM_PONG; + private final static short PACKET_TYPE = PacketType.APPLICATION_STREAM_PONG; - private final int requestId; - - public StreamPongPacket(int streamChannelId, int requestId) { - super(streamChannelId); - this.requestId = requestId; - } + private final int requestId; - @Override - public short getPacketType() { - return PACKET_TYPE; - } + public StreamPongPacket(int streamChannelId, int requestId) { + super(streamChannelId); + this.requestId = requestId; + } - @Override - public ChannelBuffer toBuffer() { - ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 4); - header.writeShort(getPacketType()); - header.writeInt(getStreamChannelId()); - header.writeInt(requestId); + @Override + public short getPacketType() { + return PACKET_TYPE; + } - return header; - } + @Override + public ChannelBuffer toBuffer() { + ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 4); + header.writeShort(getPacketType()); + header.writeInt(getStreamChannelId()); + header.writeInt(requestId); - public static StreamPongPacket readBuffer(short packetType, ChannelBuffer buffer) { - assert packetType == PACKET_TYPE; + return header; + } - if (buffer.readableBytes() < 4) { - buffer.resetReaderIndex(); - return null; - } + public static StreamPongPacket readBuffer(short packetType, ChannelBuffer buffer) { + assert packetType == PACKET_TYPE; - final int streamChannelId = buffer.readInt(); - final int requestId = buffer.readInt(); + if (buffer.readableBytes() < 4) { + buffer.resetReaderIndex(); + return null; + } - final StreamPongPacket packet = new StreamPongPacket(streamChannelId, requestId); - return packet; - } + final int streamChannelId = buffer.readInt(); + final int requestId = buffer.readInt(); - public int getRequestId() { - return requestId; - } + final StreamPongPacket packet = new StreamPongPacket(streamChannelId, requestId); + return packet; + } + + public int getRequestId() { + return requestId; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(); + sb.append(this.getClass().getSimpleName()); + sb.append("{channelId=").append(getStreamChannelId()); + sb.append(", "); + sb.append("requestId=").append(getRequestId()); + sb.append('}'); + return sb.toString(); + } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append(this.getClass().getSimpleName()); - sb.append("{channelId=").append(getStreamChannelId()); - sb.append(", "); - sb.append("requestId=").append(getRequestId()); - sb.append('}'); - return sb.toString(); - } - } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamResponsePacket.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamResponsePacket.java index 8b8f13346..3ee3ecfa8 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamResponsePacket.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/packet/stream/StreamResponsePacket.java @@ -28,52 +28,52 @@ import com.navercorp.pinpoint.rpc.util.AssertUtils; */ public class StreamResponsePacket extends BasicStreamPacket { - private final static short PACKET_TYPE = PacketType.APPLICATION_STREAM_RESPONSE; + private final static short PACKET_TYPE = PacketType.APPLICATION_STREAM_RESPONSE; - private final byte[] payload; + private final byte[] payload; - public StreamResponsePacket(int streamChannelId, byte[] payload) { - super(streamChannelId); + public StreamResponsePacket(int streamChannelId, byte[] payload) { + super(streamChannelId); - AssertUtils.assertNotNull(payload); - this.payload = payload; - } + AssertUtils.assertNotNull(payload); + this.payload = payload; + } - @Override - public short getPacketType() { - return PACKET_TYPE; - } + @Override + public short getPacketType() { + return PACKET_TYPE; + } - @Override - public byte[] getPayload() { - return payload; - } + @Override + public byte[] getPayload() { + return payload; + } - @Override - public ChannelBuffer toBuffer() { - ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 4); - header.writeShort(getPacketType()); - header.writeInt(getStreamChannelId()); + @Override + public ChannelBuffer toBuffer() { + ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 4); + header.writeShort(getPacketType()); + header.writeInt(getStreamChannelId()); - return PayloadPacket.appendPayload(header, payload); - } + return PayloadPacket.appendPayload(header, payload); + } - public static StreamResponsePacket readBuffer(short packetType, ChannelBuffer buffer) { - assert packetType == PACKET_TYPE; + public static StreamResponsePacket readBuffer(short packetType, ChannelBuffer buffer) { + assert packetType == PACKET_TYPE; - if (buffer.readableBytes() < 8) { - buffer.resetReaderIndex(); - return null; - } + if (buffer.readableBytes() < 8) { + buffer.resetReaderIndex(); + return null; + } - final int streamChannelId = buffer.readInt(); - final ChannelBuffer payload = PayloadPacket.readPayload(buffer); - if (payload == null) { - return null; - } + final int streamChannelId = buffer.readInt(); + final ChannelBuffer payload = PayloadPacket.readPayload(buffer); + if (payload == null) { + return null; + } - final StreamResponsePacket packet = new StreamResponsePacket(streamChannelId, payload.array()); - return packet; - } + final StreamResponsePacket packet = new StreamResponsePacket(streamChannelId, payload.array()); + return packet; + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/ChannelContext.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/ChannelContext.java index 501793521..b0ed4a4c2 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/ChannelContext.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/ChannelContext.java @@ -30,108 +30,108 @@ import com.navercorp.pinpoint.rpc.stream.StreamChannelManager; public class ChannelContext { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final StreamChannelManager streamChannelManager; + private final StreamChannelManager streamChannelManager; - private final SocketChannel socketChannel; + private final SocketChannel socketChannel; - private final PinpointServerSocketState state; + private final PinpointServerSocketState state; - private final SocketChannelStateChangeEventListener stateChangeEventListener; - - private final AtomicReference> properties = new AtomicReference>(); + private final SocketChannelStateChangeEventListener stateChangeEventListener; - public ChannelContext(SocketChannel socketChannel, StreamChannelManager streamChannelManager) { - this(socketChannel, streamChannelManager, DoNothingChannelStateEventListener.INSTANCE); - } - - public ChannelContext(SocketChannel socketChannel, StreamChannelManager streamChannelManager, SocketChannelStateChangeEventListener stateChangeEventListener) { - this.socketChannel = socketChannel; - this.streamChannelManager = streamChannelManager; + private final AtomicReference> properties = new AtomicReference>(); - this.stateChangeEventListener = stateChangeEventListener; - - this.state = new PinpointServerSocketState(); - } + public ChannelContext(SocketChannel socketChannel, StreamChannelManager streamChannelManager) { + this(socketChannel, streamChannelManager, DoNothingChannelStateEventListener.INSTANCE); + } - public StreamChannelContext getStreamChannel(int channelId) { - return streamChannelManager.findStreamChannel(channelId); - } + public ChannelContext(SocketChannel socketChannel, StreamChannelManager streamChannelManager, SocketChannelStateChangeEventListener stateChangeEventListener) { + this.socketChannel = socketChannel; + this.streamChannelManager = streamChannelManager; - public ClientStreamChannelContext createStreamChannel(byte[] payload, ClientStreamChannelMessageListener clientStreamChannelMessageListener) { - return streamChannelManager.openStreamChannel(payload, clientStreamChannelMessageListener); - } + this.stateChangeEventListener = stateChangeEventListener; - public void closeAllStreamChannel() { - streamChannelManager.close(); - } + this.state = new PinpointServerSocketState(); + } - public SocketChannel getSocketChannel() { - return socketChannel; - } + public StreamChannelContext getStreamChannel(int channelId) { + return streamChannelManager.findStreamChannel(channelId); + } - public PinpointServerSocketStateCode getCurrentStateCode() { - return state.getCurrentState(); - } + public ClientStreamChannelContext createStreamChannel(byte[] payload, ClientStreamChannelMessageListener clientStreamChannelMessageListener) { + return streamChannelManager.openStreamChannel(payload, clientStreamChannelMessageListener); + } - public void changeStateRun() { - logger.debug("Channel({}) state will be changed {}.", socketChannel, PinpointServerSocketStateCode.RUN); - if (state.changeStateRun()) { - stateChangeEventListener.eventPerformed(this, PinpointServerSocketStateCode.RUN); - } - } + public void closeAllStreamChannel() { + streamChannelManager.close(); + } - public void changeStateRunDuplexCommunication() { - logger.debug("Channel({}) state will be changed {}.", socketChannel, PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION); - if (state.changeStateRunDuplexCommunication()) { - stateChangeEventListener.eventPerformed(this, PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION); - } - } + public SocketChannel getSocketChannel() { + return socketChannel; + } - public void changeStateBeingShutdown() { - logger.debug("Channel({}) state will be changed {}.", socketChannel, PinpointServerSocketStateCode.BEING_SHUTDOWN); - if (state.changeStateBeingShutdown()) { - stateChangeEventListener.eventPerformed(this, PinpointServerSocketStateCode.BEING_SHUTDOWN); - } - } + public PinpointServerSocketStateCode getCurrentStateCode() { + return state.getCurrentState(); + } - public void changeStateShutdown() { - logger.debug("Channel({}) state will be changed {}.", socketChannel, PinpointServerSocketStateCode.SHUTDOWN); - if (state.changeStateShutdown()) { - stateChangeEventListener.eventPerformed(this, PinpointServerSocketStateCode.SHUTDOWN); - } - } + public void changeStateRun() { + logger.debug("Channel({}) state will be changed {}.", socketChannel, PinpointServerSocketStateCode.RUN); + if (state.changeStateRun()) { + stateChangeEventListener.eventPerformed(this, PinpointServerSocketStateCode.RUN); + } + } - public void changeStateUnexpectedShutdown() { - logger.debug("Channel({}) state will be changed {}.", socketChannel, PinpointServerSocketStateCode.UNEXPECTED_SHUTDOWN); - if (state.changeStateUnexpectedShutdown()) { - stateChangeEventListener.eventPerformed(this, PinpointServerSocketStateCode.UNEXPECTED_SHUTDOWN); - } - } + public void changeStateRunDuplexCommunication() { + logger.debug("Channel({}) state will be changed {}.", socketChannel, PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION); + if (state.changeStateRunDuplexCommunication()) { + stateChangeEventListener.eventPerformed(this, PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION); + } + } - public void changeStateUnkownError() { - logger.debug("Channel({}) state will be changed {}.", socketChannel, PinpointServerSocketStateCode.ERROR_UNKOWN); - if (state.changeStateUnkownError()) { - stateChangeEventListener.eventPerformed(this, PinpointServerSocketStateCode.ERROR_UNKOWN); - } - } + public void changeStateBeingShutdown() { + logger.debug("Channel({}) state will be changed {}.", socketChannel, PinpointServerSocketStateCode.BEING_SHUTDOWN); + if (state.changeStateBeingShutdown()) { + stateChangeEventListener.eventPerformed(this, PinpointServerSocketStateCode.BEING_SHUTDOWN); + } + } - public Map getChannelProperties() { - Map properties = this.properties.get(); - return properties == null ? Collections.emptyMap() : properties; - } + public void changeStateShutdown() { + logger.debug("Channel({}) state will be changed {}.", socketChannel, PinpointServerSocketStateCode.SHUTDOWN); + if (state.changeStateShutdown()) { + stateChangeEventListener.eventPerformed(this, PinpointServerSocketStateCode.SHUTDOWN); + } + } - public boolean setChannelProperties(Map value) { - if (value == null) { - return false; - } - - return this.properties.compareAndSet(null, Collections.unmodifiableMap(value)); - } - - public StreamChannelManager getStreamChannelManager() { - return streamChannelManager; - } + public void changeStateUnexpectedShutdown() { + logger.debug("Channel({}) state will be changed {}.", socketChannel, PinpointServerSocketStateCode.UNEXPECTED_SHUTDOWN); + if (state.changeStateUnexpectedShutdown()) { + stateChangeEventListener.eventPerformed(this, PinpointServerSocketStateCode.UNEXPECTED_SHUTDOWN); + } + } + + public void changeStateUnkownError() { + logger.debug("Channel({}) state will be changed {}.", socketChannel, PinpointServerSocketStateCode.ERROR_UNKOWN); + if (state.changeStateUnkownError()) { + stateChangeEventListener.eventPerformed(this, PinpointServerSocketStateCode.ERROR_UNKOWN); + } + } + + public Map getChannelProperties() { + Map properties = this.properties.get(); + return properties == null ? Collections.emptyMap() : properties; + } + + public boolean setChannelProperties(Map value) { + if (value == null) { + return false; + } + + return this.properties.compareAndSet(null, Collections.unmodifiableMap(value)); + } + + public StreamChannelManager getStreamChannelManager() { + return streamChannelManager; + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/DoNothingChannelStateEventListener.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/DoNothingChannelStateEventListener.java index 2fe80d151..dc5b03f20 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/DoNothingChannelStateEventListener.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/DoNothingChannelStateEventListener.java @@ -21,13 +21,13 @@ import org.slf4j.LoggerFactory; public class DoNothingChannelStateEventListener implements SocketChannelStateChangeEventListener { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public static final SocketChannelStateChangeEventListener INSTANCE = new DoNothingChannelStateEventListener(); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Override - public void eventPerformed(ChannelContext channelContext, PinpointServerSocketStateCode stateCode) { - logger.info("eventPerformed {}:", channelContext); - } + public static final SocketChannelStateChangeEventListener INSTANCE = new DoNothingChannelStateEventListener(); + + @Override + public void eventPerformed(ChannelContext channelContext, PinpointServerSocketStateCode stateCode) { + logger.info("eventPerformed {}:", channelContext); + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/PinpointServerSocket.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/PinpointServerSocket.java index 2b04facc2..a891eb81a 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/PinpointServerSocket.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/PinpointServerSocket.java @@ -85,7 +85,7 @@ public class PinpointServerSocket extends SimpleChannelHandler { private final Logger logger = LoggerFactory.getLogger(this.getClass()); // private final boolean isDebug = logger.isDebugEnabled(); - private static final long DEFAULT_TIMEOUTMILLIS = 3 * 1000; + private static final long DEFAULT_TIMEOUTMILLIS = 3 * 1000; private static final int WORKER_COUNT = CpuUtils.workerCount(); private volatile boolean released; @@ -109,7 +109,7 @@ public class PinpointServerSocket extends SimpleChannelHandler { } public PinpointServerSocket() { - this(DoNothingChannelStateEventListener.INSTANCE); + this(DoNothingChannelStateEventListener.INSTANCE); } public PinpointServerSocket(SocketChannelStateChangeEventListener channelStateChangeEventListener) { @@ -151,8 +151,8 @@ public class PinpointServerSocket extends SimpleChannelHandler { } public void setServerStreamChannelMessageListener(ServerStreamChannelMessageListener serverStreamChannelMessageListener) { - AssertUtils.assertNotNull(serverStreamChannelMessageListener, "serverStreamChannelMessageListener must not be null"); - + AssertUtils.assertNotNull(serverStreamChannelMessageListener, "serverStreamChannelMessageListener must not be null"); + this.serverStreamChannelMessageListener = serverStreamChannelMessageListener; } @@ -173,15 +173,15 @@ public class PinpointServerSocket extends SimpleChannelHandler { } private short getPacketType(Object packet) { - if (packet == null) { - return PacketType.UNKNOWN; - } - - if (packet instanceof Packet) { - return ((Packet) packet).getPacketType(); - } - - return PacketType.UNKNOWN; + if (packet == null) { + return PacketType.UNKNOWN; + } + + if (packet instanceof Packet) { + return ((Packet) packet).getPacketType(); + } + + return PacketType.UNKNOWN; } private ServerBootstrap createBootStrap(int bossCount, int workerCount) { @@ -198,24 +198,24 @@ public class PinpointServerSocket extends SimpleChannelHandler { @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { - final Channel channel = e.getChannel(); - Object message = e.getMessage(); - - logger.debug("messageReceived:{} channel:{}", message, channel); - - ChannelContext channelContext = getChannelContext(channel); - if (!PinpointServerSocketStateCode.isRun(channelContext.getCurrentStateCode())) { - logger.warn("MessageReceived:{} from IllegalState Channel:{} this message will be ignore.", message, channel); - return; - } - - final short packetType = getPacketType(message); - switch (packetType) { - case PacketType.APPLICATION_SEND: { - SocketChannel socketChannel = getChannelContext(channel).getSocketChannel(); - messageListener.handleSend((SendPacket) message, socketChannel); - return; - } + final Channel channel = e.getChannel(); + Object message = e.getMessage(); + + logger.debug("messageReceived:{} channel:{}", message, channel); + + ChannelContext channelContext = getChannelContext(channel); + if (!PinpointServerSocketStateCode.isRun(channelContext.getCurrentStateCode())) { + logger.warn("MessageReceived:{} from IllegalState Channel:{} this message will be ignore.", message, channel); + return; + } + + final short packetType = getPacketType(message); + switch (packetType) { + case PacketType.APPLICATION_SEND: { + SocketChannel socketChannel = getChannelContext(channel).getSocketChannel(); + messageListener.handleSend((SendPacket) message, socketChannel); + return; + } // case PacketType.APPLICATION_TRACE_SEND: { // SocketChannel socketChannel = getChannelContext(channel).getSocketChannel(); // TraceSendPacket traceSendPacket = (TraceSendPacket) message; @@ -228,66 +228,66 @@ public class PinpointServerSocket extends SimpleChannelHandler { // } // return; // } - case PacketType.APPLICATION_REQUEST: { - SocketChannel socketChannel = getChannelContext(channel).getSocketChannel(); - messageListener.handleRequest((RequestPacket) message, socketChannel); - return; - } - case PacketType.APPLICATION_RESPONSE: { - SocketChannel socketChannel = getChannelContext(channel).getSocketChannel(); - socketChannel.receiveResponsePacket((ResponsePacket) message); - return; - } - case PacketType.APPLICATION_STREAM_CREATE: - case PacketType.APPLICATION_STREAM_CLOSE: - case PacketType.APPLICATION_STREAM_CREATE_SUCCESS: - case PacketType.APPLICATION_STREAM_CREATE_FAIL: - case PacketType.APPLICATION_STREAM_RESPONSE: - case PacketType.APPLICATION_STREAM_PING: - case PacketType.APPLICATION_STREAM_PONG: - handleStreamPacket((StreamPacket) message, channel); - return; - case PacketType.CONTROL_HANDSHAKE: - int requestId = ((ControlHandshakePacket)message).getRequestId(); - - Map properties = decodeSocketProperties((ControlHandshakePacket) message); - if (properties == null) { - sendHandshakeResponseMessage(requestId, HandshakeResponseType.ProtocolError.PROTOCOL_ERROR, channel); - return; - } - - HandshakeResponseCode code = messageListener.handleHandshake(properties); - - if (code.getCode() != HandshakeResponseType.Success.CODE) { - sendHandshakeResponseMessage(requestId, code, channel); - } else { - boolean isSet = channelContext.setChannelProperties(properties); - - if (isSet) { - if (code == HandshakeResponseCode.DUPLEX_COMMUNICATION) { - changeStateToRunDuplexCommunication(code, channel); - } - sendHandshakeResponseMessage(requestId, code, channel); - } else { + case PacketType.APPLICATION_REQUEST: { + SocketChannel socketChannel = getChannelContext(channel).getSocketChannel(); + messageListener.handleRequest((RequestPacket) message, socketChannel); + return; + } + case PacketType.APPLICATION_RESPONSE: { + SocketChannel socketChannel = getChannelContext(channel).getSocketChannel(); + socketChannel.receiveResponsePacket((ResponsePacket) message); + return; + } + case PacketType.APPLICATION_STREAM_CREATE: + case PacketType.APPLICATION_STREAM_CLOSE: + case PacketType.APPLICATION_STREAM_CREATE_SUCCESS: + case PacketType.APPLICATION_STREAM_CREATE_FAIL: + case PacketType.APPLICATION_STREAM_RESPONSE: + case PacketType.APPLICATION_STREAM_PING: + case PacketType.APPLICATION_STREAM_PONG: + handleStreamPacket((StreamPacket) message, channel); + return; + case PacketType.CONTROL_HANDSHAKE: + int requestId = ((ControlHandshakePacket)message).getRequestId(); + + Map properties = decodeSocketProperties((ControlHandshakePacket) message); + if (properties == null) { + sendHandshakeResponseMessage(requestId, HandshakeResponseType.ProtocolError.PROTOCOL_ERROR, channel); + return; + } + + HandshakeResponseCode code = messageListener.handleHandshake(properties); + + if (code.getCode() != HandshakeResponseType.Success.CODE) { + sendHandshakeResponseMessage(requestId, code, channel); + } else { + boolean isSet = channelContext.setChannelProperties(properties); + + if (isSet) { + if (code == HandshakeResponseCode.DUPLEX_COMMUNICATION) { + changeStateToRunDuplexCommunication(code, channel); + } + sendHandshakeResponseMessage(requestId, code, channel); + } else { if (code == HandshakeResponseCode.DUPLEX_COMMUNICATION) { sendHandshakeResponseMessage(requestId, HandshakeResponseCode.ALREADY_DUPLEX_COMMUNICATION, channel); } else { sendHandshakeResponseMessage(requestId, HandshakeResponseCode.ALREADY_SIMPLEX_COMMUNICATION, channel); } - } - - } - return; - case PacketType.CONTROL_CLIENT_CLOSE: { - closeChannel(channel); - return; - } - default: - logger.warn("invalid messageReceived msg:{}, connection:{}", message, e.getChannel()); - } + } + + } + return; + case PacketType.CONTROL_CLIENT_CLOSE: { + closeChannel(channel); + return; + } + default: + logger.warn("invalid messageReceived msg:{}, connection:{}", message, e.getChannel()); + } } - private void closeChannel(Channel channel) { + private void closeChannel(Channel channel) { logger.debug("received ClientClosePacket {}", channel); ChannelContext channelContext = getChannelContext(channel); channelContext.changeStateBeingShutdown(); @@ -301,46 +301,46 @@ public class PinpointServerSocket extends SimpleChannelHandler { context.getStreamChannelManager().messageReceived(packet); } - private Map decodeSocketProperties(ControlHandshakePacket message) { - try { - byte[] payload = message.getPayload(); + private Map decodeSocketProperties(ControlHandshakePacket message) { + try { + byte[] payload = message.getPayload(); Map properties = (Map) ControlMessageEncodingUtils.decode(payload); - return properties; - } catch (ProtocolException e) { - logger.warn(e.getMessage(), e); - } - - return null; - } + return properties; + } catch (ProtocolException e) { + logger.warn(e.getMessage(), e); + } + + return null; + } - private boolean changeStateToRunDuplexCommunication(HandshakeResponseCode returnCode, Channel channel) { - ChannelContext context = getChannelContext(channel); + private boolean changeStateToRunDuplexCommunication(HandshakeResponseCode returnCode, Channel channel) { + ChannelContext context = getChannelContext(channel); - if (returnCode == HandshakeResponseType.Success.DUPLEX_COMMUNICATION) { - if (context.getCurrentStateCode() != PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION) { - context.changeStateRunDuplexCommunication(); - return true; - } - } + if (returnCode == HandshakeResponseType.Success.DUPLEX_COMMUNICATION) { + if (context.getCurrentStateCode() != PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION) { + context.changeStateRunDuplexCommunication(); + return true; + } + } + + return false; + } - return false; - } - private void sendHandshakeResponseMessage(int requestId, HandshakeResponseCode handShakeResponseCode, Channel channel) { - try { - logger.info("write HandshakeResponsePakcet. channel:{}, HandshakeResponseCode:{}.", channel, handShakeResponseCode); - - Map result = new HashMap(); - result.put(ControlHandshakeResponsePacket.CODE, handShakeResponseCode.getCode()); + try { + logger.info("write HandshakeResponsePakcet. channel:{}, HandshakeResponseCode:{}.", channel, handShakeResponseCode); + + Map result = new HashMap(); + result.put(ControlHandshakeResponsePacket.CODE, handShakeResponseCode.getCode()); result.put(ControlHandshakeResponsePacket.SUB_CODE, handShakeResponseCode.getSubCode()); - - byte[] resultPayload = ControlMessageEncodingUtils.encode(result); - ControlHandshakeResponsePacket packet = new ControlHandshakeResponsePacket(requestId, resultPayload); - - channel.write(packet); - } catch (ProtocolException e) { - logger.warn(e.getMessage(), e); - } + + byte[] resultPayload = ControlMessageEncodingUtils.encode(result); + ControlHandshakeResponsePacket packet = new ControlHandshakeResponsePacket(requestId, resultPayload); + + channel.write(packet); + } catch (ProtocolException e) { + logger.warn(e.getMessage(), e); + } } @Override @@ -374,7 +374,7 @@ public class PinpointServerSocket extends SimpleChannelHandler { boolean check = checkIgnoreAddress(channel); if (check) { - channelContext.changeStateRun(); + channelContext.changeStateRun(); } super.channelConnected(ctx, e); @@ -387,13 +387,13 @@ public class PinpointServerSocket extends SimpleChannelHandler { PinpointServerSocketStateCode currentStateCode = channelContext.getCurrentStateCode(); if (currentStateCode == PinpointServerSocketStateCode.BEING_SHUTDOWN) { - channelContext.changeStateShutdown(); + channelContext.changeStateShutdown(); } else if(released) { channelContext.changeStateShutdown(); } else { boolean check = checkIgnoreAddress(channel); if (check) { - channelContext.changeStateUnexpectedShutdown(); + channelContext.changeStateUnexpectedShutdown(); } } @@ -456,9 +456,9 @@ public class PinpointServerSocket extends SimpleChannelHandler { } private void prepareChannel(Channel channel) { - SocketChannel socketChannel = new SocketChannel(channel, DEFAULT_TIMEOUTMILLIS, requestManagerTimer); - StreamChannelManager streamChannelManager = new StreamChannelManager(channel, IDGenerator.createEvenIdGenerator(), serverStreamChannelMessageListener); - + SocketChannel socketChannel = new SocketChannel(channel, DEFAULT_TIMEOUTMILLIS, requestManagerTimer); + StreamChannelManager streamChannelManager = new StreamChannelManager(channel, IDGenerator.createEvenIdGenerator(), serverStreamChannelMessageListener); + ChannelContext channelContext = new ChannelContext(socketChannel, streamChannelManager, channelStateChangeEventListener); channel.setAttachment(channelContext); @@ -571,7 +571,7 @@ public class PinpointServerSocket extends SimpleChannelHandler { } public List getDuplexCommunicationChannelContext() { - List channelContextList = new ArrayList(); + List channelContextList = new ArrayList(); for (Channel channel : channelGroup) { ChannelContext context = getChannelContext(channel); @@ -580,8 +580,8 @@ public class PinpointServerSocket extends SimpleChannelHandler { channelContextList.add(context); } } - - return channelContextList; + + return channelContextList; } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/PinpointServerSocketState.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/PinpointServerSocketState.java index 5996b655b..4397632cc 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/PinpointServerSocketState.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/PinpointServerSocketState.java @@ -24,80 +24,80 @@ import org.slf4j.LoggerFactory; */ public class PinpointServerSocketState { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private PinpointServerSocketStateCode beforeState = PinpointServerSocketStateCode.NONE; - private PinpointServerSocketStateCode currentState = PinpointServerSocketStateCode.NONE; + private PinpointServerSocketStateCode beforeState = PinpointServerSocketStateCode.NONE; + private PinpointServerSocketStateCode currentState = PinpointServerSocketStateCode.NONE; - private synchronized boolean setSessionState(PinpointServerSocketStateCode state) { - boolean enable = this.currentState.canChangeState(state); + private synchronized boolean setSessionState(PinpointServerSocketStateCode state) { + boolean enable = this.currentState.canChangeState(state); - if (enable) { - this.beforeState = this.currentState; - this.currentState = state; - return true; - } else if (PinpointServerSocketStateCode.isFinished(this.currentState)) { - // if state can't be changed, just log. - // no problem because the state of socket has been already closed. - PinpointServerSocketStateCode checkBefore = this.beforeState; - PinpointServerSocketStateCode checkCurrent = this.currentState; + if (enable) { + this.beforeState = this.currentState; + this.currentState = state; + return true; + } else if (PinpointServerSocketStateCode.isFinished(this.currentState)) { + // if state can't be changed, just log. + // no problem because the state of socket has been already closed. + PinpointServerSocketStateCode checkBefore = this.beforeState; + PinpointServerSocketStateCode checkCurrent = this.currentState; - String errorMessage = cannotChangeMessage(checkBefore, checkCurrent, state); + String errorMessage = cannotChangeMessage(checkBefore, checkCurrent, state); - this.beforeState = this.currentState; - this.currentState = PinpointServerSocketStateCode.ERROR_ILLEGAL_STATE_CHANGE; - - logger.warn(errorMessage); - return false; - } else { - PinpointServerSocketStateCode checkBefore = this.beforeState; - PinpointServerSocketStateCode checkCurrent = this.currentState; + this.beforeState = this.currentState; + this.currentState = PinpointServerSocketStateCode.ERROR_ILLEGAL_STATE_CHANGE; - String errorMessage = errorMessage(checkBefore, checkCurrent, state); - - this.beforeState = this.currentState; - this.currentState = PinpointServerSocketStateCode.ERROR_ILLEGAL_STATE_CHANGE; - - logger.warn(errorMessage); - - throw new IllegalStateException(errorMessage); - } - } - - public boolean changeStateRun() { - return setSessionState(PinpointServerSocketStateCode.RUN); - } - - public boolean changeStateRunDuplexCommunication() { - return setSessionState(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION); - } + logger.warn(errorMessage); + return false; + } else { + PinpointServerSocketStateCode checkBefore = this.beforeState; + PinpointServerSocketStateCode checkCurrent = this.currentState; - public boolean changeStateBeingShutdown() { - return setSessionState(PinpointServerSocketStateCode.BEING_SHUTDOWN); - } + String errorMessage = errorMessage(checkBefore, checkCurrent, state); - public boolean changeStateShutdown() { - return setSessionState(PinpointServerSocketStateCode.SHUTDOWN); - } + this.beforeState = this.currentState; + this.currentState = PinpointServerSocketStateCode.ERROR_ILLEGAL_STATE_CHANGE; - public boolean changeStateUnexpectedShutdown() { - return setSessionState(PinpointServerSocketStateCode.UNEXPECTED_SHUTDOWN); - } + logger.warn(errorMessage); - public boolean changeStateUnkownError() { - return setSessionState(PinpointServerSocketStateCode.ERROR_UNKOWN); - } - - private String errorMessage(PinpointServerSocketStateCode checkBefore, PinpointServerSocketStateCode checkCurrent, PinpointServerSocketStateCode nextState) { - return "Invalid State(current:" + checkCurrent + " before:" + checkBefore + " next:" + nextState + ")"; - } + throw new IllegalStateException(errorMessage); + } + } - private String cannotChangeMessage(PinpointServerSocketStateCode checkBefore, PinpointServerSocketStateCode checkCurrent, PinpointServerSocketStateCode nextState) { - return "Can not change State(current:" + checkCurrent + " before:" + checkBefore + " next:" + nextState + ")"; - } + public boolean changeStateRun() { + return setSessionState(PinpointServerSocketStateCode.RUN); + } - public synchronized PinpointServerSocketStateCode getCurrentState() { - return currentState; - } + public boolean changeStateRunDuplexCommunication() { + return setSessionState(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION); + } + + public boolean changeStateBeingShutdown() { + return setSessionState(PinpointServerSocketStateCode.BEING_SHUTDOWN); + } + + public boolean changeStateShutdown() { + return setSessionState(PinpointServerSocketStateCode.SHUTDOWN); + } + + public boolean changeStateUnexpectedShutdown() { + return setSessionState(PinpointServerSocketStateCode.UNEXPECTED_SHUTDOWN); + } + + public boolean changeStateUnkownError() { + return setSessionState(PinpointServerSocketStateCode.ERROR_UNKOWN); + } + + private String errorMessage(PinpointServerSocketStateCode checkBefore, PinpointServerSocketStateCode checkCurrent, PinpointServerSocketStateCode nextState) { + return "Invalid State(current:" + checkCurrent + " before:" + checkBefore + " next:" + nextState + ")"; + } + + private String cannotChangeMessage(PinpointServerSocketStateCode checkBefore, PinpointServerSocketStateCode checkCurrent, PinpointServerSocketStateCode nextState) { + return "Can not change State(current:" + checkCurrent + " before:" + checkBefore + " next:" + nextState + ")"; + } + + public synchronized PinpointServerSocketStateCode getCurrentState() { + return currentState; + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/PinpointServerSocketStateCode.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/PinpointServerSocketStateCode.java index 1c1478316..66cca7593 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/PinpointServerSocketStateCode.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/PinpointServerSocketStateCode.java @@ -24,85 +24,85 @@ import java.util.Set; */ public enum PinpointServerSocketStateCode { - // NONE : No event - // RUN : can send message only to server - // RUN_DUPLEX_COMMUNICATION : can communicate each other by full-duplex - // BEING_SHUTDOWN : received a close packet from a peer first and releasing resources - // SHUTDOWN : has been closed - // UNEXPECTED_SHUTDOWN : has not received a close packet from a peer but a peer has been shutdown - - NONE(), - RUN(NONE), //Simplex Communication - RUN_DUPLEX_COMMUNICATION(NONE, RUN), - BEING_SHUTDOWN(RUN_DUPLEX_COMMUNICATION, RUN), - SHUTDOWN(RUN_DUPLEX_COMMUNICATION, RUN, BEING_SHUTDOWN), - UNEXPECTED_SHUTDOWN(RUN_DUPLEX_COMMUNICATION, RUN), - + // NONE : No event + // RUN : can send message only to server + // RUN_DUPLEX_COMMUNICATION : can communicate each other by full-duplex + // BEING_SHUTDOWN : received a close packet from a peer first and releasing resources + // SHUTDOWN : has been closed + // UNEXPECTED_SHUTDOWN : has not received a close packet from a peer but a peer has been shutdown - // need messages to close a connection from server to agent - // for example, checked all of needed things followed by HELLO, if a same agent name exists, have to notify that to agent or not? - ERROR_UNKOWN(RUN_DUPLEX_COMMUNICATION, RUN), - ERROR_ILLEGAL_STATE_CHANGE(NONE, RUN_DUPLEX_COMMUNICATION, RUN, BEING_SHUTDOWN); + NONE(), + RUN(NONE), //Simplex Communication + RUN_DUPLEX_COMMUNICATION(NONE, RUN), + BEING_SHUTDOWN(RUN_DUPLEX_COMMUNICATION, RUN), + SHUTDOWN(RUN_DUPLEX_COMMUNICATION, RUN, BEING_SHUTDOWN), + UNEXPECTED_SHUTDOWN(RUN_DUPLEX_COMMUNICATION, RUN), - private final Set validBeforeStateSet; - private PinpointServerSocketStateCode(PinpointServerSocketStateCode... validBeforeStates) { - this.validBeforeStateSet = new HashSet(); + // need messages to close a connection from server to agent + // for example, checked all of needed things followed by HELLO, if a same agent name exists, have to notify that to agent or not? + ERROR_UNKOWN(RUN_DUPLEX_COMMUNICATION, RUN), + ERROR_ILLEGAL_STATE_CHANGE(NONE, RUN_DUPLEX_COMMUNICATION, RUN, BEING_SHUTDOWN); - if (validBeforeStates != null) { - for (PinpointServerSocketStateCode eachStateCode : validBeforeStates) { - getValidBeforeStateSet().add(eachStateCode); - } - } - } + private final Set validBeforeStateSet; - public boolean canChangeState(PinpointServerSocketStateCode nextState) { - Set validBeforeStateSet = nextState.getValidBeforeStateSet(); + private PinpointServerSocketStateCode(PinpointServerSocketStateCode... validBeforeStates) { + this.validBeforeStateSet = new HashSet(); - if (validBeforeStateSet.contains(this)) { - return true; - } + if (validBeforeStates != null) { + for (PinpointServerSocketStateCode eachStateCode : validBeforeStates) { + getValidBeforeStateSet().add(eachStateCode); + } + } + } - return false; - } + public boolean canChangeState(PinpointServerSocketStateCode nextState) { + Set validBeforeStateSet = nextState.getValidBeforeStateSet(); - public Set getValidBeforeStateSet() { - return validBeforeStateSet; - } + if (validBeforeStateSet.contains(this)) { + return true; + } - public static boolean isRun(PinpointServerSocketStateCode code) { - if (code == RUN_DUPLEX_COMMUNICATION || code == RUN) { - return true; - } + return false; + } - return false; - } + public Set getValidBeforeStateSet() { + return validBeforeStateSet; + } - public static boolean isRunDuplexCommunication(PinpointServerSocketStateCode code) { - if (code == RUN_DUPLEX_COMMUNICATION) { - return true; - } + public static boolean isRun(PinpointServerSocketStateCode code) { + if (code == RUN_DUPLEX_COMMUNICATION || code == RUN) { + return true; + } - return false; - } - - public static boolean isFinished(PinpointServerSocketStateCode code) { - if (code == SHUTDOWN || code == UNEXPECTED_SHUTDOWN || code == ERROR_UNKOWN || code == ERROR_ILLEGAL_STATE_CHANGE) { - return true; - } - return false; - } - - public static PinpointServerSocketStateCode getStateCode(String name) { - PinpointServerSocketStateCode[] allStateCodes = PinpointServerSocketStateCode.values(); - - for (PinpointServerSocketStateCode code : allStateCodes) { - if (code.name().equalsIgnoreCase(name)) { - return code; - } - } - - return null; - } + return false; + } + + public static boolean isRunDuplexCommunication(PinpointServerSocketStateCode code) { + if (code == RUN_DUPLEX_COMMUNICATION) { + return true; + } + + return false; + } + + public static boolean isFinished(PinpointServerSocketStateCode code) { + if (code == SHUTDOWN || code == UNEXPECTED_SHUTDOWN || code == ERROR_UNKOWN || code == ERROR_ILLEGAL_STATE_CHANGE) { + return true; + } + return false; + } + + public static PinpointServerSocketStateCode getStateCode(String name) { + PinpointServerSocketStateCode[] allStateCodes = PinpointServerSocketStateCode.values(); + + for (PinpointServerSocketStateCode code : allStateCodes) { + if (code.name().equalsIgnoreCase(name)) { + return code; + } + } + + return null; + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/SocketChannel.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/SocketChannel.java index d406f14e8..c94426bd6 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/SocketChannel.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/SocketChannel.java @@ -79,17 +79,17 @@ public class SocketChannel { } public Future sendRequestMessage(byte[] payload) { - if (payload == null) { + if (payload == null) { throw new NullPointerException("requestMessage must not be null"); - } - RequestPacket requestPacket = new RequestPacket(payload); - - ChannelWriteFailListenableFuture messageFuture = this.requestManager.register(requestPacket, this.timeoutMillis); - - ChannelFuture write = this.channel.write(requestPacket); - write.addListener(messageFuture); - - return messageFuture; + } + RequestPacket requestPacket = new RequestPacket(payload); + + ChannelWriteFailListenableFuture messageFuture = this.requestManager.register(requestPacket, this.timeoutMillis); + + ChannelFuture write = this.channel.write(requestPacket); + write.addListener(messageFuture); + + return messageFuture; } public void sendMessage(byte[] payload) { @@ -98,7 +98,7 @@ public class SocketChannel { } public void receiveResponsePacket(ResponsePacket packet) { - this.requestManager.messageReceived(packet, channel); + this.requestManager.messageReceived(packet, channel); } @Override diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/SocketChannelStateChangeEventListener.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/SocketChannelStateChangeEventListener.java index d8abd3831..6bc5e0273 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/SocketChannelStateChangeEventListener.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/server/SocketChannelStateChangeEventListener.java @@ -17,7 +17,7 @@ package com.navercorp.pinpoint.rpc.server; public interface SocketChannelStateChangeEventListener { - - void eventPerformed(ChannelContext channelContext, PinpointServerSocketStateCode stateCode); + + void eventPerformed(ChannelContext channelContext, PinpointServerSocketStateCode stateCode); } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ClientStreamChannel.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ClientStreamChannel.java index 1b04b4201..698f725f2 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ClientStreamChannel.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ClientStreamChannel.java @@ -26,29 +26,29 @@ import com.navercorp.pinpoint.rpc.packet.stream.StreamCreatePacket; */ public class ClientStreamChannel extends StreamChannel { - public ClientStreamChannel(Channel channel, int streamId, StreamChannelManager streamChannelManager) { - super(channel, streamId, streamChannelManager); - } + public ClientStreamChannel(Channel channel, int streamId, StreamChannelManager streamChannelManager) { + super(channel, streamId, streamChannelManager); + } - public ChannelFuture sendCreate(byte[] payload) { - assertState(StreamChannelStateCode.OPEN_AWAIT); + public ChannelFuture sendCreate(byte[] payload) { + assertState(StreamChannelStateCode.OPEN_AWAIT); - StreamCreatePacket packet = new StreamCreatePacket(getStreamId(), payload); - return this.getChannel().write(packet); - } + StreamCreatePacket packet = new StreamCreatePacket(getStreamId(), payload); + return this.getChannel().write(packet); + } - boolean changeStateOpen() { - boolean result = getState().changeStateOpen(); + boolean changeStateOpen() { + boolean result = getState().changeStateOpen(); - logger.info(makeStateChangeMessage(StreamChannelStateCode.OPEN, result)); - return result; - } + logger.info(makeStateChangeMessage(StreamChannelStateCode.OPEN, result)); + return result; + } - boolean changeStateOpenAwait() { - boolean result = getState().changeStateOpenAwait(); + boolean changeStateOpenAwait() { + boolean result = getState().changeStateOpenAwait(); - logger.info(makeStateChangeMessage(StreamChannelStateCode.OPEN_AWAIT, result)); - return result; - } + logger.info(makeStateChangeMessage(StreamChannelStateCode.OPEN_AWAIT, result)); + return result; + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ClientStreamChannelContext.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ClientStreamChannelContext.java index 5529be035..9a15f0f7c 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ClientStreamChannelContext.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ClientStreamChannelContext.java @@ -23,24 +23,24 @@ import com.navercorp.pinpoint.rpc.util.AssertUtils; */ public class ClientStreamChannelContext extends StreamChannelContext { - private final ClientStreamChannel clientStreamChannel; - private final ClientStreamChannelMessageListener clientStreamChannelMessageListener; + private final ClientStreamChannel clientStreamChannel; + private final ClientStreamChannelMessageListener clientStreamChannelMessageListener; - public ClientStreamChannelContext(ClientStreamChannel clientStreamChannel, ClientStreamChannelMessageListener clientStreamChannelMessageListener) { - AssertUtils.assertNotNull(clientStreamChannel); - AssertUtils.assertNotNull(clientStreamChannelMessageListener); + public ClientStreamChannelContext(ClientStreamChannel clientStreamChannel, ClientStreamChannelMessageListener clientStreamChannelMessageListener) { + AssertUtils.assertNotNull(clientStreamChannel); + AssertUtils.assertNotNull(clientStreamChannelMessageListener); - this.clientStreamChannel = clientStreamChannel; - this.clientStreamChannelMessageListener = clientStreamChannelMessageListener; - } + this.clientStreamChannel = clientStreamChannel; + this.clientStreamChannelMessageListener = clientStreamChannelMessageListener; + } - @Override - public ClientStreamChannel getStreamChannel() { - return clientStreamChannel; - } + @Override + public ClientStreamChannel getStreamChannel() { + return clientStreamChannel; + } - public ClientStreamChannelMessageListener getClientStreamChannelMessageListener() { - return clientStreamChannelMessageListener; - } + public ClientStreamChannelMessageListener getClientStreamChannelMessageListener() { + return clientStreamChannelMessageListener; + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ClientStreamChannelMessageListener.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ClientStreamChannelMessageListener.java index c061dc901..7116f11d1 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ClientStreamChannelMessageListener.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ClientStreamChannelMessageListener.java @@ -24,8 +24,8 @@ import com.navercorp.pinpoint.rpc.packet.stream.StreamResponsePacket; */ public interface ClientStreamChannelMessageListener { - void handleStreamData(ClientStreamChannelContext streamChannelContext, StreamResponsePacket packet); + void handleStreamData(ClientStreamChannelContext streamChannelContext, StreamResponsePacket packet); - void handleStreamClose(ClientStreamChannelContext streamChannelContext, StreamClosePacket packet); + void handleStreamClose(ClientStreamChannelContext streamChannelContext, StreamClosePacket packet); } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/DisabledServerStreamChannelMessageListener.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/DisabledServerStreamChannelMessageListener.java index c6546fad7..58d3f7c81 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/DisabledServerStreamChannelMessageListener.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/DisabledServerStreamChannelMessageListener.java @@ -25,19 +25,19 @@ import com.navercorp.pinpoint.rpc.packet.stream.StreamCreatePacket; public class DisabledServerStreamChannelMessageListener implements ServerStreamChannelMessageListener { - public static final ServerStreamChannelMessageListener INSTANCE = new DisabledServerStreamChannelMessageListener(); + public static final ServerStreamChannelMessageListener INSTANCE = new DisabledServerStreamChannelMessageListener(); - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Override - public short handleStreamCreate(ServerStreamChannelContext streamChannelContext, StreamCreatePacket packet) { - logger.info("{} handleStreamCreate unsupported operation. StreamChannel:{}, Packet:{}", this.getClass().getSimpleName(), streamChannelContext, packet); - return BasicStreamPacket.TYPE_SERVER_UNSUPPORT; - } + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Override - public void handleStreamClose(ServerStreamChannelContext streamChannelContext, StreamClosePacket packet) { - logger.info("{} handleStreamClose unsupported operation. StreamChannel:{}, Packet:{}", this.getClass().getSimpleName(), streamChannelContext, packet); - } + @Override + public short handleStreamCreate(ServerStreamChannelContext streamChannelContext, StreamCreatePacket packet) { + logger.info("{} handleStreamCreate unsupported operation. StreamChannel:{}, Packet:{}", this.getClass().getSimpleName(), streamChannelContext, packet); + return BasicStreamPacket.TYPE_SERVER_UNSUPPORT; + } + + @Override + public void handleStreamClose(ServerStreamChannelContext streamChannelContext, StreamClosePacket packet) { + logger.info("{} handleStreamClose unsupported operation. StreamChannel:{}, Packet:{}", this.getClass().getSimpleName(), streamChannelContext, packet); + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/LoggingStreamChannelMessageListener.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/LoggingStreamChannelMessageListener.java index ff676353b..e09604128 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/LoggingStreamChannelMessageListener.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/LoggingStreamChannelMessageListener.java @@ -28,37 +28,37 @@ import com.navercorp.pinpoint.rpc.packet.stream.StreamResponsePacket; */ public class LoggingStreamChannelMessageListener { - private static final Logger LOGGER = LoggerFactory.getLogger(LoggingStreamChannelMessageListener.class); + private static final Logger LOGGER = LoggerFactory.getLogger(LoggingStreamChannelMessageListener.class); - public static final ServerStreamChannelMessageListener SERVER_LISTENER = new Server(); - public static final ClientStreamChannelMessageListener CLIENT_LISTENER = new Client(); + public static final ServerStreamChannelMessageListener SERVER_LISTENER = new Server(); + public static final ClientStreamChannelMessageListener CLIENT_LISTENER = new Client(); - static class Server implements ServerStreamChannelMessageListener { + static class Server implements ServerStreamChannelMessageListener { - @Override - public short handleStreamCreate(ServerStreamChannelContext streamChannelContext, StreamCreatePacket packet) { - LOGGER.info("handleStreamCreate StreamChannel:{}, Packet:{}", streamChannelContext, packet); - return 0; - } + @Override + public short handleStreamCreate(ServerStreamChannelContext streamChannelContext, StreamCreatePacket packet) { + LOGGER.info("handleStreamCreate StreamChannel:{}, Packet:{}", streamChannelContext, packet); + return 0; + } - @Override - public void handleStreamClose(ServerStreamChannelContext streamChannelContext, StreamClosePacket packet) { - LOGGER.info("handleStreamClose StreamChannel:{}, Packet:{}", streamChannelContext, packet); - } + @Override + public void handleStreamClose(ServerStreamChannelContext streamChannelContext, StreamClosePacket packet) { + LOGGER.info("handleStreamClose StreamChannel:{}, Packet:{}", streamChannelContext, packet); + } - } + } - static class Client implements ClientStreamChannelMessageListener { + static class Client implements ClientStreamChannelMessageListener { - @Override - public void handleStreamData(ClientStreamChannelContext streamChannelContext, StreamResponsePacket packet) { - LOGGER.info("handleStreamData StreamChannel:{}, Packet:{}", streamChannelContext, packet); - } + @Override + public void handleStreamData(ClientStreamChannelContext streamChannelContext, StreamResponsePacket packet) { + LOGGER.info("handleStreamData StreamChannel:{}, Packet:{}", streamChannelContext, packet); + } - @Override - public void handleStreamClose(ClientStreamChannelContext streamChannelContext, StreamClosePacket packet) { - LOGGER.info("handleStreamClose StreamChannel:{}, Packet:{}", streamChannelContext, packet); - } + @Override + public void handleStreamClose(ClientStreamChannelContext streamChannelContext, StreamClosePacket packet) { + LOGGER.info("handleStreamClose StreamChannel:{}, Packet:{}", streamChannelContext, packet); + } - } + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ServerStreamChannel.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ServerStreamChannel.java index 18cee06d7..f33be0d47 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ServerStreamChannel.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ServerStreamChannel.java @@ -27,29 +27,29 @@ import com.navercorp.pinpoint.rpc.packet.stream.StreamResponsePacket; */ public class ServerStreamChannel extends StreamChannel { - public ServerStreamChannel(Channel channel, int streamId, StreamChannelManager streamChannelManager) { - super(channel, streamId, streamChannelManager); - } + public ServerStreamChannel(Channel channel, int streamId, StreamChannelManager streamChannelManager) { + super(channel, streamId, streamChannelManager); + } - public ChannelFuture sendData(byte[] payload) { - assertState(StreamChannelStateCode.RUN); + public ChannelFuture sendData(byte[] payload) { + assertState(StreamChannelStateCode.RUN); - StreamResponsePacket dataPacket = new StreamResponsePacket(getStreamId(), payload); - return this.getChannel().write(dataPacket); - } + StreamResponsePacket dataPacket = new StreamResponsePacket(getStreamId(), payload); + return this.getChannel().write(dataPacket); + } - public ChannelFuture sendCreateSuccess() { - assertState(StreamChannelStateCode.RUN); + public ChannelFuture sendCreateSuccess() { + assertState(StreamChannelStateCode.RUN); - StreamCreateSuccessPacket packet = new StreamCreateSuccessPacket(getStreamId()); - return this.getChannel().write(packet); - } + StreamCreateSuccessPacket packet = new StreamCreateSuccessPacket(getStreamId()); + return this.getChannel().write(packet); + } - boolean changeStateOpenArrived() { - boolean result = getState().changeStateOpenArrived(); + boolean changeStateOpenArrived() { + boolean result = getState().changeStateOpenArrived(); - logger.info(makeStateChangeMessage(StreamChannelStateCode.OPEN_ARRIVED, result)); - return result; - } + logger.info(makeStateChangeMessage(StreamChannelStateCode.OPEN_ARRIVED, result)); + return result; + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ServerStreamChannelContext.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ServerStreamChannelContext.java index cf22a1f52..90df3ec3c 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ServerStreamChannelContext.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ServerStreamChannelContext.java @@ -21,15 +21,15 @@ package com.navercorp.pinpoint.rpc.stream; */ public class ServerStreamChannelContext extends StreamChannelContext { - private ServerStreamChannel streamChannel; - - public ServerStreamChannelContext(ServerStreamChannel streamChannel) { - this.streamChannel = streamChannel; - } + private ServerStreamChannel streamChannel; - @Override - public ServerStreamChannel getStreamChannel() { - return streamChannel; - } + public ServerStreamChannelContext(ServerStreamChannel streamChannel) { + this.streamChannel = streamChannel; + } + + @Override + public ServerStreamChannel getStreamChannel() { + return streamChannel; + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ServerStreamChannelMessageListener.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ServerStreamChannelMessageListener.java index 94f8f6716..2f1333e80 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ServerStreamChannelMessageListener.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/ServerStreamChannelMessageListener.java @@ -24,8 +24,8 @@ import com.navercorp.pinpoint.rpc.packet.stream.StreamCreatePacket; */ public interface ServerStreamChannelMessageListener { - short handleStreamCreate(ServerStreamChannelContext streamChannelContext, StreamCreatePacket packet); + short handleStreamCreate(ServerStreamChannelContext streamChannelContext, StreamCreatePacket packet); - void handleStreamClose(ServerStreamChannelContext streamChannelContext, StreamClosePacket packet); + void handleStreamClose(ServerStreamChannelContext streamChannelContext, StreamClosePacket packet); } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/StreamChannelContext.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/StreamChannelContext.java index b61e428f3..f17c72500 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/StreamChannelContext.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/StreamChannelContext.java @@ -23,36 +23,36 @@ import java.util.concurrent.ConcurrentHashMap; */ public abstract class StreamChannelContext { - private final ConcurrentHashMap attribute = new ConcurrentHashMap(); + private final ConcurrentHashMap attribute = new ConcurrentHashMap(); - public StreamChannelContext() { - } + public StreamChannelContext() { + } - abstract public StreamChannel getStreamChannel(); + abstract public StreamChannel getStreamChannel(); - public int getStreamId() { - return getStreamChannel().getStreamId(); - } + public int getStreamId() { + return getStreamChannel().getStreamId(); + } - public final Object getAttribute(String key) { - return attribute.get(key); - } + public final Object getAttribute(String key) { + return attribute.get(key); + } - public final Object setAttributeIfAbsent(String key, Object value) { - return attribute.putIfAbsent(key, value); - } + public final Object setAttributeIfAbsent(String key, Object value) { + return attribute.putIfAbsent(key, value); + } - public final Object removeAttribute(String key) { - return attribute.remove(key); - } - - public boolean isServer() { - return getStreamChannel().isServer(); - } - - @Override - public String toString() { - return getStreamChannel().toString(); - } + public final Object removeAttribute(String key) { + return attribute.remove(key); + } + + public boolean isServer() { + return getStreamChannel().isServer(); + } + + @Override + public String toString() { + return getStreamChannel().toString(); + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/StreamChannelManager.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/StreamChannelManager.java index fefb4db8a..54d397dde 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/StreamChannelManager.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/StreamChannelManager.java @@ -43,286 +43,286 @@ import com.navercorp.pinpoint.rpc.util.IDGenerator; */ public class StreamChannelManager { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final Channel channel; + private final Channel channel; - private final IDGenerator idGenerator; + private final IDGenerator idGenerator; - private final ServerStreamChannelMessageListener streamChannelMessageListener; + private final ServerStreamChannelMessageListener streamChannelMessageListener; - private final ConcurrentMap channelMap = new ConcurrentHashMap(); + private final ConcurrentMap channelMap = new ConcurrentHashMap(); - public StreamChannelManager(Channel channel, IDGenerator idGenerator) { - this(channel, idGenerator, DisabledServerStreamChannelMessageListener.INSTANCE); - } + public StreamChannelManager(Channel channel, IDGenerator idGenerator) { + this(channel, idGenerator, DisabledServerStreamChannelMessageListener.INSTANCE); + } - public StreamChannelManager(Channel channel, IDGenerator idGenerator, ServerStreamChannelMessageListener serverStreamChannelMessageListener) { - AssertUtils.assertNotNull(channel, "Channel may not be null."); - AssertUtils.assertNotNull(idGenerator, "IDGenerator may not be null."); - AssertUtils.assertNotNull(serverStreamChannelMessageListener, "ServerStreamChannelMessageListener may not be null."); - - this.channel = channel; - this.idGenerator = idGenerator; - this.streamChannelMessageListener = serverStreamChannelMessageListener; - } - - public void close() { - Set keySet = channelMap.keySet(); - - for (Integer key : keySet) { - clearResourceAndSendClose(key, BasicStreamPacket.CHANNEL_CLOSE); - } - - } + public StreamChannelManager(Channel channel, IDGenerator idGenerator, ServerStreamChannelMessageListener serverStreamChannelMessageListener) { + AssertUtils.assertNotNull(channel, "Channel may not be null."); + AssertUtils.assertNotNull(idGenerator, "IDGenerator may not be null."); + AssertUtils.assertNotNull(serverStreamChannelMessageListener, "ServerStreamChannelMessageListener may not be null."); - public ClientStreamChannelContext openStreamChannel(byte[] payload, ClientStreamChannelMessageListener clientStreamChannelMessageListener) { - logger.info("Open streamChannel initialization started. Channel:{} ", channel); + this.channel = channel; + this.idGenerator = idGenerator; + this.streamChannelMessageListener = serverStreamChannelMessageListener; + } - final int streamChannelId = idGenerator.generate(); + public void close() { + Set keySet = channelMap.keySet(); - ClientStreamChannel newStreamChannel = new ClientStreamChannel(channel, streamChannelId, this); - newStreamChannel.changeStateOpen(); + for (Integer key : keySet) { + clearResourceAndSendClose(key, BasicStreamPacket.CHANNEL_CLOSE); + } - ClientStreamChannelContext newStreamChannelContext = new ClientStreamChannelContext(newStreamChannel, clientStreamChannelMessageListener); + } - StreamChannelContext old = channelMap.put(streamChannelId, newStreamChannelContext); - if (old != null) { - throw new PinpointSocketException("already streamChannelId exist:" + streamChannelId + " streamChannel:" + old); - } + public ClientStreamChannelContext openStreamChannel(byte[] payload, ClientStreamChannelMessageListener clientStreamChannelMessageListener) { + logger.info("Open streamChannel initialization started. Channel:{} ", channel); - // the order of below code is very important. - newStreamChannel.changeStateOpenAwait(); - newStreamChannel.sendCreate(payload); + final int streamChannelId = idGenerator.generate(); - newStreamChannel.awaitOpen(3000); + ClientStreamChannel newStreamChannel = new ClientStreamChannel(channel, streamChannelId, this); + newStreamChannel.changeStateOpen(); - if (newStreamChannel.checkState(StreamChannelStateCode.RUN)) { - logger.info("Open streamChannel initialization completed. Channel:{}, StreamChnnelContext:{} ", channel, newStreamChannelContext); - return newStreamChannelContext; - } else { - newStreamChannel.changeStateClose(); - channelMap.remove(streamChannelId); + ClientStreamChannelContext newStreamChannelContext = new ClientStreamChannelContext(newStreamChannel, clientStreamChannelMessageListener); - throw new PinpointSocketException("Create StreamChannel failed.(channel:" + channel + ", StreamChannelId:" + streamChannelId + ")"); - } - } + StreamChannelContext old = channelMap.put(streamChannelId, newStreamChannelContext); + if (old != null) { + throw new PinpointSocketException("already streamChannelId exist:" + streamChannelId + " streamChannel:" + old); + } - public void messageReceived(StreamPacket packet) { - final int streamChannelId = packet.getStreamChannelId(); - final short packetType = packet.getPacketType(); + // the order of below code is very important. + newStreamChannel.changeStateOpenAwait(); + newStreamChannel.sendCreate(payload); - logger.info("StreamChannel message received. (Channel:{}, StreamId:{}, Packet:{}).", channel, streamChannelId, packet); + newStreamChannel.awaitOpen(3000); - if (PacketType.APPLICATION_STREAM_CREATE == packetType) { - handleCreate((StreamCreatePacket) packet); - return; - } + if (newStreamChannel.checkState(StreamChannelStateCode.RUN)) { + logger.info("Open streamChannel initialization completed. Channel:{}, StreamChnnelContext:{} ", channel, newStreamChannelContext); + return newStreamChannelContext; + } else { + newStreamChannel.changeStateClose(); + channelMap.remove(streamChannelId); - StreamChannelContext context = findStreamChannel(streamChannelId); - if (context == null) { - if (!(PacketType.APPLICATION_STREAM_CLOSE == packetType)) { - clearResourceAndSendClose(streamChannelId, StreamClosePacket.ID_NOT_FOUND); - } - } else { - if (isServerStreamChannelContext(context)) { - messageReceived((ServerStreamChannelContext) context, packet); - } else if (isClientStreamChannelContext(context)) { - messageReceived((ClientStreamChannelContext) context, packet); - } else { - clearResourceAndSendClose(streamChannelId, StreamClosePacket.TYPE_UNKOWN); - } - } - } + throw new PinpointSocketException("Create StreamChannel failed.(channel:" + channel + ", StreamChannelId:" + streamChannelId + ")"); + } + } - private void messageReceived(ServerStreamChannelContext context, StreamPacket packet) { - final short packetType = packet.getPacketType(); - final int streamChannelId = packet.getStreamChannelId(); + public void messageReceived(StreamPacket packet) { + final int streamChannelId = packet.getStreamChannelId(); + final short packetType = packet.getPacketType(); - switch (packetType) { - case PacketType.APPLICATION_STREAM_CLOSE: - handleStreamClose(context, (StreamClosePacket)packet); - break; - case PacketType.APPLICATION_STREAM_PING: - handlePing(context, (StreamPingPacket) packet); - break; - case PacketType.APPLICATION_STREAM_PONG: - // handlePong((StreamPongPacket) packet); - break; - default: - clearResourceAndSendClose(streamChannelId, StreamClosePacket.PACKET_UNKNOWN); - logger.info("Unkown StreamPacket received Channel:{}, StreamId:{}, Packet;{}.", channel, streamChannelId, packet); - } - } + logger.info("StreamChannel message received. (Channel:{}, StreamId:{}, Packet:{}).", channel, streamChannelId, packet); - private void messageReceived(ClientStreamChannelContext context, StreamPacket packet) { - final short packetType = packet.getPacketType(); - final int streamChannelId = packet.getStreamChannelId(); + if (PacketType.APPLICATION_STREAM_CREATE == packetType) { + handleCreate((StreamCreatePacket) packet); + return; + } - switch (packetType) { - case PacketType.APPLICATION_STREAM_CREATE_SUCCESS: - handleCreateSuccess(context, (StreamCreateSuccessPacket) packet); - break; - case PacketType.APPLICATION_STREAM_CREATE_FAIL: - handleCreateFail(context, (StreamCreateFailPacket) packet); - break; - case PacketType.APPLICATION_STREAM_RESPONSE: - handleStreamResponse(context, (StreamResponsePacket) packet); - break; - case PacketType.APPLICATION_STREAM_CLOSE: - handleStreamClose(context, (StreamClosePacket) packet); - break; - case PacketType.APPLICATION_STREAM_PING: - handlePing(context, (StreamPingPacket) packet); - break; - case PacketType.APPLICATION_STREAM_PONG: - // handlePong((StreamPongPacket) packet); - break; - default: - clearResourceAndSendClose(streamChannelId, StreamClosePacket.PACKET_UNKNOWN); - logger.info("Unkown StreamPacket received Channel:{}, StreamId:{}, Packet;{}.", channel, streamChannelId, packet); - } - } + StreamChannelContext context = findStreamChannel(streamChannelId); + if (context == null) { + if (!(PacketType.APPLICATION_STREAM_CLOSE == packetType)) { + clearResourceAndSendClose(streamChannelId, StreamClosePacket.ID_NOT_FOUND); + } + } else { + if (isServerStreamChannelContext(context)) { + messageReceived((ServerStreamChannelContext) context, packet); + } else if (isClientStreamChannelContext(context)) { + messageReceived((ClientStreamChannelContext) context, packet); + } else { + clearResourceAndSendClose(streamChannelId, StreamClosePacket.TYPE_UNKOWN); + } + } + } - private void handleCreate(StreamCreatePacket packet) { - final int streamChannelId = packet.getStreamChannelId(); + private void messageReceived(ServerStreamChannelContext context, StreamPacket packet) { + final short packetType = packet.getPacketType(); + final int streamChannelId = packet.getStreamChannelId(); - short code = BasicStreamPacket.SUCCESS; - ServerStreamChannel streamChannel = new ServerStreamChannel(this.channel, streamChannelId, this); - ServerStreamChannelContext streamChannelContext = new ServerStreamChannelContext(streamChannel); + switch (packetType) { + case PacketType.APPLICATION_STREAM_CLOSE: + handleStreamClose(context, (StreamClosePacket)packet); + break; + case PacketType.APPLICATION_STREAM_PING: + handlePing(context, (StreamPingPacket) packet); + break; + case PacketType.APPLICATION_STREAM_PONG: + // handlePong((StreamPongPacket) packet); + break; + default: + clearResourceAndSendClose(streamChannelId, StreamClosePacket.PACKET_UNKNOWN); + logger.info("Unkown StreamPacket received Channel:{}, StreamId:{}, Packet;{}.", channel, streamChannelId, packet); + } + } - code = registerStreamChannel(streamChannelContext); + private void messageReceived(ClientStreamChannelContext context, StreamPacket packet) { + final short packetType = packet.getPacketType(); + final int streamChannelId = packet.getStreamChannelId(); - if (code == BasicStreamPacket.SUCCESS) { - code = streamChannelMessageListener.handleStreamCreate(streamChannelContext, (StreamCreatePacket) packet); + switch (packetType) { + case PacketType.APPLICATION_STREAM_CREATE_SUCCESS: + handleCreateSuccess(context, (StreamCreateSuccessPacket) packet); + break; + case PacketType.APPLICATION_STREAM_CREATE_FAIL: + handleCreateFail(context, (StreamCreateFailPacket) packet); + break; + case PacketType.APPLICATION_STREAM_RESPONSE: + handleStreamResponse(context, (StreamResponsePacket) packet); + break; + case PacketType.APPLICATION_STREAM_CLOSE: + handleStreamClose(context, (StreamClosePacket) packet); + break; + case PacketType.APPLICATION_STREAM_PING: + handlePing(context, (StreamPingPacket) packet); + break; + case PacketType.APPLICATION_STREAM_PONG: + // handlePong((StreamPongPacket) packet); + break; + default: + clearResourceAndSendClose(streamChannelId, StreamClosePacket.PACKET_UNKNOWN); + logger.info("Unkown StreamPacket received Channel:{}, StreamId:{}, Packet;{}.", channel, streamChannelId, packet); + } + } - if (code == 0) { - streamChannel.changeStateRun(); - streamChannel.sendCreateSuccess(); - } - } + private void handleCreate(StreamCreatePacket packet) { + final int streamChannelId = packet.getStreamChannelId(); - if (code != 0) { - clearResourceAndSendCreateFail(streamChannelId, code); - } - } + short code = BasicStreamPacket.SUCCESS; + ServerStreamChannel streamChannel = new ServerStreamChannel(this.channel, streamChannelId, this); + ServerStreamChannelContext streamChannelContext = new ServerStreamChannelContext(streamChannel); - private short registerStreamChannel(ServerStreamChannelContext streamChannelContext) { - int streamChannelId = streamChannelContext.getStreamId(); - ServerStreamChannel streamChannel = streamChannelContext.getStreamChannel(); + code = registerStreamChannel(streamChannelContext); - if (channelMap.putIfAbsent(streamChannelId, streamChannelContext) != null) { - streamChannel.changeStateClose(); - return StreamCreateFailPacket.ID_DUPLICATED; - } + if (code == BasicStreamPacket.SUCCESS) { + code = streamChannelMessageListener.handleStreamCreate(streamChannelContext, (StreamCreatePacket) packet); - if (!streamChannel.changeStateOpenArrived()) { - streamChannel.changeStateClose(); - channelMap.remove(streamChannelId); + if (code == 0) { + streamChannel.changeStateRun(); + streamChannel.sendCreateSuccess(); + } + } - return StreamCreateFailPacket.STATE_ILLEGAL; - } + if (code != 0) { + clearResourceAndSendCreateFail(streamChannelId, code); + } + } - return BasicStreamPacket.SUCCESS; - } + private short registerStreamChannel(ServerStreamChannelContext streamChannelContext) { + int streamChannelId = streamChannelContext.getStreamId(); + ServerStreamChannel streamChannel = streamChannelContext.getStreamChannel(); - private void handleCreateSuccess(ClientStreamChannelContext streamChannelContext, StreamCreateSuccessPacket packet) { - StreamChannel streamChannel = streamChannelContext.getStreamChannel(); - streamChannel.changeStateRun(); - } + if (channelMap.putIfAbsent(streamChannelId, streamChannelContext) != null) { + streamChannel.changeStateClose(); + return StreamCreateFailPacket.ID_DUPLICATED; + } - private void handleCreateFail(ClientStreamChannelContext streamChannelContext, StreamCreateFailPacket packet) { - clearStreamChannelResource(streamChannelContext.getStreamId()); - } + if (!streamChannel.changeStateOpenArrived()) { + streamChannel.changeStateClose(); + channelMap.remove(streamChannelId); - private void handleStreamResponse(ClientStreamChannelContext context, StreamResponsePacket packet) { - int streamChannelId = packet.getStreamChannelId(); + return StreamCreateFailPacket.STATE_ILLEGAL; + } - StreamChannel streamChannel = context.getStreamChannel(); + return BasicStreamPacket.SUCCESS; + } - StreamChannelStateCode currentCode = streamChannel.getCurrentState(); - - if (StreamChannelStateCode.RUN == currentCode) { - context.getClientStreamChannelMessageListener().handleStreamData(context, packet); - } else if (StreamChannelStateCode.OPEN_AWAIT == currentCode) { - // may happen in the timing - } else { - clearResourceAndSendClose(streamChannelId, StreamClosePacket.STATE_NOT_RUN); - } - } + private void handleCreateSuccess(ClientStreamChannelContext streamChannelContext, StreamCreateSuccessPacket packet) { + StreamChannel streamChannel = streamChannelContext.getStreamChannel(); + streamChannel.changeStateRun(); + } - private void handleStreamClose(ClientStreamChannelContext context, StreamClosePacket packet) { - context.getClientStreamChannelMessageListener().handleStreamClose(context, (StreamClosePacket) packet); - clearStreamChannelResource(context.getStreamId()); - } - - private void handleStreamClose(ServerStreamChannelContext context, StreamClosePacket packet) { - streamChannelMessageListener.handleStreamClose(context, packet); - clearStreamChannelResource(context.getStreamId()); - } + private void handleCreateFail(ClientStreamChannelContext streamChannelContext, StreamCreateFailPacket packet) { + clearStreamChannelResource(streamChannelContext.getStreamId()); + } - private void handlePing(StreamChannelContext streamChannelContext, StreamPingPacket packet) { - int streamChannelId = packet.getStreamChannelId(); + private void handleStreamResponse(ClientStreamChannelContext context, StreamResponsePacket packet) { + int streamChannelId = packet.getStreamChannelId(); - StreamChannel streamChannel = streamChannelContext.getStreamChannel(); - if (!streamChannel.checkState(StreamChannelStateCode.RUN)) { - clearResourceAndSendClose(streamChannelId, StreamClosePacket.STATE_NOT_RUN); - return; - } + StreamChannel streamChannel = context.getStreamChannel(); - streamChannel.sendPong(packet.getRequestId()); - } + StreamChannelStateCode currentCode = streamChannel.getCurrentState(); - public StreamChannelContext findStreamChannel(int channelId) { - StreamChannelContext streamChannelContext = this.channelMap.get(channelId); + if (StreamChannelStateCode.RUN == currentCode) { + context.getClientStreamChannelMessageListener().handleStreamData(context, packet); + } else if (StreamChannelStateCode.OPEN_AWAIT == currentCode) { + // may happen in the timing + } else { + clearResourceAndSendClose(streamChannelId, StreamClosePacket.STATE_NOT_RUN); + } + } - return streamChannelContext; - } + private void handleStreamClose(ClientStreamChannelContext context, StreamClosePacket packet) { + context.getClientStreamChannelMessageListener().handleStreamClose(context, (StreamClosePacket) packet); + clearStreamChannelResource(context.getStreamId()); + } - private ChannelFuture clearResourceAndSendCreateFail(int streamChannelId, short code) { - clearStreamChannelResource(streamChannelId); - return sendCreateFail(streamChannelId, code); - } + private void handleStreamClose(ServerStreamChannelContext context, StreamClosePacket packet) { + streamChannelMessageListener.handleStreamClose(context, packet); + clearStreamChannelResource(context.getStreamId()); + } - protected ChannelFuture clearResourceAndSendClose(int streamChannelId, short code) { - clearStreamChannelResource(streamChannelId); - return sendClose(streamChannelId, code); - } + private void handlePing(StreamChannelContext streamChannelContext, StreamPingPacket packet) { + int streamChannelId = packet.getStreamChannelId(); - private void clearStreamChannelResource(int streamId) { - StreamChannelContext streamChannelContext = channelMap.remove(streamId); + StreamChannel streamChannel = streamChannelContext.getStreamChannel(); + if (!streamChannel.checkState(StreamChannelStateCode.RUN)) { + clearResourceAndSendClose(streamChannelId, StreamClosePacket.STATE_NOT_RUN); + return; + } - if (streamChannelContext != null) { - streamChannelContext.getStreamChannel().changeStateClose(); - } - } + streamChannel.sendPong(packet.getRequestId()); + } - private ChannelFuture sendCreateFail(int streamChannelId, short code) { - StreamCreateFailPacket packet = new StreamCreateFailPacket(streamChannelId, code); - return this.channel.write(packet); - } + public StreamChannelContext findStreamChannel(int channelId) { + StreamChannelContext streamChannelContext = this.channelMap.get(channelId); - private ChannelFuture sendClose(int streamChannelId, short code) { - StreamClosePacket packet = new StreamClosePacket(streamChannelId, code); - return this.channel.write(packet); - } + return streamChannelContext; + } - private boolean isServerStreamChannelContext(StreamChannelContext context) { - if (context == null || !(context instanceof ServerStreamChannelContext)) { - return false; - } - return true; - } + private ChannelFuture clearResourceAndSendCreateFail(int streamChannelId, short code) { + clearStreamChannelResource(streamChannelId); + return sendCreateFail(streamChannelId, code); + } - private boolean isClientStreamChannelContext(StreamChannelContext context) { - if (context == null || !(context instanceof ClientStreamChannelContext)) { - return false; - } - return true; - } + protected ChannelFuture clearResourceAndSendClose(int streamChannelId, short code) { + clearStreamChannelResource(streamChannelId); + return sendClose(streamChannelId, code); + } - public boolean isSupportServerMode() { - return streamChannelMessageListener != DisabledServerStreamChannelMessageListener.INSTANCE; - } + private void clearStreamChannelResource(int streamId) { + StreamChannelContext streamChannelContext = channelMap.remove(streamId); + + if (streamChannelContext != null) { + streamChannelContext.getStreamChannel().changeStateClose(); + } + } + + private ChannelFuture sendCreateFail(int streamChannelId, short code) { + StreamCreateFailPacket packet = new StreamCreateFailPacket(streamChannelId, code); + return this.channel.write(packet); + } + + private ChannelFuture sendClose(int streamChannelId, short code) { + StreamClosePacket packet = new StreamClosePacket(streamChannelId, code); + return this.channel.write(packet); + } + + private boolean isServerStreamChannelContext(StreamChannelContext context) { + if (context == null || !(context instanceof ServerStreamChannelContext)) { + return false; + } + return true; + } + + private boolean isClientStreamChannelContext(StreamChannelContext context) { + if (context == null || !(context instanceof ClientStreamChannelContext)) { + return false; + } + return true; + } + + public boolean isSupportServerMode() { + return streamChannelMessageListener != DisabledServerStreamChannelMessageListener.INSTANCE; + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/StreamChannelState.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/StreamChannelState.java index 9a5441845..f28399d51 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/StreamChannelState.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/StreamChannelState.java @@ -23,63 +23,63 @@ import java.util.concurrent.atomic.AtomicReference; */ public class StreamChannelState { - private final AtomicReference currentStateRefernce = new AtomicReference(); + private final AtomicReference currentStateRefernce = new AtomicReference(); - public StreamChannelState() { - currentStateRefernce.set(StreamChannelStateCode.NEW); - } + public StreamChannelState() { + currentStateRefernce.set(StreamChannelStateCode.NEW); + } - public boolean changeStateOpen() { - boolean result = currentStateRefernce.compareAndSet(StreamChannelStateCode.NEW, StreamChannelStateCode.OPEN); - if (!result) { - changeStateIllegal(); - } - return result; - } + public boolean changeStateOpen() { + boolean result = currentStateRefernce.compareAndSet(StreamChannelStateCode.NEW, StreamChannelStateCode.OPEN); + if (!result) { + changeStateIllegal(); + } + return result; + } - public boolean changeStateOpenAwait() { - boolean result = currentStateRefernce.compareAndSet(StreamChannelStateCode.OPEN, StreamChannelStateCode.OPEN_AWAIT); - if (!result) { - changeStateIllegal(); - } - return result; - } + public boolean changeStateOpenAwait() { + boolean result = currentStateRefernce.compareAndSet(StreamChannelStateCode.OPEN, StreamChannelStateCode.OPEN_AWAIT); + if (!result) { + changeStateIllegal(); + } + return result; + } - public boolean changeStateOpenArrived() { - boolean result = currentStateRefernce.compareAndSet(StreamChannelStateCode.NEW, StreamChannelStateCode.OPEN_ARRIVED); - if (!result) { - changeStateIllegal(); - } - return result; - } + public boolean changeStateOpenArrived() { + boolean result = currentStateRefernce.compareAndSet(StreamChannelStateCode.NEW, StreamChannelStateCode.OPEN_ARRIVED); + if (!result) { + changeStateIllegal(); + } + return result; + } - public boolean changeStateRun() { - StreamChannelStateCode currentState = this.currentStateRefernce.get(); - - StreamChannelStateCode nextState = StreamChannelStateCode.RUN; - if (!nextState.canChangeState(currentState)) { - changeStateIllegal(); - return false; - } + public boolean changeStateRun() { + StreamChannelStateCode currentState = this.currentStateRefernce.get(); - return currentStateRefernce.compareAndSet(currentState, StreamChannelStateCode.RUN); - } + StreamChannelStateCode nextState = StreamChannelStateCode.RUN; + if (!nextState.canChangeState(currentState)) { + changeStateIllegal(); + return false; + } - public boolean changeStateClose() { - if (currentStateRefernce.get() == StreamChannelStateCode.CLOSED) { - return false; - } - - currentStateRefernce.set(StreamChannelStateCode.CLOSED); - return true; - } - - private void changeStateIllegal() { - currentStateRefernce.set(StreamChannelStateCode.ILLEGAL_STATE); - } + return currentStateRefernce.compareAndSet(currentState, StreamChannelStateCode.RUN); + } + + public boolean changeStateClose() { + if (currentStateRefernce.get() == StreamChannelStateCode.CLOSED) { + return false; + } + + currentStateRefernce.set(StreamChannelStateCode.CLOSED); + return true; + } + + private void changeStateIllegal() { + currentStateRefernce.set(StreamChannelStateCode.ILLEGAL_STATE); + } + + public StreamChannelStateCode getCurrentState() { + return currentStateRefernce.get(); + } - public StreamChannelStateCode getCurrentState() { - return currentStateRefernce.get(); - } - } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/StreamChannelStateCode.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/StreamChannelStateCode.java index 58c90003f..387be9065 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/StreamChannelStateCode.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/StreamChannelStateCode.java @@ -25,30 +25,30 @@ import java.util.Set; */ public enum StreamChannelStateCode { - NEW, - OPEN(NEW), - OPEN_AWAIT(OPEN), - OPEN_ARRIVED(OPEN), - RUN(OPEN_AWAIT, OPEN_ARRIVED), - CLOSED(OPEN_AWAIT, OPEN_ARRIVED, RUN), - ILLEGAL_STATE(NEW, OPEN, OPEN_AWAIT, OPEN_ARRIVED, RUN, CLOSED); + NEW, + OPEN(NEW), + OPEN_AWAIT(OPEN), + OPEN_ARRIVED(OPEN), + RUN(OPEN_AWAIT, OPEN_ARRIVED), + CLOSED(OPEN_AWAIT, OPEN_ARRIVED, RUN), + ILLEGAL_STATE(NEW, OPEN, OPEN_AWAIT, OPEN_ARRIVED, RUN, CLOSED); - private final Set validBeforeStateSet; + private final Set validBeforeStateSet; - private StreamChannelStateCode(StreamChannelStateCode... validBeforeStates) { - this.validBeforeStateSet = new HashSet(); + private StreamChannelStateCode(StreamChannelStateCode... validBeforeStates) { + this.validBeforeStateSet = new HashSet(); - if (validBeforeStates != null) { + if (validBeforeStates != null) { Collections.addAll(validBeforeStateSet, validBeforeStates); - } - } + } + } - public boolean canChangeState(StreamChannelStateCode currentState) { - if (validBeforeStateSet.contains(currentState)) { - return true; - } + public boolean canChangeState(StreamChannelStateCode currentState) { + if (validBeforeStateSet.contains(currentState)) { + return true; + } - return false; - } + return false; + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/ClassUtils.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/ClassUtils.java index 96914bbab..699560b11 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/ClassUtils.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/ClassUtils.java @@ -40,19 +40,19 @@ import java.util.Map; */ public class ClassUtils { - private static final Map, Class> primitiveWrapperMap = new HashMap, Class>(); - static { - primitiveWrapperMap.put(Boolean.TYPE, Boolean.class); - primitiveWrapperMap.put(Byte.TYPE, Byte.class); - primitiveWrapperMap.put(Character.TYPE, Character.class); - primitiveWrapperMap.put(Short.TYPE, Short.class); - primitiveWrapperMap.put(Integer.TYPE, Integer.class); - primitiveWrapperMap.put(Long.TYPE, Long.class); - primitiveWrapperMap.put(Double.TYPE, Double.class); - primitiveWrapperMap.put(Float.TYPE, Float.class); - primitiveWrapperMap.put(Void.TYPE, Void.TYPE); - } - + private static final Map, Class> primitiveWrapperMap = new HashMap, Class>(); + static { + primitiveWrapperMap.put(Boolean.TYPE, Boolean.class); + primitiveWrapperMap.put(Byte.TYPE, Byte.class); + primitiveWrapperMap.put(Character.TYPE, Character.class); + primitiveWrapperMap.put(Short.TYPE, Short.class); + primitiveWrapperMap.put(Integer.TYPE, Integer.class); + primitiveWrapperMap.put(Long.TYPE, Long.class); + primitiveWrapperMap.put(Double.TYPE, Double.class); + primitiveWrapperMap.put(Float.TYPE, Float.class); + primitiveWrapperMap.put(Void.TYPE, Void.TYPE); + } + private static final Map wrapperPrimitiveMap = new HashMap(); static { for (Object o : primitiveWrapperMap.keySet()) { @@ -97,10 +97,10 @@ public class ClassUtils { * @param toClassArray the array of Classes to try to assign into, may be null * @return true if assignment possible */ - public static boolean isAssignable(Class cls, Class toClass) { - return isAssignable(cls, toClass, true); - } - + public static boolean isAssignable(Class cls, Class toClass) { + return isAssignable(cls, toClass, true); + } + /** *

Checks if an array of Classes can be assigned to another array of Classes.

* @@ -134,66 +134,66 @@ public class ClassUtils { * @return true if assignment possible * @since 2.5 */ - public static boolean isAssignable(Class cls, Class toClass, boolean autoboxing) { - if (toClass == null) { - return false; - } - // have to check for null, as isAssignableFrom doesn't - if (cls == null) { - return !(toClass.isPrimitive()); - } - // autoboxing: - if (autoboxing) { - if (cls.isPrimitive() && !toClass.isPrimitive()) { - cls = primitiveToWrapper(cls); - if (cls == null) { - return false; - } - } - if (toClass.isPrimitive() && !cls.isPrimitive()) { - cls = wrapperToPrimitive(cls); - if (cls == null) { - return false; - } - } - } - if (cls.equals(toClass)) { - return true; - } - if (cls.isPrimitive()) { - if (toClass.isPrimitive() == false) { - return false; - } - if (Integer.TYPE.equals(cls)) { - return Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass); - } - if (Long.TYPE.equals(cls)) { - return Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass); - } - if (Boolean.TYPE.equals(cls)) { - return false; - } - if (Double.TYPE.equals(cls)) { - return false; - } - if (Float.TYPE.equals(cls)) { - return Double.TYPE.equals(toClass); - } - if (Character.TYPE.equals(cls)) { - return Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass); - } - if (Short.TYPE.equals(cls)) { - return Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass); - } - if (Byte.TYPE.equals(cls)) { - return Short.TYPE.equals(toClass) || Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) - || Double.TYPE.equals(toClass); - } - // should never get here - return false; - } - return toClass.isAssignableFrom(cls); - } + public static boolean isAssignable(Class cls, Class toClass, boolean autoboxing) { + if (toClass == null) { + return false; + } + // have to check for null, as isAssignableFrom doesn't + if (cls == null) { + return !(toClass.isPrimitive()); + } + // autoboxing: + if (autoboxing) { + if (cls.isPrimitive() && !toClass.isPrimitive()) { + cls = primitiveToWrapper(cls); + if (cls == null) { + return false; + } + } + if (toClass.isPrimitive() && !cls.isPrimitive()) { + cls = wrapperToPrimitive(cls); + if (cls == null) { + return false; + } + } + } + if (cls.equals(toClass)) { + return true; + } + if (cls.isPrimitive()) { + if (toClass.isPrimitive() == false) { + return false; + } + if (Integer.TYPE.equals(cls)) { + return Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass); + } + if (Long.TYPE.equals(cls)) { + return Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass); + } + if (Boolean.TYPE.equals(cls)) { + return false; + } + if (Double.TYPE.equals(cls)) { + return false; + } + if (Float.TYPE.equals(cls)) { + return Double.TYPE.equals(toClass); + } + if (Character.TYPE.equals(cls)) { + return Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass); + } + if (Short.TYPE.equals(cls)) { + return Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass); + } + if (Byte.TYPE.equals(cls)) { + return Short.TYPE.equals(toClass) || Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) + || Double.TYPE.equals(toClass); + } + // should never get here + return false; + } + return toClass.isAssignableFrom(cls); + } /** *

Converts the specified primitive Class object to its corresponding @@ -207,13 +207,13 @@ public class ClassUtils { * cls is not a primitive. null if null input. * @since 2.1 */ - public static Class primitiveToWrapper(Class cls) { - Class convertedClass = cls; - if (cls != null && cls.isPrimitive()) { - convertedClass = primitiveWrapperMap.get(cls); - } - return convertedClass; - } + public static Class primitiveToWrapper(Class cls) { + Class convertedClass = cls; + if (cls != null && cls.isPrimitive()) { + convertedClass = primitiveWrapperMap.get(cls); + } + return convertedClass; + } /** *

Converts the specified array of primitive Class objects to an array of @@ -225,8 +225,8 @@ public class ClassUtils { * Empty array if an empty array passed in. * @since 2.1 */ - public static Class wrapperToPrimitive(Class cls) { - return wrapperPrimitiveMap.get(cls); - } + public static Class wrapperToPrimitive(Class cls) { + return wrapperPrimitiveMap.get(cls); + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/ControlMessageEncodingUtils.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/ControlMessageEncodingUtils.java index 1f0bacd9e..6441a90d5 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/ControlMessageEncodingUtils.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/ControlMessageEncodingUtils.java @@ -27,18 +27,18 @@ import com.navercorp.pinpoint.rpc.control.ProtocolException; */ public final class ControlMessageEncodingUtils { - private static final ControlMessageEncoder encoder = new ControlMessageEncoder(); - private static final ControlMessageDecoder decoder = new ControlMessageDecoder(); + private static final ControlMessageEncoder encoder = new ControlMessageEncoder(); + private static final ControlMessageDecoder decoder = new ControlMessageDecoder(); - private ControlMessageEncodingUtils() { - } + private ControlMessageEncodingUtils() { + } - public static byte[] encode(Map value) throws ProtocolException { - return encoder.encode(value); - } + public static byte[] encode(Map value) throws ProtocolException { + return encoder.encode(value); + } - public static Object decode(byte[] in) throws ProtocolException { - return decoder.decode(in); - } + public static Object decode(byte[] in) throws ProtocolException { + return decoder.decode(in); + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/CopyUtils.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/CopyUtils.java index 52045494f..4808a3406 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/CopyUtils.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/CopyUtils.java @@ -33,11 +33,11 @@ import java.util.Map; public final class CopyUtils { - private CopyUtils() { - } + private CopyUtils() { + } - public static Map mediumCopyMap(Map original) { - Map result = new LinkedHashMap(); + public static Map mediumCopyMap(Map original) { + Map result = new LinkedHashMap(); for (Map.Entry entry : original.entrySet()) { Object key = entry.getKey(); @@ -45,21 +45,21 @@ public final class CopyUtils { result.put(mediumCopy(key), mediumCopy(value)); } - return result; - } + return result; + } - public static Collection mediumCopyCollection(Collection original) { - return new ArrayList(original); - } + public static Collection mediumCopyCollection(Collection original) { + return new ArrayList(original); + } - private static Object mediumCopy(Object original) { - if (original instanceof Map) { - return mediumCopyMap((Map) original); - } else if (original instanceof Collection) { - return mediumCopyCollection((Collection) original); - } else { - return original; - } - } + private static Object mediumCopy(Object original) { + if (original instanceof Map) { + return mediumCopyMap((Map) original); + } else if (original instanceof Collection) { + return mediumCopyCollection((Collection) original); + } else { + return original; + } + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/IDGenerator.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/IDGenerator.java index 4bd6e9381..5b78574b9 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/IDGenerator.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/IDGenerator.java @@ -23,41 +23,41 @@ import java.util.concurrent.atomic.AtomicInteger; */ public class IDGenerator { - private final AtomicInteger idGenerator; + private final AtomicInteger idGenerator; - private final int gap; + private final int gap; - public IDGenerator() { - this(1, 1); - } + public IDGenerator() { + this(1, 1); + } - public IDGenerator(int startIndex) { - this(startIndex, 1); - } + public IDGenerator(int startIndex) { + this(startIndex, 1); + } - public IDGenerator(int startIndex, int gap) { - AssertUtils.assertTrue(startIndex >= 0, "Startindex must be grater than or equal to 0."); - AssertUtils.assertTrue(gap > 0, "Gap must be grater than 0."); + public IDGenerator(int startIndex, int gap) { + AssertUtils.assertTrue(startIndex >= 0, "Startindex must be grater than or equal to 0."); + AssertUtils.assertTrue(gap > 0, "Gap must be grater than 0."); - this.gap = gap; + this.gap = gap; - this.idGenerator = new AtomicInteger(startIndex); - } + this.idGenerator = new AtomicInteger(startIndex); + } - public int generate() { - return idGenerator.getAndAdd(gap); - } - - public int get() { - return idGenerator.get(); - } + public int generate() { + return idGenerator.getAndAdd(gap); + } - public static IDGenerator createOddIdGenerator() { - return new IDGenerator(1, 2); - } + public int get() { + return idGenerator.get(); + } - public static IDGenerator createEvenIdGenerator() { - return new IDGenerator(2, 2); - } + public static IDGenerator createOddIdGenerator() { + return new IDGenerator(1, 2); + } + + public static IDGenerator createEvenIdGenerator() { + return new IDGenerator(2, 2); + } } diff --git a/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/MapUtils.java b/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/MapUtils.java index b380b9b64..79cf81e0a 100644 --- a/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/MapUtils.java +++ b/rpc/src/main/java/com/navercorp/pinpoint/rpc/util/MapUtils.java @@ -24,43 +24,43 @@ import java.util.Map; */ public final class MapUtils { - private MapUtils() { - } + private MapUtils() { + } - public static String getString(Map map, String key) { - return getString(map, key, null); - } + public static String getString(Map map, String key) { + return getString(map, key, null); + } - public static String getString(Map map, String key, String defaultValue) { - if (map == null) { - return defaultValue; - } - - final Object value = map.get(key); + public static String getString(Map map, String key, String defaultValue) { + if (map == null) { + return defaultValue; + } + + final Object value = map.get(key); if (value instanceof String) { return (String) value; } - return defaultValue; - } - - public static Boolean getBoolean(Map map, String key) { - return getBoolean(map, key, false); - } - - public static Boolean getBoolean(Map map, String key, Boolean defaultValue) { - if (map == null) { - return defaultValue; - } - - final Object value = map.get(key); + return defaultValue; + } + + public static Boolean getBoolean(Map map, String key) { + return getBoolean(map, key, false); + } + + public static Boolean getBoolean(Map map, String key, Boolean defaultValue) { + if (map == null) { + return defaultValue; + } + + final Object value = map.get(key); if (value instanceof Boolean) { return (Boolean) value; } - return defaultValue; - } - + return defaultValue; + } + public static Integer getInteger(Map map, String key) { return getInteger(map, key, null); @@ -80,7 +80,7 @@ public final class MapUtils { } public static Long getLong(Map map, String key) { - return getLong(map, key, null); + return getLong(map, key, null); } public static Long getLong(Map map, String key, Long defaultValue) { diff --git a/rpc/src/test/java/com/navercorp/pinpoint/rpc/FutureTest.java b/rpc/src/test/java/com/navercorp/pinpoint/rpc/FutureTest.java index a9209ec9a..f43cf6444 100644 --- a/rpc/src/test/java/com/navercorp/pinpoint/rpc/FutureTest.java +++ b/rpc/src/test/java/com/navercorp/pinpoint/rpc/FutureTest.java @@ -31,49 +31,49 @@ import com.navercorp.pinpoint.rpc.FutureListener; */ public class FutureTest { - @Test - public void simpleTest1() { - DefaultFuture future = new DefaultFuture(); + @Test + public void simpleTest1() { + DefaultFuture future = new DefaultFuture(); - SimpleListener listener1 = new SimpleListener(); + SimpleListener listener1 = new SimpleListener(); - future.setListener(listener1); -// future.addListener(listener2); + future.setListener(listener1); +// future.addListener(listener2); - Assert.assertFalse(listener1.isFinished()); -// Assert.assertFalse(listener2.isFinished()); + Assert.assertFalse(listener1.isFinished()); +// Assert.assertFalse(listener2.isFinished()); - future.setResult("Hello"); + future.setResult("Hello"); - Assert.assertTrue(listener1.isFinished()); -// Assert.assertTrue(listener2.isFinished()); - } + Assert.assertTrue(listener1.isFinished()); +// Assert.assertTrue(listener2.isFinished()); + } - @Test - public void simpleTest2() { - DefaultFuture future = new DefaultFuture(); + @Test + public void simpleTest2() { + DefaultFuture future = new DefaultFuture(); - SimpleListener listener = new SimpleListener(); + SimpleListener listener = new SimpleListener(); - future.setResult("Hello"); + future.setResult("Hello"); - future.setListener(listener); + future.setListener(listener); - Assert.assertTrue(listener.isFinished()); - } + Assert.assertTrue(listener.isFinished()); + } - static class SimpleListener implements FutureListener { + static class SimpleListener implements FutureListener { - private final AtomicBoolean isFinished = new AtomicBoolean(false); + private final AtomicBoolean isFinished = new AtomicBoolean(false); - @Override - public void onComplete(Future future) { - isFinished.compareAndSet(false, true); - } + @Override + public void onComplete(Future future) { + isFinished.compareAndSet(false, true); + } - public boolean isFinished() { - return isFinished.get(); - } - } + public boolean isFinished() { + return isFinished.get(); + } + } } diff --git a/rpc/src/test/java/com/navercorp/pinpoint/rpc/RecordedStreamChannelMessageListener.java b/rpc/src/test/java/com/navercorp/pinpoint/rpc/RecordedStreamChannelMessageListener.java index 5f814d13c..3bc6074c4 100644 --- a/rpc/src/test/java/com/navercorp/pinpoint/rpc/RecordedStreamChannelMessageListener.java +++ b/rpc/src/test/java/com/navercorp/pinpoint/rpc/RecordedStreamChannelMessageListener.java @@ -44,20 +44,20 @@ public class RecordedStreamChannelMessageListener implements ClientStreamChannel public RecordedStreamChannelMessageListener(int receiveMessageCount) { this.latch = new CountDownLatch(receiveMessageCount); } - - @Override - public void handleStreamData(ClientStreamChannelContext streamChannelContext, StreamResponsePacket packet) { - logger.info("handleStreamData {}, {}", streamChannelContext, packet); + + @Override + public void handleStreamData(ClientStreamChannelContext streamChannelContext, StreamResponsePacket packet) { + logger.info("handleStreamData {}, {}", streamChannelContext, packet); receivedMessageList.add(packet.getPayload()); latch.countDown(); - } + } - @Override - public void handleStreamClose(ClientStreamChannelContext streamChannelContext, StreamClosePacket packet) { + @Override + public void handleStreamClose(ClientStreamChannelContext streamChannelContext, StreamClosePacket packet) { logger.info("handleClose {}, {}", streamChannelContext, packet); receivedMessageList.add(packet.getPayload()); latch.countDown(); - } + } public CountDownLatch getLatch() { return latch; diff --git a/rpc/src/test/java/com/navercorp/pinpoint/rpc/client/PinpointSocketHandlerTest.java b/rpc/src/test/java/com/navercorp/pinpoint/rpc/client/PinpointSocketHandlerTest.java index 394cd3265..62fe70f21 100644 --- a/rpc/src/test/java/com/navercorp/pinpoint/rpc/client/PinpointSocketHandlerTest.java +++ b/rpc/src/test/java/com/navercorp/pinpoint/rpc/client/PinpointSocketHandlerTest.java @@ -18,5 +18,5 @@ package com.navercorp.pinpoint.rpc.client; public class PinpointSocketHandlerTest { - + } 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 350229635..60eed2e19 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 @@ -60,13 +60,13 @@ public class ReconnectTest { try { PinpointSocket socket = pinpointSocketFactory.connect("localhost", 10234); socket.addPinpointSocketReconnectEventListener(new PinpointSocketReconnectEventListener() { - - @Override - public void reconnectPerformed(PinpointSocket socket) { - reconnectPerformed.set(true); - } - - }); + + @Override + public void reconnectPerformed(PinpointSocket socket) { + reconnectPerformed.set(true); + } + + }); serverSocket.close(); logger.info("server.close()---------------------------"); diff --git a/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/AgentHandshakePropertyType.java b/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/AgentHandshakePropertyType.java index 255895c5a..28a8b6ac2 100644 --- a/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/AgentHandshakePropertyType.java +++ b/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/AgentHandshakePropertyType.java @@ -22,52 +22,52 @@ import com.navercorp.pinpoint.rpc.util.ClassUtils; public enum AgentHandshakePropertyType { - SUPPORT_SERVER("supportServer", Boolean.class), + SUPPORT_SERVER("supportServer", Boolean.class), - HOSTNAME("hostName", String.class), - IP("ip", String.class), - AGENT_ID("agentId", String.class), - APPLICATION_NAME("applicationName", String.class), - SERVICE_TYPE("serviceType", Integer.class), - PID("pid", Integer.class), - VERSION("version", String.class), - START_TIMESTAMP("startTimestamp", Long.class); - + HOSTNAME("hostName", String.class), + IP("ip", String.class), + AGENT_ID("agentId", String.class), + APPLICATION_NAME("applicationName", String.class), + SERVICE_TYPE("serviceType", Integer.class), + PID("pid", Integer.class), + VERSION("version", String.class), + START_TIMESTAMP("startTimestamp", Long.class); - private final String name; - private final Class clazzType; - - private AgentHandshakePropertyType(String name, Class clazzType) { - this.name = name; - this.clazzType = clazzType; - } - public String getName() { - return name; - } - - public Class getClazzType() { - return clazzType; - } - - public static boolean hasAllType(Map properties) { - for (AgentHandshakePropertyType type : AgentHandshakePropertyType.values()) { - Object value = properties.get(type.getName()); - - if (type == SUPPORT_SERVER) { - continue; - } + private final String name; + private final Class clazzType; - if (value == null) { - return false; - } - - if (!ClassUtils.isAssignable(value.getClass(), type.getClazzType())) { - return false; - } - } - - return true; - } + private AgentHandshakePropertyType(String name, Class clazzType) { + this.name = name; + this.clazzType = clazzType; + } + + public String getName() { + return name; + } + + public Class getClazzType() { + return clazzType; + } + + public static boolean hasAllType(Map properties) { + for (AgentHandshakePropertyType type : AgentHandshakePropertyType.values()) { + Object value = properties.get(type.getName()); + + if (type == SUPPORT_SERVER) { + continue; + } + + if (value == null) { + return false; + } + + if (!ClassUtils.isAssignable(value.getClass(), type.getClazzType())) { + return false; + } + } + + return true; + } } diff --git a/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/ControlPacketServerTest.java b/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/ControlPacketServerTest.java index c4e8ba986..af6a04673 100644 --- a/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/ControlPacketServerTest.java +++ b/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/ControlPacketServerTest.java @@ -51,240 +51,240 @@ import com.navercorp.pinpoint.rpc.util.MapUtils; */ public class ControlPacketServerTest { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - // Test for being possible to send messages in case of failure of registering packet ( return code : 2, lack of parameter) - @Test - public void registerAgentTest1() throws Exception { - PinpointServerSocket pinpointServerSocket = new PinpointServerSocket(); - pinpointServerSocket.setMessageListener(new SimpleListener()); - pinpointServerSocket.bind("127.0.0.1", 22234); + // Test for being possible to send messages in case of failure of registering packet ( return code : 2, lack of parameter) + @Test + public void registerAgentTest1() throws Exception { + PinpointServerSocket pinpointServerSocket = new PinpointServerSocket(); + pinpointServerSocket.setMessageListener(new SimpleListener()); + pinpointServerSocket.bind("127.0.0.1", 22234); - Socket socket = null; - try { - socket = new Socket("127.0.0.1", 22234); - - sendAndReceiveSimplePacket(socket); - - int code= sendAndReceiveRegisterPacket(socket); - Assert.assertEquals(2, code); + Socket socket = null; + try { + socket = new Socket("127.0.0.1", 22234); - sendAndReceiveSimplePacket(socket); - } finally { - if (socket != null) { - socket.close(); - } + sendAndReceiveSimplePacket(socket); - if (pinpointServerSocket != null) { - pinpointServerSocket.close(); - } - } - } + int code= sendAndReceiveRegisterPacket(socket); + Assert.assertEquals(2, code); - // Test for being possible to send messages in case of success of registering packet ( return code : 0) - @Test - public void registerAgentTest2() throws Exception { - PinpointServerSocket pinpointServerSocket = new PinpointServerSocket(); - pinpointServerSocket.setMessageListener(new SimpleListener()); - pinpointServerSocket.bind("127.0.0.1", 22234); + sendAndReceiveSimplePacket(socket); + } finally { + if (socket != null) { + socket.close(); + } - Socket socket = null; - try { - socket = new Socket("127.0.0.1", 22234); + if (pinpointServerSocket != null) { + pinpointServerSocket.close(); + } + } + } - sendAndReceiveSimplePacket(socket); + // Test for being possible to send messages in case of success of registering packet ( return code : 0) + @Test + public void registerAgentTest2() throws Exception { + PinpointServerSocket pinpointServerSocket = new PinpointServerSocket(); + pinpointServerSocket.setMessageListener(new SimpleListener()); + pinpointServerSocket.bind("127.0.0.1", 22234); - int code= sendAndReceiveRegisterPacket(socket, getParams()); - Assert.assertEquals(0, code); + Socket socket = null; + try { + socket = new Socket("127.0.0.1", 22234); - sendAndReceiveSimplePacket(socket); - } finally { - if (socket != null) { - socket.close(); - } + sendAndReceiveSimplePacket(socket); - if (pinpointServerSocket != null) { - pinpointServerSocket.close(); - } - } - } + int code= sendAndReceiveRegisterPacket(socket, getParams()); + Assert.assertEquals(0, code); - // when failure of registering and retrying to register, confirm to return same code ( return code : 2 - @Test - public void registerAgentTest3() throws Exception { - PinpointServerSocket pinpointServerSocket = new PinpointServerSocket(); - pinpointServerSocket.setMessageListener(new SimpleListener()); - pinpointServerSocket.bind("127.0.0.1", 22234); + sendAndReceiveSimplePacket(socket); + } finally { + if (socket != null) { + socket.close(); + } - Socket socket = null; - try { - socket = new Socket("127.0.0.1", 22234); - int code = sendAndReceiveRegisterPacket(socket); - Assert.assertEquals(2, code); - - code = sendAndReceiveRegisterPacket(socket); - Assert.assertEquals(2, code); - - sendAndReceiveSimplePacket(socket); - } finally { - if (socket != null) { - socket.close(); - } + if (pinpointServerSocket != null) { + pinpointServerSocket.close(); + } + } + } - if (pinpointServerSocket != null) { - pinpointServerSocket.close(); - } - } - } + // when failure of registering and retrying to register, confirm to return same code ( return code : 2 + @Test + public void registerAgentTest3() throws Exception { + PinpointServerSocket pinpointServerSocket = new PinpointServerSocket(); + pinpointServerSocket.setMessageListener(new SimpleListener()); + pinpointServerSocket.bind("127.0.0.1", 22234); - // after success of registering, when success message are sent repeatedly. - // test 1) confirm to return success code, 2) confirm to return already success code. - @Test - public void registerAgentTest4() throws Exception { - PinpointServerSocket pinpointServerSocket = new PinpointServerSocket(); - pinpointServerSocket.setMessageListener(new SimpleListener()); - pinpointServerSocket.bind("127.0.0.1", 22234); + Socket socket = null; + try { + socket = new Socket("127.0.0.1", 22234); + int code = sendAndReceiveRegisterPacket(socket); + Assert.assertEquals(2, code); - Socket socket = null; - try { - socket = new Socket("127.0.0.1", 22234); - sendAndReceiveSimplePacket(socket); + code = sendAndReceiveRegisterPacket(socket); + Assert.assertEquals(2, code); - int code = sendAndReceiveRegisterPacket(socket, getParams()); - Assert.assertEquals(0, code); + sendAndReceiveSimplePacket(socket); + } finally { + if (socket != null) { + socket.close(); + } - sendAndReceiveSimplePacket(socket); + if (pinpointServerSocket != null) { + pinpointServerSocket.close(); + } + } + } - code = sendAndReceiveRegisterPacket(socket, getParams()); - Assert.assertEquals(1, code); + // after success of registering, when success message are sent repeatedly. + // test 1) confirm to return success code, 2) confirm to return already success code. + @Test + public void registerAgentTest4() throws Exception { + PinpointServerSocket pinpointServerSocket = new PinpointServerSocket(); + pinpointServerSocket.setMessageListener(new SimpleListener()); + pinpointServerSocket.bind("127.0.0.1", 22234); - sendAndReceiveSimplePacket(socket); - } finally { - if (socket != null) { - socket.close(); - } + Socket socket = null; + try { + socket = new Socket("127.0.0.1", 22234); + sendAndReceiveSimplePacket(socket); - if (pinpointServerSocket != null) { - pinpointServerSocket.close(); - } - } - } + int code = sendAndReceiveRegisterPacket(socket, getParams()); + Assert.assertEquals(0, code); - - private int sendAndReceiveRegisterPacket(Socket socket) throws ProtocolException, IOException { - return sendAndReceiveRegisterPacket(socket, Collections.EMPTY_MAP); - } + sendAndReceiveSimplePacket(socket); - private int sendAndReceiveRegisterPacket(Socket socket, Map properties) throws ProtocolException, IOException { - sendRegisterPacket(socket.getOutputStream(), properties); - ControlHandshakeResponsePacket packet = receiveRegisterConfirmPacket(socket.getInputStream()); - Map result = (Map) ControlMessageEncodingUtils.decode(packet.getPayload()); - - return MapUtils.getInteger(result, "code", -1); - } + code = sendAndReceiveRegisterPacket(socket, getParams()); + Assert.assertEquals(1, code); - private void sendAndReceiveSimplePacket(Socket socket) throws ProtocolException, IOException { - sendSimpleRequestPacket(socket.getOutputStream()); - ResponsePacket responsePacket = readSimpleResponsePacket(socket.getInputStream()); - Assert.assertNotNull(responsePacket); - } + sendAndReceiveSimplePacket(socket); + } finally { + if (socket != null) { + socket.close(); + } - private void sendRegisterPacket(OutputStream outputStream, Map properties) throws ProtocolException, IOException { - byte[] payload = ControlMessageEncodingUtils.encode(properties); - ControlHandshakePacket packet = new ControlHandshakePacket(1, payload); + if (pinpointServerSocket != null) { + pinpointServerSocket.close(); + } + } + } - ByteBuffer bb = packet.toBuffer().toByteBuffer(0, packet.toBuffer().writerIndex()); - sendData(outputStream, bb.array()); - } - private void sendSimpleRequestPacket(OutputStream outputStream) throws ProtocolException, IOException { - RequestPacket packet = new RequestPacket(new byte[0]); - packet.setRequestId(10); + private int sendAndReceiveRegisterPacket(Socket socket) throws ProtocolException, IOException { + return sendAndReceiveRegisterPacket(socket, Collections.EMPTY_MAP); + } - ByteBuffer bb = packet.toBuffer().toByteBuffer(0, packet.toBuffer().writerIndex()); - sendData(outputStream, bb.array()); - } + private int sendAndReceiveRegisterPacket(Socket socket, Map properties) throws ProtocolException, IOException { + sendRegisterPacket(socket.getOutputStream(), properties); + ControlHandshakeResponsePacket packet = receiveRegisterConfirmPacket(socket.getInputStream()); + Map result = (Map) ControlMessageEncodingUtils.decode(packet.getPayload()); - private void sendData(OutputStream outputStream, byte[] payload) throws IOException { - outputStream.write(payload); - outputStream.flush(); - } + return MapUtils.getInteger(result, "code", -1); + } - private ControlHandshakeResponsePacket receiveRegisterConfirmPacket(InputStream inputStream) throws ProtocolException, IOException { + private void sendAndReceiveSimplePacket(Socket socket) throws ProtocolException, IOException { + sendSimpleRequestPacket(socket.getOutputStream()); + ResponsePacket responsePacket = readSimpleResponsePacket(socket.getInputStream()); + Assert.assertNotNull(responsePacket); + } - byte[] payload = readData(inputStream); - ChannelBuffer cb = ChannelBuffers.wrappedBuffer(payload); + private void sendRegisterPacket(OutputStream outputStream, Map properties) throws ProtocolException, IOException { + byte[] payload = ControlMessageEncodingUtils.encode(properties); + ControlHandshakePacket packet = new ControlHandshakePacket(1, payload); - short packetType = cb.readShort(); + ByteBuffer bb = packet.toBuffer().toByteBuffer(0, packet.toBuffer().writerIndex()); + sendData(outputStream, bb.array()); + } - ControlHandshakeResponsePacket packet = ControlHandshakeResponsePacket.readBuffer(packetType, cb); - return packet; - } + private void sendSimpleRequestPacket(OutputStream outputStream) throws ProtocolException, IOException { + RequestPacket packet = new RequestPacket(new byte[0]); + packet.setRequestId(10); - private ResponsePacket readSimpleResponsePacket(InputStream inputStream) throws ProtocolException, IOException { - byte[] payload = readData(inputStream); - ChannelBuffer cb = ChannelBuffers.wrappedBuffer(payload); + ByteBuffer bb = packet.toBuffer().toByteBuffer(0, packet.toBuffer().writerIndex()); + sendData(outputStream, bb.array()); + } - short packetType = cb.readShort(); + private void sendData(OutputStream outputStream, byte[] payload) throws IOException { + outputStream.write(payload); + outputStream.flush(); + } - ResponsePacket packet = ResponsePacket.readBuffer(packetType, cb); - return packet; - } + private ControlHandshakeResponsePacket receiveRegisterConfirmPacket(InputStream inputStream) throws ProtocolException, IOException { - private byte[] readData(InputStream inputStream) throws IOException { - int availableSize = 0; + byte[] payload = readData(inputStream); + ChannelBuffer cb = ChannelBuffers.wrappedBuffer(payload); - for (int i = 0; i < 3; i++) { - availableSize = inputStream.available(); + short packetType = cb.readShort(); - if (availableSize > 0) { - break; - } + ControlHandshakeResponsePacket packet = ControlHandshakeResponsePacket.readBuffer(packetType, cb); + return packet; + } - try { - Thread.sleep(50); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + private ResponsePacket readSimpleResponsePacket(InputStream inputStream) throws ProtocolException, IOException { + byte[] payload = readData(inputStream); + ChannelBuffer cb = ChannelBuffers.wrappedBuffer(payload); - byte[] payload = new byte[availableSize]; - inputStream.read(payload); + short packetType = cb.readShort(); - return payload; - } + ResponsePacket packet = ResponsePacket.readBuffer(packetType, cb); + return packet; + } - class SimpleListener implements ServerMessageListener { - @Override - public void handleSend(SendPacket sendPacket, SocketChannel channel) { + private byte[] readData(InputStream inputStream) throws IOException { + int availableSize = 0; - } + for (int i = 0; i < 3; i++) { + availableSize = inputStream.available(); - @Override - public void handleRequest(RequestPacket requestPacket, SocketChannel channel) { - logger.info("handlerRequest {} {}", requestPacket, channel); - channel.sendResponseMessage(requestPacket, requestPacket.getPayload()); - } - - @Override - public HandshakeResponseCode handleHandshake(Map properties) { - if (properties == null) { - return HandshakeResponseType.ProtocolError.PROTOCOL_ERROR; - } - - boolean hasAllType = AgentHandshakePropertyType.hasAllType(properties); - if (!hasAllType) { - return HandshakeResponseType.PropertyError.PROPERTY_ERROR; - } + if (availableSize > 0) { + break; + } + + try { + Thread.sleep(50); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + byte[] payload = new byte[availableSize]; + inputStream.read(payload); + + return payload; + } + + class SimpleListener implements ServerMessageListener { + @Override + public void handleSend(SendPacket sendPacket, SocketChannel channel) { + + } + + @Override + public void handleRequest(RequestPacket requestPacket, SocketChannel channel) { + logger.info("handlerRequest {} {}", requestPacket, channel); + channel.sendResponseMessage(requestPacket, requestPacket.getPayload()); + } + + @Override + public HandshakeResponseCode handleHandshake(Map properties) { + if (properties == null) { + return HandshakeResponseType.ProtocolError.PROTOCOL_ERROR; + } + + boolean hasAllType = AgentHandshakePropertyType.hasAllType(properties); + if (!hasAllType) { + return HandshakeResponseType.PropertyError.PROPERTY_ERROR; + } + + return HandshakeResponseType.Success.DUPLEX_COMMUNICATION; + } + } + + private Map getParams() { + Map properties = new HashMap(); - return HandshakeResponseType.Success.DUPLEX_COMMUNICATION; - } - } - - private Map getParams() { - Map properties = new HashMap(); - properties.put(AgentHandshakePropertyType.AGENT_ID.getName(), "agent"); properties.put(AgentHandshakePropertyType.APPLICATION_NAME.getName(), "application"); properties.put(AgentHandshakePropertyType.HOSTNAME.getName(), "hostname"); @@ -293,8 +293,8 @@ public class ControlPacketServerTest { properties.put(AgentHandshakePropertyType.SERVICE_TYPE.getName(), 10); properties.put(AgentHandshakePropertyType.START_TIMESTAMP.getName(), System.currentTimeMillis()); properties.put(AgentHandshakePropertyType.VERSION.getName(), "1.0"); - - return properties; - } + + return properties; + } } diff --git a/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/EventListenerTest.java b/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/EventListenerTest.java index 728f06456..366c82cc5 100644 --- a/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/EventListenerTest.java +++ b/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/EventListenerTest.java @@ -53,121 +53,121 @@ import com.navercorp.pinpoint.rpc.util.MapUtils; */ public class EventListenerTest { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - // Test for being possible to send messages in case of failure of registering packet ( return code : 2, lack of parameter) - @Test - public void registerAgentTest1() throws Exception { - EventListener eventListner = new EventListener(); - - PinpointServerSocket pinpointServerSocket = new PinpointServerSocket(eventListner); - pinpointServerSocket.setMessageListener(new SimpleListener()); - pinpointServerSocket.bind("127.0.0.1", 22234); + // Test for being possible to send messages in case of failure of registering packet ( return code : 2, lack of parameter) + @Test + public void registerAgentTest1() throws Exception { + EventListener eventListner = new EventListener(); - Socket socket = null; - try { - socket = new Socket("127.0.0.1", 22234); - sendAndReceiveSimplePacket(socket); - Assert.assertEquals(eventListner.getCode(), PinpointServerSocketStateCode.RUN); - - int code = sendAndReceiveRegisterPacket(socket, getParams()); - Assert.assertEquals(eventListner.getCode(), PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION); + PinpointServerSocket pinpointServerSocket = new PinpointServerSocket(eventListner); + pinpointServerSocket.setMessageListener(new SimpleListener()); + pinpointServerSocket.bind("127.0.0.1", 22234); - sendAndReceiveSimplePacket(socket); - } finally { - if (socket != null) { - socket.close(); - } + Socket socket = null; + try { + socket = new Socket("127.0.0.1", 22234); + sendAndReceiveSimplePacket(socket); + Assert.assertEquals(eventListner.getCode(), PinpointServerSocketStateCode.RUN); - if (pinpointServerSocket != null) { - pinpointServerSocket.close(); - } - } - } + int code = sendAndReceiveRegisterPacket(socket, getParams()); + Assert.assertEquals(eventListner.getCode(), PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION); - private int sendAndReceiveRegisterPacket(Socket socket, Map properties) throws ProtocolException, IOException { - sendRegisterPacket(socket.getOutputStream(), properties); - ControlHandshakeResponsePacket packet = receiveRegisterConfirmPacket(socket.getInputStream()); - Map result = (Map) ControlMessageEncodingUtils.decode(packet.getPayload()); - - return MapUtils.getInteger(result, "code", -1); - } + sendAndReceiveSimplePacket(socket); + } finally { + if (socket != null) { + socket.close(); + } - private void sendAndReceiveSimplePacket(Socket socket) throws ProtocolException, IOException { - sendSimpleRequestPacket(socket.getOutputStream()); - ResponsePacket responsePacket = readSimpleResponsePacket(socket.getInputStream()); - Assert.assertNotNull(responsePacket); - } + if (pinpointServerSocket != null) { + pinpointServerSocket.close(); + } + } + } - private void sendRegisterPacket(OutputStream outputStream, Map properties) throws ProtocolException, IOException { - byte[] payload = ControlMessageEncodingUtils.encode(properties); - ControlHandshakePacket packet = new ControlHandshakePacket(1, payload); + private int sendAndReceiveRegisterPacket(Socket socket, Map properties) throws ProtocolException, IOException { + sendRegisterPacket(socket.getOutputStream(), properties); + ControlHandshakeResponsePacket packet = receiveRegisterConfirmPacket(socket.getInputStream()); + Map result = (Map) ControlMessageEncodingUtils.decode(packet.getPayload()); - ByteBuffer bb = packet.toBuffer().toByteBuffer(0, packet.toBuffer().writerIndex()); - sendData(outputStream, bb.array()); - } + return MapUtils.getInteger(result, "code", -1); + } - private void sendSimpleRequestPacket(OutputStream outputStream) throws ProtocolException, IOException { - RequestPacket packet = new RequestPacket(new byte[0]); - packet.setRequestId(10); + private void sendAndReceiveSimplePacket(Socket socket) throws ProtocolException, IOException { + sendSimpleRequestPacket(socket.getOutputStream()); + ResponsePacket responsePacket = readSimpleResponsePacket(socket.getInputStream()); + Assert.assertNotNull(responsePacket); + } - ByteBuffer bb = packet.toBuffer().toByteBuffer(0, packet.toBuffer().writerIndex()); - sendData(outputStream, bb.array()); - } + private void sendRegisterPacket(OutputStream outputStream, Map properties) throws ProtocolException, IOException { + byte[] payload = ControlMessageEncodingUtils.encode(properties); + ControlHandshakePacket packet = new ControlHandshakePacket(1, payload); - private void sendData(OutputStream outputStream, byte[] payload) throws IOException { - outputStream.write(payload); - outputStream.flush(); - } + ByteBuffer bb = packet.toBuffer().toByteBuffer(0, packet.toBuffer().writerIndex()); + sendData(outputStream, bb.array()); + } - private ControlHandshakeResponsePacket receiveRegisterConfirmPacket(InputStream inputStream) throws ProtocolException, IOException { + private void sendSimpleRequestPacket(OutputStream outputStream) throws ProtocolException, IOException { + RequestPacket packet = new RequestPacket(new byte[0]); + packet.setRequestId(10); - byte[] payload = readData(inputStream); - ChannelBuffer cb = ChannelBuffers.wrappedBuffer(payload); + ByteBuffer bb = packet.toBuffer().toByteBuffer(0, packet.toBuffer().writerIndex()); + sendData(outputStream, bb.array()); + } - short packetType = cb.readShort(); + private void sendData(OutputStream outputStream, byte[] payload) throws IOException { + outputStream.write(payload); + outputStream.flush(); + } - ControlHandshakeResponsePacket packet = ControlHandshakeResponsePacket.readBuffer(packetType, cb); - return packet; - } + private ControlHandshakeResponsePacket receiveRegisterConfirmPacket(InputStream inputStream) throws ProtocolException, IOException { - private ResponsePacket readSimpleResponsePacket(InputStream inputStream) throws ProtocolException, IOException { - byte[] payload = readData(inputStream); - ChannelBuffer cb = ChannelBuffers.wrappedBuffer(payload); + byte[] payload = readData(inputStream); + ChannelBuffer cb = ChannelBuffers.wrappedBuffer(payload); - short packetType = cb.readShort(); + short packetType = cb.readShort(); - ResponsePacket packet = ResponsePacket.readBuffer(packetType, cb); - return packet; - } + ControlHandshakeResponsePacket packet = ControlHandshakeResponsePacket.readBuffer(packetType, cb); + return packet; + } - private byte[] readData(InputStream inputStream) throws IOException { - int availableSize = 0; + private ResponsePacket readSimpleResponsePacket(InputStream inputStream) throws ProtocolException, IOException { + byte[] payload = readData(inputStream); + ChannelBuffer cb = ChannelBuffers.wrappedBuffer(payload); - for (int i = 0; i < 3; i++) { - availableSize = inputStream.available(); + short packetType = cb.readShort(); - if (availableSize > 0) { - break; - } + ResponsePacket packet = ResponsePacket.readBuffer(packetType, cb); + return packet; + } - try { - Thread.sleep(50); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + private byte[] readData(InputStream inputStream) throws IOException { + int availableSize = 0; - byte[] payload = new byte[availableSize]; - inputStream.read(payload); + for (int i = 0; i < 3; i++) { + availableSize = inputStream.available(); + + if (availableSize > 0) { + break; + } + + try { + Thread.sleep(50); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + byte[] payload = new byte[availableSize]; + inputStream.read(payload); + + return payload; + } + + private Map getParams() { + Map properties = new HashMap(); - return payload; - } - - private Map getParams() { - Map properties = new HashMap(); - properties.put(AgentHandshakePropertyType.AGENT_ID.getName(), "agent"); properties.put(AgentHandshakePropertyType.APPLICATION_NAME.getName(), "application"); properties.put(AgentHandshakePropertyType.HOSTNAME.getName(), "hostname"); @@ -176,43 +176,43 @@ public class EventListenerTest { properties.put(AgentHandshakePropertyType.SERVICE_TYPE.getName(), 10); properties.put(AgentHandshakePropertyType.START_TIMESTAMP.getName(), System.currentTimeMillis()); properties.put(AgentHandshakePropertyType.VERSION.getName(), "1.0"); - - return properties; - } - class SimpleListener implements ServerMessageListener { - @Override - public void handleSend(SendPacket sendPacket, SocketChannel channel) { + return properties; + } - } + class SimpleListener implements ServerMessageListener { + @Override + public void handleSend(SendPacket sendPacket, SocketChannel channel) { - @Override - public void handleRequest(RequestPacket requestPacket, SocketChannel channel) { - logger.info("handlerRequest {}", requestPacket, channel); - channel.sendResponseMessage(requestPacket, requestPacket.getPayload()); - } - - @Override - public HandshakeResponseCode handleHandshake(Map properties) { - logger.info("handle Handshake {}", properties); - return HandshakeResponseType.Success.DUPLEX_COMMUNICATION; - } - } + } + + @Override + public void handleRequest(RequestPacket requestPacket, SocketChannel channel) { + logger.info("handlerRequest {}", requestPacket, channel); + channel.sendResponseMessage(requestPacket, requestPacket.getPayload()); + } + + @Override + public HandshakeResponseCode handleHandshake(Map properties) { + logger.info("handle Handshake {}", properties); + return HandshakeResponseType.Success.DUPLEX_COMMUNICATION; + } + } - class EventListener implements SocketChannelStateChangeEventListener { + class EventListener implements SocketChannelStateChangeEventListener { - private PinpointServerSocketStateCode code; - - @Override - public void eventPerformed(ChannelContext channelContext, PinpointServerSocketStateCode stateCode) { - this.code = stateCode; - } + private PinpointServerSocketStateCode code; + + @Override + public void eventPerformed(ChannelContext channelContext, PinpointServerSocketStateCode stateCode) { + this.code = stateCode; + } + + public PinpointServerSocketStateCode getCode() { + return code; + } + + } - public PinpointServerSocketStateCode getCode() { - return code; - } - - } - } diff --git a/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/MessageListenerTest.java b/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/MessageListenerTest.java index 44f3976cc..d496b5f38 100644 --- a/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/MessageListenerTest.java +++ b/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/MessageListenerTest.java @@ -46,232 +46,232 @@ import com.navercorp.pinpoint.rpc.server.SimpleLoggingServerMessageListener; public class MessageListenerTest { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Test - public void serverMessageListenerTest1() throws InterruptedException { - PinpointServerSocket ss = new PinpointServerSocket(); - ss.bind("127.0.0.1", 10234); - ss.setMessageListener(new SimpleListener()); - - PinpointSocketFactory socketFactory1 = createPinpointSocketFactory(); - socketFactory1.setMessageListener(new EchoMessageListener()); - - PinpointSocketFactory socketFactory2 = createPinpointSocketFactory(); - - try { - - PinpointSocket socket = socketFactory1.connect("127.0.0.1", 10234); - PinpointSocket socket2 = socketFactory2.connect("127.0.0.1", 10234); - - Thread.sleep(500); - - List channelContextList = ss.getDuplexCommunicationChannelContext(); - if (channelContextList.size() != 2) { - Assert.fail(); - } - - socket.close(); - socket2.close(); - } finally { - socketFactory1.release(); - socketFactory2.release(); - - ss.close(); - } - } - - @Test - public void serverMessageListenerTest2() throws InterruptedException { - PinpointServerSocket ss = new PinpointServerSocket(); - ss.bind("127.0.0.1", 10234); + @Test + public void serverMessageListenerTest1() throws InterruptedException { + PinpointServerSocket ss = new PinpointServerSocket(); + ss.bind("127.0.0.1", 10234); ss.setMessageListener(new SimpleListener()); - EchoMessageListener echoMessageListener = new EchoMessageListener(); + PinpointSocketFactory socketFactory1 = createPinpointSocketFactory(); + socketFactory1.setMessageListener(new EchoMessageListener()); - PinpointSocketFactory socketFactory = createPinpointSocketFactory(); - socketFactory.setMessageListener(echoMessageListener); + PinpointSocketFactory socketFactory2 = createPinpointSocketFactory(); - try { + try { - PinpointSocket socket = socketFactory.connect("127.0.0.1", 10234); - Thread.sleep(500); + PinpointSocket socket = socketFactory1.connect("127.0.0.1", 10234); + PinpointSocket socket2 = socketFactory2.connect("127.0.0.1", 10234); - List channelContextList = ss.getDuplexCommunicationChannelContext(); - if (channelContextList.size() != 1) { - Assert.fail(); - } + Thread.sleep(500); - ChannelContext channelContext = channelContextList.get(0); - - channelContext.getSocketChannel().sendMessage("simple".getBytes()); - Thread.sleep(100); - - Assert.assertEquals("simple", new String(echoMessageListener.getSendPacketRepository().get(0).getPayload())); - - Future future = channelContext.getSocketChannel().sendRequestMessage("request".getBytes()); - future.await(); - ResponseMessage message = future.getResult(); - Assert.assertEquals("request", new String(message.getMessage())); - Assert.assertEquals("request", new String(echoMessageListener.getRequestPacketRepository().get(0).getPayload())); - - socket.close(); - } finally { - socketFactory.release(); - ss.close(); - } - } + List channelContextList = ss.getDuplexCommunicationChannelContext(); + if (channelContextList.size() != 2) { + Assert.fail(); + } - @Test - public void serverMessageListenerTest3() throws InterruptedException { - PinpointServerSocket ss = new PinpointServerSocket(); - ss.bind("127.0.0.1", 10234); + socket.close(); + socket2.close(); + } finally { + socketFactory1.release(); + socketFactory2.release(); + + ss.close(); + } + } + + @Test + public void serverMessageListenerTest2() throws InterruptedException { + PinpointServerSocket ss = new PinpointServerSocket(); + ss.bind("127.0.0.1", 10234); ss.setMessageListener(new SimpleListener()); - PinpointSocketFactory socketFactory1 = createPinpointSocketFactory(); - EchoMessageListener echoMessageListener1 = new EchoMessageListener(); - socketFactory1.setMessageListener(echoMessageListener1); - - PinpointSocketFactory socketFactory2 = createPinpointSocketFactory(); - EchoMessageListener echoMessageListener2 = new EchoMessageListener(); - socketFactory2.setMessageListener(echoMessageListener2); - - try { + EchoMessageListener echoMessageListener = new EchoMessageListener(); - PinpointSocket socket = socketFactory1.connect("127.0.0.1", 10234); - PinpointSocket socket2 = socketFactory2.connect("127.0.0.1", 10234); - - Thread.sleep(500); + PinpointSocketFactory socketFactory = createPinpointSocketFactory(); + socketFactory.setMessageListener(echoMessageListener); - List channelContextList = ss.getDuplexCommunicationChannelContext(); - if (channelContextList.size() != 2) { - Assert.fail(); - } + try { - ChannelContext channelContext = channelContextList.get(0); - Future future = channelContext.getSocketChannel().sendRequestMessage("socket1".getBytes()); - ChannelContext channelContext2 = channelContextList.get(1); - Future future2 = channelContext2.getSocketChannel().sendRequestMessage("socket2".getBytes()); + PinpointSocket socket = socketFactory.connect("127.0.0.1", 10234); + Thread.sleep(500); - future.await(); - future2.await(); - Assert.assertEquals("socket1", new String(future.getResult().getMessage())); - Assert.assertEquals("socket2", new String(future2.getResult().getMessage())); - - socket.close(); - socket2.close(); - } finally { - socketFactory1.release(); - socketFactory2.release(); - - ss.close(); - } - } - - @Test - public void serverMessageListenerTest4() throws InterruptedException { - PinpointServerSocket ss = new PinpointServerSocket(); - ss.bind("127.0.0.1", 10234); + List channelContextList = ss.getDuplexCommunicationChannelContext(); + if (channelContextList.size() != 1) { + Assert.fail(); + } + + ChannelContext channelContext = channelContextList.get(0); + + channelContext.getSocketChannel().sendMessage("simple".getBytes()); + Thread.sleep(100); + + Assert.assertEquals("simple", new String(echoMessageListener.getSendPacketRepository().get(0).getPayload())); + + Future future = channelContext.getSocketChannel().sendRequestMessage("request".getBytes()); + future.await(); + ResponseMessage message = future.getResult(); + Assert.assertEquals("request", new String(message.getMessage())); + Assert.assertEquals("request", new String(echoMessageListener.getRequestPacketRepository().get(0).getPayload())); + + socket.close(); + } finally { + socketFactory.release(); + ss.close(); + } + } + + @Test + public void serverMessageListenerTest3() throws InterruptedException { + PinpointServerSocket ss = new PinpointServerSocket(); + ss.bind("127.0.0.1", 10234); ss.setMessageListener(new SimpleListener()); - Map params = getParams(); - PinpointSocketFactory socketFactory = createPinpointSocketFactory(params); - socketFactory.setMessageListener(new EchoMessageListener()); + PinpointSocketFactory socketFactory1 = createPinpointSocketFactory(); + EchoMessageListener echoMessageListener1 = new EchoMessageListener(); + socketFactory1.setMessageListener(echoMessageListener1); - try { - - PinpointSocket socket = socketFactory.connect("127.0.0.1", 10234); - - Thread.sleep(500); + PinpointSocketFactory socketFactory2 = createPinpointSocketFactory(); + EchoMessageListener echoMessageListener2 = new EchoMessageListener(); + socketFactory2.setMessageListener(echoMessageListener2); - ChannelContext channelContext = getChannelContext("application", "agent", (Long) params.get(AgentHandshakePropertyType.START_TIMESTAMP.getName()), ss.getDuplexCommunicationChannelContext()); - Assert.assertNotNull(channelContext); + try { - channelContext = getChannelContext("application", "agent", (Long) params.get(AgentHandshakePropertyType.START_TIMESTAMP.getName()) + 1, ss.getDuplexCommunicationChannelContext()); - Assert.assertNull(channelContext); + PinpointSocket socket = socketFactory1.connect("127.0.0.1", 10234); + PinpointSocket socket2 = socketFactory2.connect("127.0.0.1", 10234); - socket.close(); - } finally { - socketFactory.release(); - ss.close(); - } - } + Thread.sleep(500); - @Test - public void serverMessageListenerTest5() throws InterruptedException { - PinpointServerSocket ss = new PinpointServerSocket(); - ss.bind("127.0.0.1", 10234); + List channelContextList = ss.getDuplexCommunicationChannelContext(); + if (channelContextList.size() != 2) { + Assert.fail(); + } + + ChannelContext channelContext = channelContextList.get(0); + Future future = channelContext.getSocketChannel().sendRequestMessage("socket1".getBytes()); + ChannelContext channelContext2 = channelContextList.get(1); + Future future2 = channelContext2.getSocketChannel().sendRequestMessage("socket2".getBytes()); + + future.await(); + future2.await(); + Assert.assertEquals("socket1", new String(future.getResult().getMessage())); + Assert.assertEquals("socket2", new String(future2.getResult().getMessage())); + + socket.close(); + socket2.close(); + } finally { + socketFactory1.release(); + socketFactory2.release(); + + ss.close(); + } + } + + @Test + public void serverMessageListenerTest4() throws InterruptedException { + PinpointServerSocket ss = new PinpointServerSocket(); + ss.bind("127.0.0.1", 10234); ss.setMessageListener(new SimpleListener()); - PinpointSocketFactory socketFactory = createPinpointSocketFactory(); - socketFactory.setMessageListener(SimpleLoggingMessageListener.LISTENER); - try { - // SimpleLoggingMessageListener.LISTENER as default listener can't connect by duplex mode. - PinpointSocket socket = socketFactory.connect("127.0.0.1", 10234); + Map params = getParams(); + PinpointSocketFactory socketFactory = createPinpointSocketFactory(params); + socketFactory.setMessageListener(new EchoMessageListener()); - Thread.sleep(500); + try { - List channelContextList = ss.getDuplexCommunicationChannelContext(); - if (channelContextList.size() != 1) { - Assert.fail(); - } + PinpointSocket socket = socketFactory.connect("127.0.0.1", 10234); - socket.close(); - } finally { - socketFactory.release(); - ss.close(); - } - } + Thread.sleep(500); - // confirm how many times retry when packet has not been received. - @Test - public void serverMessageListenerTest6() throws InterruptedException { - DuplexCheckListener serverListener = new DuplexCheckListener(); - - PinpointServerSocket ss = new PinpointServerSocket(); - ss.bind("127.0.0.1", 10234); - ss.setMessageListener(serverListener); + ChannelContext channelContext = getChannelContext("application", "agent", (Long) params.get(AgentHandshakePropertyType.START_TIMESTAMP.getName()), ss.getDuplexCommunicationChannelContext()); + Assert.assertNotNull(channelContext); - PinpointSocketFactory socketFactory = createPinpointSocketFactory(); - socketFactory.setEnableWorkerPacketDelay(500); - socketFactory.setMessageListener(new EchoMessageListener()); - - try { + channelContext = getChannelContext("application", "agent", (Long) params.get(AgentHandshakePropertyType.START_TIMESTAMP.getName()) + 1, ss.getDuplexCommunicationChannelContext()); + Assert.assertNull(channelContext); - // SimpleLoggingMessageListener.LISTENER as default listener can't connect by duplex mode. - PinpointSocket socket = socketFactory.connect("127.0.0.1", 10234); - Thread.sleep(5000); + socket.close(); + } finally { + socketFactory.release(); + ss.close(); + } + } - List channelContextList = ss.getDuplexCommunicationChannelContext(); - if (channelContextList.size() != 0) { - Assert.fail(); - } - - System.out.println(serverListener.getReceiveEnableWorkerPacketCount()); - if (serverListener.getReceiveEnableWorkerPacketCount() < 8) { - Assert.fail(); - } + @Test + public void serverMessageListenerTest5() throws InterruptedException { + PinpointServerSocket ss = new PinpointServerSocket(); + ss.bind("127.0.0.1", 10234); + ss.setMessageListener(new SimpleListener()); - socket.close(); - } finally { - socketFactory.release(); - ss.close(); - } - } - - private PinpointSocketFactory createPinpointSocketFactory() { - return createPinpointSocketFactory(getParams()); - } + PinpointSocketFactory socketFactory = createPinpointSocketFactory(); + socketFactory.setMessageListener(SimpleLoggingMessageListener.LISTENER); + try { + // SimpleLoggingMessageListener.LISTENER as default listener can't connect by duplex mode. + PinpointSocket socket = socketFactory.connect("127.0.0.1", 10234); - private PinpointSocketFactory createPinpointSocketFactory(Map param) { - PinpointSocketFactory pinpointSocketFactory = new PinpointSocketFactory(); - pinpointSocketFactory.setProperties(param); + Thread.sleep(500); - return pinpointSocketFactory; - } + List channelContextList = ss.getDuplexCommunicationChannelContext(); + if (channelContextList.size() != 1) { + Assert.fail(); + } - private Map getParams() { - Map properties = new HashMap(); + socket.close(); + } finally { + socketFactory.release(); + ss.close(); + } + } + + // confirm how many times retry when packet has not been received. + @Test + public void serverMessageListenerTest6() throws InterruptedException { + DuplexCheckListener serverListener = new DuplexCheckListener(); + + PinpointServerSocket ss = new PinpointServerSocket(); + ss.bind("127.0.0.1", 10234); + ss.setMessageListener(serverListener); + + PinpointSocketFactory socketFactory = createPinpointSocketFactory(); + socketFactory.setEnableWorkerPacketDelay(500); + socketFactory.setMessageListener(new EchoMessageListener()); + + try { + + // SimpleLoggingMessageListener.LISTENER as default listener can't connect by duplex mode. + PinpointSocket socket = socketFactory.connect("127.0.0.1", 10234); + Thread.sleep(5000); + + List channelContextList = ss.getDuplexCommunicationChannelContext(); + if (channelContextList.size() != 0) { + Assert.fail(); + } + + System.out.println(serverListener.getReceiveEnableWorkerPacketCount()); + if (serverListener.getReceiveEnableWorkerPacketCount() < 8) { + Assert.fail(); + } + + socket.close(); + } finally { + socketFactory.release(); + ss.close(); + } + } + + private PinpointSocketFactory createPinpointSocketFactory() { + return createPinpointSocketFactory(getParams()); + } + + private PinpointSocketFactory createPinpointSocketFactory(Map param) { + PinpointSocketFactory pinpointSocketFactory = new PinpointSocketFactory(); + pinpointSocketFactory.setProperties(param); + + return pinpointSocketFactory; + } + + private Map getParams() { + Map properties = new HashMap(); properties.put(AgentHandshakePropertyType.AGENT_ID.getName(), "agent"); properties.put(AgentHandshakePropertyType.APPLICATION_NAME.getName(), "application"); @@ -282,72 +282,72 @@ public class MessageListenerTest { properties.put(AgentHandshakePropertyType.START_TIMESTAMP.getName(), System.currentTimeMillis()); properties.put(AgentHandshakePropertyType.VERSION.getName(), "1.0"); - return properties; - } + return properties; + } - class EchoMessageListener implements MessageListener { - private final List sendPacketRepository = new ArrayList(); - private final List requestPacketRepository = new ArrayList(); + class EchoMessageListener implements MessageListener { + private final List sendPacketRepository = new ArrayList(); + private final List requestPacketRepository = new ArrayList(); - @Override - public void handleSend(SendPacket sendPacket, Channel channel) { - sendPacketRepository.add(sendPacket); - - byte[] payload = sendPacket.getPayload(); + @Override + public void handleSend(SendPacket sendPacket, Channel channel) { + sendPacketRepository.add(sendPacket); + + byte[] payload = sendPacket.getPayload(); logger.debug(new String(payload)); - } + } - @Override - public void handleRequest(RequestPacket requestPacket, Channel channel) { - requestPacketRepository.add(requestPacket); - - byte[] payload = requestPacket.getPayload(); - logger.debug(new String(payload)); + @Override + public void handleRequest(RequestPacket requestPacket, Channel channel) { + requestPacketRepository.add(requestPacket); - channel.write(new ResponsePacket(requestPacket.getRequestId(), requestPacket.getPayload())); - } + byte[] payload = requestPacket.getPayload(); + logger.debug(new String(payload)); - public List getSendPacketRepository() { - return sendPacketRepository; - } + channel.write(new ResponsePacket(requestPacket.getRequestId(), requestPacket.getPayload())); + } - public List getRequestPacketRepository() { - return requestPacketRepository; - } - } - - class DuplexCheckListener extends SimpleLoggingServerMessageListener { - - private final AtomicInteger receiveEnableWorkerPacketCount = new AtomicInteger(); - - @Override - public HandshakeResponseCode handleHandshake(Map properties) { - receiveEnableWorkerPacketCount.incrementAndGet(); + public List getSendPacketRepository() { + return sendPacketRepository; + } + + public List getRequestPacketRepository() { + return requestPacketRepository; + } + } + + class DuplexCheckListener extends SimpleLoggingServerMessageListener { + + private final AtomicInteger receiveEnableWorkerPacketCount = new AtomicInteger(); + + @Override + public HandshakeResponseCode handleHandshake(Map properties) { + receiveEnableWorkerPacketCount.incrementAndGet(); return HandshakeResponseType.Error.UNKNOWN_ERROR; - } + } - public int getReceiveEnableWorkerPacketCount() { - return receiveEnableWorkerPacketCount.get(); - } - - } - - private ChannelContext getChannelContext(String applicationName, String agentId, long startTimeMillis, List duplexChannelContextList) { - if (applicationName == null) { - return null; - } - - if (agentId == null) { - return null; - } - - if (startTimeMillis <= 0) { - return null; - } - - List channelContextList = new ArrayList(); + public int getReceiveEnableWorkerPacketCount() { + return receiveEnableWorkerPacketCount.get(); + } - for (ChannelContext eachContext : duplexChannelContextList) { + } + + private ChannelContext getChannelContext(String applicationName, String agentId, long startTimeMillis, List duplexChannelContextList) { + if (applicationName == null) { + return null; + } + + if (agentId == null) { + return null; + } + + if (startTimeMillis <= 0) { + return null; + } + + List channelContextList = new ArrayList(); + + for (ChannelContext eachContext : duplexChannelContextList) { if (eachContext.getCurrentStateCode() == PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION) { Map agentProperties = eachContext.getChannelProperties(); @@ -365,22 +365,22 @@ public class MessageListenerTest { channelContextList.add(eachContext); } - } - + } - if (channelContextList.size() == 0) { - return null; - } - - if (channelContextList.size() == 1) { - return channelContextList.get(0); - } else { - logger.warn("Ambiguous Channel Context {}, {}, {} (Valid Agent list={}).", applicationName, agentId, startTimeMillis, channelContextList); - return null; - } + + if (channelContextList.size() == 0) { + return null; + } + + if (channelContextList.size() == 1) { + return channelContextList.get(0); + } else { + logger.warn("Ambiguous Channel Context {}, {}, {} (Valid Agent list={}).", applicationName, agentId, startTimeMillis, channelContextList); + return null; + } } - - private class SimpleListener extends SimpleLoggingServerMessageListener { + + private class SimpleListener extends SimpleLoggingServerMessageListener { @Override public HandshakeResponseCode handleHandshake(Map properties) { @@ -388,8 +388,8 @@ public class MessageListenerTest { return HandshakeResponseType.Success.DUPLEX_COMMUNICATION; } - - } - + + } + } diff --git a/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/PinpointServerSocketStateTest.java b/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/PinpointServerSocketStateTest.java index 14a1ca9cf..e51907176 100644 --- a/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/PinpointServerSocketStateTest.java +++ b/rpc/src/test/java/com/navercorp/pinpoint/rpc/server/PinpointServerSocketStateTest.java @@ -27,92 +27,92 @@ import com.navercorp.pinpoint.rpc.server.PinpointServerSocketStateCode; */ public class PinpointServerSocketStateTest { - // basic type of connection's lifecycle between peers. - // RUN -> RUN_DUPLEX_COMMUNICATION -> BEING_SHUTDOWN -> connection closed - @Test - public void changeStateTest1() { - PinpointServerSocketState state = new PinpointServerSocketState(); + // basic type of connection's lifecycle between peers. + // RUN -> RUN_DUPLEX_COMMUNICATION -> BEING_SHUTDOWN -> connection closed + @Test + public void changeStateTest1() { + PinpointServerSocketState state = new PinpointServerSocketState(); - state.changeStateRun(); - Assert.assertEquals(PinpointServerSocketStateCode.RUN, state.getCurrentState()); + state.changeStateRun(); + Assert.assertEquals(PinpointServerSocketStateCode.RUN, state.getCurrentState()); - state.changeStateRunDuplexCommunication(); - Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, state.getCurrentState()); + state.changeStateRunDuplexCommunication(); + Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, state.getCurrentState()); - state.changeStateBeingShutdown(); - Assert.assertEquals(PinpointServerSocketStateCode.BEING_SHUTDOWN, state.getCurrentState()); + state.changeStateBeingShutdown(); + Assert.assertEquals(PinpointServerSocketStateCode.BEING_SHUTDOWN, state.getCurrentState()); - state.changeStateShutdown(); - Assert.assertEquals(PinpointServerSocketStateCode.SHUTDOWN, state.getCurrentState()); - } + state.changeStateShutdown(); + Assert.assertEquals(PinpointServerSocketStateCode.SHUTDOWN, state.getCurrentState()); + } - // basic type of connection's lifecycle between peers. - // RUN_DUPLEX_COMMUNICATION -> RUN_DUPLEX_COMMUNICATION -> BEING_SHUTDOWN -> connection closed - @Test - public void changeStateTest2() { - PinpointServerSocketState state = new PinpointServerSocketState(); + // basic type of connection's lifecycle between peers. + // RUN_DUPLEX_COMMUNICATION -> RUN_DUPLEX_COMMUNICATION -> BEING_SHUTDOWN -> connection closed + @Test + public void changeStateTest2() { + PinpointServerSocketState state = new PinpointServerSocketState(); - state.changeStateRunDuplexCommunication(); - Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, state.getCurrentState()); + state.changeStateRunDuplexCommunication(); + Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, state.getCurrentState()); - state.changeStateBeingShutdown(); - Assert.assertEquals(PinpointServerSocketStateCode.BEING_SHUTDOWN, state.getCurrentState()); + state.changeStateBeingShutdown(); + Assert.assertEquals(PinpointServerSocketStateCode.BEING_SHUTDOWN, state.getCurrentState()); - state.changeStateShutdown(); - Assert.assertEquals(PinpointServerSocketStateCode.SHUTDOWN, state.getCurrentState()); - } + state.changeStateShutdown(); + Assert.assertEquals(PinpointServerSocketStateCode.SHUTDOWN, state.getCurrentState()); + } - @Test - public void changeStateTest3() { - PinpointServerSocketState state = new PinpointServerSocketState(); + @Test + public void changeStateTest3() { + PinpointServerSocketState state = new PinpointServerSocketState(); - state.changeStateRun(); - Assert.assertEquals(PinpointServerSocketStateCode.RUN, state.getCurrentState()); + state.changeStateRun(); + Assert.assertEquals(PinpointServerSocketStateCode.RUN, state.getCurrentState()); - state.changeStateUnexpectedShutdown(); - Assert.assertEquals(PinpointServerSocketStateCode.UNEXPECTED_SHUTDOWN, state.getCurrentState()); - } + state.changeStateUnexpectedShutdown(); + Assert.assertEquals(PinpointServerSocketStateCode.UNEXPECTED_SHUTDOWN, state.getCurrentState()); + } - @Test - public void changeStateTest4() { - PinpointServerSocketState state = new PinpointServerSocketState(); + @Test + public void changeStateTest4() { + PinpointServerSocketState state = new PinpointServerSocketState(); - state.changeStateRun(); - Assert.assertEquals(PinpointServerSocketStateCode.RUN, state.getCurrentState()); + state.changeStateRun(); + Assert.assertEquals(PinpointServerSocketStateCode.RUN, state.getCurrentState()); - state.changeStateShutdown(); - Assert.assertEquals(PinpointServerSocketStateCode.SHUTDOWN, state.getCurrentState()); - } + state.changeStateShutdown(); + Assert.assertEquals(PinpointServerSocketStateCode.SHUTDOWN, state.getCurrentState()); + } - @Test - public void changeStateTest5() { - PinpointServerSocketState state = new PinpointServerSocketState(); + @Test + public void changeStateTest5() { + PinpointServerSocketState state = new PinpointServerSocketState(); - state.changeStateRunDuplexCommunication(); - Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, state.getCurrentState()); + state.changeStateRunDuplexCommunication(); + Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, state.getCurrentState()); - state.changeStateShutdown(); - Assert.assertEquals(PinpointServerSocketStateCode.SHUTDOWN, state.getCurrentState()); - } + state.changeStateShutdown(); + Assert.assertEquals(PinpointServerSocketStateCode.SHUTDOWN, state.getCurrentState()); + } - @Test(expected = IllegalStateException.class) - public void invalidChangeStateTest1() { - PinpointServerSocketState state = new PinpointServerSocketState(); + @Test(expected = IllegalStateException.class) + public void invalidChangeStateTest1() { + PinpointServerSocketState state = new PinpointServerSocketState(); - state.changeStateBeingShutdown(); - } + state.changeStateBeingShutdown(); + } - @Test(expected = IllegalStateException.class) - public void invalidChangeStateTest2() { - PinpointServerSocketState state = new PinpointServerSocketState(); + @Test(expected = IllegalStateException.class) + public void invalidChangeStateTest2() { + PinpointServerSocketState state = new PinpointServerSocketState(); - state.changeStateRunDuplexCommunication(); - Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, state.getCurrentState()); + state.changeStateRunDuplexCommunication(); + Assert.assertEquals(PinpointServerSocketStateCode.RUN_DUPLEX_COMMUNICATION, state.getCurrentState()); - state.changeStateBeingShutdown(); - Assert.assertEquals(PinpointServerSocketStateCode.BEING_SHUTDOWN, state.getCurrentState()); + state.changeStateBeingShutdown(); + Assert.assertEquals(PinpointServerSocketStateCode.BEING_SHUTDOWN, state.getCurrentState()); - state.changeStateUnexpectedShutdown(); - } + state.changeStateUnexpectedShutdown(); + } } diff --git a/rpc/src/test/java/com/navercorp/pinpoint/rpc/stream/StreamChannelManagerTest.java b/rpc/src/test/java/com/navercorp/pinpoint/rpc/stream/StreamChannelManagerTest.java index 5abe1ec28..e089660b6 100644 --- a/rpc/src/test/java/com/navercorp/pinpoint/rpc/stream/StreamChannelManagerTest.java +++ b/rpc/src/test/java/com/navercorp/pinpoint/rpc/stream/StreamChannelManagerTest.java @@ -44,322 +44,322 @@ import com.navercorp.pinpoint.rpc.stream.StreamChannelContext; public class StreamChannelManagerTest { - // Client to Server Stream - @Test - public void streamSuccessTest1() throws IOException, InterruptedException { - SimpleStreamBO bo = new SimpleStreamBO(); + // Client to Server Stream + @Test + public void streamSuccessTest1() throws IOException, InterruptedException { + SimpleStreamBO bo = new SimpleStreamBO(); - PinpointServerSocket ss = createServerSocket(new TestSeverMessageListener(), new ServerListener(bo)); - ss.bind("localhost", 10234); + PinpointServerSocket ss = createServerSocket(new TestSeverMessageListener(), new ServerListener(bo)); + ss.bind("localhost", 10234); - PinpointSocketFactory pinpointSocketFactory = createSocketFactory(); - try { - PinpointSocket socket = pinpointSocketFactory.connect("127.0.0.1", 10234); + PinpointSocketFactory pinpointSocketFactory = createSocketFactory(); + try { + PinpointSocket socket = pinpointSocketFactory.connect("127.0.0.1", 10234); - RecordedStreamChannelMessageListener clientListener = new RecordedStreamChannelMessageListener(4); + RecordedStreamChannelMessageListener clientListener = new RecordedStreamChannelMessageListener(4); - ClientStreamChannelContext clientContext = socket.createStreamChannel(new byte[0], clientListener); + ClientStreamChannelContext clientContext = socket.createStreamChannel(new byte[0], clientListener); - int sendCount = 4; + int sendCount = 4; - for (int i = 0; i < sendCount; i++) { - sendRandomBytes(bo); - } + for (int i = 0; i < sendCount; i++) { + sendRandomBytes(bo); + } - Thread.sleep(100); + Thread.sleep(100); - Assert.assertEquals(sendCount, clientListener.getReceivedMessage().size()); + Assert.assertEquals(sendCount, clientListener.getReceivedMessage().size()); - clientContext.getStreamChannel().close(); - socket.close(); - } finally { - pinpointSocketFactory.release(); - ss.close(); - } - } + clientContext.getStreamChannel().close(); + socket.close(); + } finally { + pinpointSocketFactory.release(); + ss.close(); + } + } - // Client to Server Stream - @Test - public void streamSuccessTest2() throws IOException, InterruptedException { - SimpleStreamBO bo = new SimpleStreamBO(); + // Client to Server Stream + @Test + public void streamSuccessTest2() throws IOException, InterruptedException { + SimpleStreamBO bo = new SimpleStreamBO(); - PinpointServerSocket ss = createServerSocket(new TestSeverMessageListener(), new ServerListener(bo)); - ss.bind("localhost", 10234); + PinpointServerSocket ss = createServerSocket(new TestSeverMessageListener(), new ServerListener(bo)); + ss.bind("localhost", 10234); - PinpointSocketFactory pinpointSocketFactory = createSocketFactory(); - try { - PinpointSocket socket = pinpointSocketFactory.connect("127.0.0.1", 10234); + PinpointSocketFactory pinpointSocketFactory = createSocketFactory(); + try { + PinpointSocket socket = pinpointSocketFactory.connect("127.0.0.1", 10234); - RecordedStreamChannelMessageListener clientListener = new RecordedStreamChannelMessageListener(4); - ClientStreamChannelContext clientContext = socket.createStreamChannel(new byte[0], clientListener); + RecordedStreamChannelMessageListener clientListener = new RecordedStreamChannelMessageListener(4); + ClientStreamChannelContext clientContext = socket.createStreamChannel(new byte[0], clientListener); - RecordedStreamChannelMessageListener clientListener2 = new RecordedStreamChannelMessageListener(4); - ClientStreamChannelContext clientContext2 = socket.createStreamChannel(new byte[0], clientListener2); + RecordedStreamChannelMessageListener clientListener2 = new RecordedStreamChannelMessageListener(4); + ClientStreamChannelContext clientContext2 = socket.createStreamChannel(new byte[0], clientListener2); - - int sendCount = 4; - for (int i = 0; i < sendCount; i++) { - sendRandomBytes(bo); - } - Thread.sleep(100); + int sendCount = 4; + for (int i = 0; i < sendCount; i++) { + sendRandomBytes(bo); + } - Assert.assertEquals(sendCount, clientListener.getReceivedMessage().size()); - Assert.assertEquals(sendCount, clientListener2.getReceivedMessage().size()); + Thread.sleep(100); - clientContext.getStreamChannel().close(); + Assert.assertEquals(sendCount, clientListener.getReceivedMessage().size()); + Assert.assertEquals(sendCount, clientListener2.getReceivedMessage().size()); - Thread.sleep(100); - - sendCount = 4; - for (int i = 0; i < sendCount; i++) { - sendRandomBytes(bo); - } + clientContext.getStreamChannel().close(); - Thread.sleep(100); + Thread.sleep(100); - Assert.assertEquals(sendCount, clientListener.getReceivedMessage().size()); - Assert.assertEquals(8, clientListener2.getReceivedMessage().size()); + sendCount = 4; + for (int i = 0; i < sendCount; i++) { + sendRandomBytes(bo); + } - - clientContext2.getStreamChannel().close(); - - socket.close(); - } finally { - pinpointSocketFactory.release(); - ss.close(); - } - } + Thread.sleep(100); - @Test - public void streamSuccessTest3() throws IOException, InterruptedException { - PinpointServerSocket ss = createServerSocket(new TestSeverMessageListener(), null); - ss.bind("localhost", 10234); + Assert.assertEquals(sendCount, clientListener.getReceivedMessage().size()); + Assert.assertEquals(8, clientListener2.getReceivedMessage().size()); - SimpleStreamBO bo = new SimpleStreamBO(); - PinpointSocketFactory pinpointSocketFactory = createSocketFactory(new TestListener(), new ServerListener(bo)); + clientContext2.getStreamChannel().close(); - try { - PinpointSocket socket = pinpointSocketFactory.connect("127.0.0.1", 10234); + socket.close(); + } finally { + pinpointSocketFactory.release(); + ss.close(); + } + } - Thread.sleep(100); + @Test + public void streamSuccessTest3() throws IOException, InterruptedException { + PinpointServerSocket ss = createServerSocket(new TestSeverMessageListener(), null); + ss.bind("localhost", 10234); - List contextList = ss.getDuplexCommunicationChannelContext(); - Assert.assertEquals(1, contextList.size()); + SimpleStreamBO bo = new SimpleStreamBO(); - ChannelContext context = contextList.get(0); + PinpointSocketFactory pinpointSocketFactory = createSocketFactory(new TestListener(), new ServerListener(bo)); - RecordedStreamChannelMessageListener clientListener = new RecordedStreamChannelMessageListener(4); + try { + PinpointSocket socket = pinpointSocketFactory.connect("127.0.0.1", 10234); - ClientStreamChannelContext clientContext = context.createStreamChannel(new byte[0], clientListener); + Thread.sleep(100); - int sendCount = 4; + List contextList = ss.getDuplexCommunicationChannelContext(); + Assert.assertEquals(1, contextList.size()); - for (int i = 0; i < sendCount; i++) { - sendRandomBytes(bo); - } + ChannelContext context = contextList.get(0); - Thread.sleep(100); + RecordedStreamChannelMessageListener clientListener = new RecordedStreamChannelMessageListener(4); - Assert.assertEquals(sendCount, clientListener.getReceivedMessage().size()); + ClientStreamChannelContext clientContext = context.createStreamChannel(new byte[0], clientListener); - clientContext.getStreamChannel().close(); - socket.close(); - } finally { - pinpointSocketFactory.release(); - ss.close(); - } - } - - @Test(expected = PinpointSocketException.class) - public void streamClosedTest1() throws IOException, InterruptedException { - PinpointServerSocket ss = createServerSocket(new TestSeverMessageListener(), null); - ss.bind("localhost", 10234); + int sendCount = 4; - PinpointSocketFactory pinpointSocketFactory = createSocketFactory(); - try { - PinpointSocket socket = pinpointSocketFactory.connect("127.0.0.1", 10234); + for (int i = 0; i < sendCount; i++) { + sendRandomBytes(bo); + } - RecordedStreamChannelMessageListener clientListener = new RecordedStreamChannelMessageListener(4); + Thread.sleep(100); - ClientStreamChannelContext clientContext = socket.createStreamChannel(new byte[0], clientListener); + Assert.assertEquals(sendCount, clientListener.getReceivedMessage().size()); - Thread.sleep(100); + clientContext.getStreamChannel().close(); + socket.close(); + } finally { + pinpointSocketFactory.release(); + ss.close(); + } + } - clientContext.getStreamChannel().close(); - socket.close(); - } finally { - pinpointSocketFactory.release(); - ss.close(); - } - } + @Test(expected = PinpointSocketException.class) + public void streamClosedTest1() throws IOException, InterruptedException { + PinpointServerSocket ss = createServerSocket(new TestSeverMessageListener(), null); + ss.bind("localhost", 10234); - @Test - public void streamClosedTest2() throws IOException, InterruptedException { - SimpleStreamBO bo = new SimpleStreamBO(); + PinpointSocketFactory pinpointSocketFactory = createSocketFactory(); + try { + PinpointSocket socket = pinpointSocketFactory.connect("127.0.0.1", 10234); - PinpointServerSocket ss = createServerSocket(new TestSeverMessageListener(), new ServerListener(bo)); - ss.bind("localhost", 10234); + RecordedStreamChannelMessageListener clientListener = new RecordedStreamChannelMessageListener(4); - PinpointSocketFactory pinpointSocketFactory = createSocketFactory(); + ClientStreamChannelContext clientContext = socket.createStreamChannel(new byte[0], clientListener); - PinpointSocket socket = null; - try { - socket = pinpointSocketFactory.connect("127.0.0.1", 10234); + Thread.sleep(100); - RecordedStreamChannelMessageListener clientListener = new RecordedStreamChannelMessageListener(4); + clientContext.getStreamChannel().close(); + socket.close(); + } finally { + pinpointSocketFactory.release(); + ss.close(); + } + } - ClientStreamChannelContext clientContext = socket.createStreamChannel(new byte[0], clientListener); - Thread.sleep(100); + @Test + public void streamClosedTest2() throws IOException, InterruptedException { + SimpleStreamBO bo = new SimpleStreamBO(); - Assert.assertEquals(1, bo.getStreamChannelContextSize()); - - clientContext.getStreamChannel().close(); - Thread.sleep(100); + PinpointServerSocket ss = createServerSocket(new TestSeverMessageListener(), new ServerListener(bo)); + ss.bind("localhost", 10234); - Assert.assertEquals(0, bo.getStreamChannelContextSize()); + PinpointSocketFactory pinpointSocketFactory = createSocketFactory(); - } finally { - if (socket != null) { - socket.close(); - } + PinpointSocket socket = null; + try { + socket = pinpointSocketFactory.connect("127.0.0.1", 10234); - pinpointSocketFactory.release(); - ss.close(); - } - } - - // ServerSocket to Client Stream - - - // ServerStreamChannel first close. - @Test(expected = PinpointSocketException.class) - public void streamClosedTest3() throws IOException, InterruptedException { - PinpointServerSocket ss = createServerSocket(new TestSeverMessageListener(), null); - ss.bind("localhost", 10234); + RecordedStreamChannelMessageListener clientListener = new RecordedStreamChannelMessageListener(4); - SimpleStreamBO bo = new SimpleStreamBO(); + ClientStreamChannelContext clientContext = socket.createStreamChannel(new byte[0], clientListener); + Thread.sleep(100); - PinpointSocketFactory pinpointSocketFactory = createSocketFactory(new TestListener(), new ServerListener(bo)); + Assert.assertEquals(1, bo.getStreamChannelContextSize()); - PinpointSocket socket = pinpointSocketFactory.connect("127.0.0.1", 10234); - try { - - Thread.sleep(100); + clientContext.getStreamChannel().close(); + Thread.sleep(100); - List contextList = ss.getDuplexCommunicationChannelContext(); - Assert.assertEquals(1, contextList.size()); + Assert.assertEquals(0, bo.getStreamChannelContextSize()); - ChannelContext context = contextList.get(0); + } finally { + if (socket != null) { + socket.close(); + } - RecordedStreamChannelMessageListener clientListener = new RecordedStreamChannelMessageListener(4); + pinpointSocketFactory.release(); + ss.close(); + } + } - ClientStreamChannelContext clientContext = context.createStreamChannel(new byte[0], clientListener); + // ServerSocket to Client Stream - - StreamChannelContext aaa = socket.findStreamChannel(2); - - aaa.getStreamChannel().close(); - - sendRandomBytes(bo); - Thread.sleep(100); + // ServerStreamChannel first close. + @Test(expected = PinpointSocketException.class) + public void streamClosedTest3() throws IOException, InterruptedException { + PinpointServerSocket ss = createServerSocket(new TestSeverMessageListener(), null); + ss.bind("localhost", 10234); + SimpleStreamBO bo = new SimpleStreamBO(); - clientContext.getStreamChannel().close(); - } finally { - socket.close(); - pinpointSocketFactory.release(); - ss.close(); - } - } - + PinpointSocketFactory pinpointSocketFactory = createSocketFactory(new TestListener(), new ServerListener(bo)); - private PinpointServerSocket createServerSocket(ServerMessageListener severMessageListener, - ServerStreamChannelMessageListener serverStreamChannelMessageListener) { - PinpointServerSocket serverSocket = new PinpointServerSocket(); + PinpointSocket socket = pinpointSocketFactory.connect("127.0.0.1", 10234); + try { - if (severMessageListener != null) { - serverSocket.setMessageListener(severMessageListener); - } + Thread.sleep(100); - if (serverStreamChannelMessageListener != null) { - serverSocket.setServerStreamChannelMessageListener(serverStreamChannelMessageListener); - } + List contextList = ss.getDuplexCommunicationChannelContext(); + Assert.assertEquals(1, contextList.size()); - return serverSocket; - } + ChannelContext context = contextList.get(0); - private PinpointSocketFactory createSocketFactory() { - PinpointSocketFactory pinpointSocketFactory = new PinpointSocketFactory(); - return pinpointSocketFactory; - } + RecordedStreamChannelMessageListener clientListener = new RecordedStreamChannelMessageListener(4); - private PinpointSocketFactory createSocketFactory(MessageListener messageListener, ServerStreamChannelMessageListener serverStreamChannelMessageListener) { - PinpointSocketFactory pinpointSocketFactory = new PinpointSocketFactory(); - pinpointSocketFactory.setMessageListener(messageListener); - pinpointSocketFactory.setServerStreamChannelMessageListener(serverStreamChannelMessageListener); + ClientStreamChannelContext clientContext = context.createStreamChannel(new byte[0], clientListener); - return pinpointSocketFactory; - } - class TestListener extends SimpleLoggingMessageListener { + StreamChannelContext aaa = socket.findStreamChannel(2); - } + aaa.getStreamChannel().close(); - private void sendRandomBytes(SimpleStreamBO bo) { - byte[] openBytes = TestByteUtils.createRandomByte(30); - bo.sendResponse(openBytes); - } + sendRandomBytes(bo); - class ServerListener implements ServerStreamChannelMessageListener { + Thread.sleep(100); - private final SimpleStreamBO bo; - public ServerListener(SimpleStreamBO bo) { - this.bo = bo; - } + clientContext.getStreamChannel().close(); + } finally { + socket.close(); + pinpointSocketFactory.release(); + ss.close(); + } + } - @Override - public short handleStreamCreate(ServerStreamChannelContext streamChannelContext, StreamCreatePacket packet) { - bo.addServerStreamChannelContext(streamChannelContext); - return 0; - } - @Override - public void handleStreamClose(ServerStreamChannelContext streamChannelContext, StreamClosePacket packet) { - bo.removeServerStreamChannelContext(streamChannelContext); - } + private PinpointServerSocket createServerSocket(ServerMessageListener severMessageListener, + ServerStreamChannelMessageListener serverStreamChannelMessageListener) { + PinpointServerSocket serverSocket = new PinpointServerSocket(); - } + if (severMessageListener != null) { + serverSocket.setMessageListener(severMessageListener); + } - class SimpleStreamBO { + if (serverStreamChannelMessageListener != null) { + serverSocket.setServerStreamChannelMessageListener(serverStreamChannelMessageListener); + } - private final List serverStreamChannelContextList; + return serverSocket; + } - public SimpleStreamBO() { - serverStreamChannelContextList = new CopyOnWriteArrayList(); - } + private PinpointSocketFactory createSocketFactory() { + PinpointSocketFactory pinpointSocketFactory = new PinpointSocketFactory(); + return pinpointSocketFactory; + } - public void addServerStreamChannelContext(ServerStreamChannelContext context) { - serverStreamChannelContextList.add(context); - } + private PinpointSocketFactory createSocketFactory(MessageListener messageListener, ServerStreamChannelMessageListener serverStreamChannelMessageListener) { + PinpointSocketFactory pinpointSocketFactory = new PinpointSocketFactory(); + pinpointSocketFactory.setMessageListener(messageListener); + pinpointSocketFactory.setServerStreamChannelMessageListener(serverStreamChannelMessageListener); - public void removeServerStreamChannelContext(ServerStreamChannelContext context) { - serverStreamChannelContextList.remove(context); - } + return pinpointSocketFactory; + } - void sendResponse(byte[] data) { + class TestListener extends SimpleLoggingMessageListener { - for (ServerStreamChannelContext context : serverStreamChannelContextList) { - context.getStreamChannel().sendData(data); - } - } + } - int getStreamChannelContextSize() { - return serverStreamChannelContextList.size(); - } - } + private void sendRandomBytes(SimpleStreamBO bo) { + byte[] openBytes = TestByteUtils.createRandomByte(30); + bo.sendResponse(openBytes); + } + + class ServerListener implements ServerStreamChannelMessageListener { + + private final SimpleStreamBO bo; + + public ServerListener(SimpleStreamBO bo) { + this.bo = bo; + } + + @Override + public short handleStreamCreate(ServerStreamChannelContext streamChannelContext, StreamCreatePacket packet) { + bo.addServerStreamChannelContext(streamChannelContext); + return 0; + } + + @Override + public void handleStreamClose(ServerStreamChannelContext streamChannelContext, StreamClosePacket packet) { + bo.removeServerStreamChannelContext(streamChannelContext); + } + + } + + class SimpleStreamBO { + + private final List serverStreamChannelContextList; + + public SimpleStreamBO() { + serverStreamChannelContextList = new CopyOnWriteArrayList(); + } + + public void addServerStreamChannelContext(ServerStreamChannelContext context) { + serverStreamChannelContextList.add(context); + } + + public void removeServerStreamChannelContext(ServerStreamChannelContext context) { + serverStreamChannelContextList.remove(context); + } + + void sendResponse(byte[] data) { + + for (ServerStreamChannelContext context : serverStreamChannelContextList) { + context.getStreamChannel().sendData(data); + } + } + + int getStreamChannelContextSize() { + return serverStreamChannelContextList.size(); + } + } } diff --git a/rpc/src/test/java/com/navercorp/pinpoint/rpc/stream/StreamChannelStateTest.java b/rpc/src/test/java/com/navercorp/pinpoint/rpc/stream/StreamChannelStateTest.java index ac3b653c9..612af4985 100644 --- a/rpc/src/test/java/com/navercorp/pinpoint/rpc/stream/StreamChannelStateTest.java +++ b/rpc/src/test/java/com/navercorp/pinpoint/rpc/stream/StreamChannelStateTest.java @@ -25,60 +25,60 @@ import com.navercorp.pinpoint.rpc.stream.StreamChannelStateCode; public class StreamChannelStateTest { - @Test - public void functionTest1() { - StreamChannelState state = new StreamChannelState(); - Assert.assertEquals(StreamChannelStateCode.NEW, state.getCurrentState()); - - state.changeStateOpen(); - Assert.assertEquals(StreamChannelStateCode.OPEN, state.getCurrentState()); + @Test + public void functionTest1() { + StreamChannelState state = new StreamChannelState(); + Assert.assertEquals(StreamChannelStateCode.NEW, state.getCurrentState()); - state.changeStateOpenAwait(); - Assert.assertEquals(StreamChannelStateCode.OPEN_AWAIT, state.getCurrentState()); - - state.changeStateRun(); - Assert.assertEquals(StreamChannelStateCode.RUN, state.getCurrentState()); - - state.changeStateClose(); - Assert.assertEquals(StreamChannelStateCode.CLOSED, state.getCurrentState()); - } - - @Test - public void functionTest2() { - StreamChannelState state = new StreamChannelState(); - Assert.assertEquals(StreamChannelStateCode.NEW, state.getCurrentState()); - - state.changeStateOpenArrived(); - Assert.assertEquals(StreamChannelStateCode.OPEN_ARRIVED, state.getCurrentState()); + state.changeStateOpen(); + Assert.assertEquals(StreamChannelStateCode.OPEN, state.getCurrentState()); - state.changeStateRun(); - Assert.assertEquals(StreamChannelStateCode.RUN, state.getCurrentState()); - - state.changeStateClose(); - Assert.assertEquals(StreamChannelStateCode.CLOSED, state.getCurrentState()); - } + state.changeStateOpenAwait(); + Assert.assertEquals(StreamChannelStateCode.OPEN_AWAIT, state.getCurrentState()); - @Test - public void functionTest3() { - StreamChannelState state = new StreamChannelState(); - Assert.assertEquals(StreamChannelStateCode.NEW, state.getCurrentState()); - - boolean result = state.changeStateRun(); - Assert.assertFalse(result); - Assert.assertEquals(StreamChannelStateCode.ILLEGAL_STATE, state.getCurrentState()); - } - - @Test - public void functionTest4() { - StreamChannelState state = new StreamChannelState(); - Assert.assertEquals(StreamChannelStateCode.NEW, state.getCurrentState()); - - state.changeStateOpen(); - Assert.assertEquals(StreamChannelStateCode.OPEN, state.getCurrentState()); - - boolean result = state.changeStateRun(); - Assert.assertFalse(result); - Assert.assertEquals(StreamChannelStateCode.ILLEGAL_STATE, state.getCurrentState()); - } + state.changeStateRun(); + Assert.assertEquals(StreamChannelStateCode.RUN, state.getCurrentState()); + + state.changeStateClose(); + Assert.assertEquals(StreamChannelStateCode.CLOSED, state.getCurrentState()); + } + + @Test + public void functionTest2() { + StreamChannelState state = new StreamChannelState(); + Assert.assertEquals(StreamChannelStateCode.NEW, state.getCurrentState()); + + state.changeStateOpenArrived(); + Assert.assertEquals(StreamChannelStateCode.OPEN_ARRIVED, state.getCurrentState()); + + state.changeStateRun(); + Assert.assertEquals(StreamChannelStateCode.RUN, state.getCurrentState()); + + state.changeStateClose(); + Assert.assertEquals(StreamChannelStateCode.CLOSED, state.getCurrentState()); + } + + @Test + public void functionTest3() { + StreamChannelState state = new StreamChannelState(); + Assert.assertEquals(StreamChannelStateCode.NEW, state.getCurrentState()); + + boolean result = state.changeStateRun(); + Assert.assertFalse(result); + Assert.assertEquals(StreamChannelStateCode.ILLEGAL_STATE, state.getCurrentState()); + } + + @Test + public void functionTest4() { + StreamChannelState state = new StreamChannelState(); + Assert.assertEquals(StreamChannelStateCode.NEW, state.getCurrentState()); + + state.changeStateOpen(); + Assert.assertEquals(StreamChannelStateCode.OPEN, state.getCurrentState()); + + boolean result = state.changeStateRun(); + Assert.assertFalse(result); + Assert.assertEquals(StreamChannelStateCode.ILLEGAL_STATE, state.getCurrentState()); + } } diff --git a/rpc/src/test/java/com/navercorp/pinpoint/rpc/util/CopyUtilsTest.java b/rpc/src/test/java/com/navercorp/pinpoint/rpc/util/CopyUtilsTest.java index 5fd020064..a73648a1f 100644 --- a/rpc/src/test/java/com/navercorp/pinpoint/rpc/util/CopyUtilsTest.java +++ b/rpc/src/test/java/com/navercorp/pinpoint/rpc/util/CopyUtilsTest.java @@ -27,57 +27,57 @@ import com.navercorp.pinpoint.rpc.util.CopyUtils; public class CopyUtilsTest { - @Test - public void copyUtilsTest() { - Map original = createSimpleMap("key", 2); + @Test + public void copyUtilsTest() { + Map original = createSimpleMap("key", 2); - Map copied = CopyUtils.mediumCopyMap(original); - Assert.assertEquals(2, copied.get("key")); - Assert.assertEquals(2, original.get("key")); + Map copied = CopyUtils.mediumCopyMap(original); + Assert.assertEquals(2, copied.get("key")); + Assert.assertEquals(2, original.get("key")); - original.put("key", 4); - copied.put("key", 3); - copied.put("new", "new"); + original.put("key", 4); + copied.put("key", 3); + copied.put("new", "new"); - Assert.assertEquals(3, copied.get("key")); - Assert.assertEquals("new", copied.get("new")); - Assert.assertEquals(4, original.get("key")); - } + Assert.assertEquals(3, copied.get("key")); + Assert.assertEquals("new", copied.get("new")); + Assert.assertEquals(4, original.get("key")); + } - @Test - public void copyUtilsTest2() { - Map original = createSimpleMap("key", 2); + @Test + public void copyUtilsTest2() { + Map original = createSimpleMap("key", 2); - Map innerMap = createSimpleMap("innerKey", "inner"); - original.put("map", innerMap); + Map innerMap = createSimpleMap("innerKey", "inner"); + original.put("map", innerMap); - Map copied = CopyUtils.mediumCopyMap(original); + Map copied = CopyUtils.mediumCopyMap(original); - Assert.assertEquals(2, copied.get("key")); - Assert.assertEquals("inner", ((Map) copied.get("map")).get("innerKey")); - Assert.assertEquals(2, original.get("key")); - Assert.assertEquals("inner", ((Map) original.get("map")).get("innerKey")); + Assert.assertEquals(2, copied.get("key")); + Assert.assertEquals("inner", ((Map) copied.get("map")).get("innerKey")); + Assert.assertEquals(2, original.get("key")); + Assert.assertEquals("inner", ((Map) original.get("map")).get("innerKey")); - original.put("key", 3); - copied.put("key", 4); - - innerMap.put("innerKey", "key"); - Map copiedInnerMap = (Map) copied.get("map"); - copiedInnerMap.put("test", "test"); - - Assert.assertEquals(4, copied.get("key")); - Assert.assertEquals("inner", ((Map) copied.get("map")).get("innerKey")); - Assert.assertEquals("test", ((Map) copied.get("map")).get("test")); - Assert.assertEquals(3, original.get("key")); - Assert.assertEquals("key", ((Map) original.get("map")).get("innerKey")); - Assert.assertFalse(((Map) original.get("map")).containsKey("test")); - } + original.put("key", 3); + copied.put("key", 4); - private Map createSimpleMap(Object key, Object value) { - Map map = new HashMap(); - map.put(key, value); + innerMap.put("innerKey", "key"); + Map copiedInnerMap = (Map) copied.get("map"); + copiedInnerMap.put("test", "test"); - return map; - } + Assert.assertEquals(4, copied.get("key")); + Assert.assertEquals("inner", ((Map) copied.get("map")).get("innerKey")); + Assert.assertEquals("test", ((Map) copied.get("map")).get("test")); + Assert.assertEquals(3, original.get("key")); + Assert.assertEquals("key", ((Map) original.get("map")).get("innerKey")); + Assert.assertFalse(((Map) original.get("map")).containsKey("test")); + } + + private Map createSimpleMap(Object key, Object value) { + Map map = new HashMap(); + map.put(key, value); + + return map; + } } diff --git a/rpc/src/test/java/com/navercorp/pinpoint/rpc/util/IDGeneratorTest.java b/rpc/src/test/java/com/navercorp/pinpoint/rpc/util/IDGeneratorTest.java index 3b73c819b..17a542aed 100644 --- a/rpc/src/test/java/com/navercorp/pinpoint/rpc/util/IDGeneratorTest.java +++ b/rpc/src/test/java/com/navercorp/pinpoint/rpc/util/IDGeneratorTest.java @@ -24,19 +24,19 @@ import com.navercorp.pinpoint.rpc.util.IDGenerator; public class IDGeneratorTest { - @Test - public void generatorTest() { - IDGenerator generator = new IDGenerator(); - - Assert.assertEquals(1, generator.generate()); - Assert.assertEquals(2, generator.generate()); - Assert.assertEquals(3, generator.generate()); - - generator = new IDGenerator(2, 3); - - Assert.assertEquals(2, generator.generate()); - Assert.assertEquals(5, generator.generate()); - Assert.assertEquals(8, generator.generate()); - } - + @Test + public void generatorTest() { + IDGenerator generator = new IDGenerator(); + + Assert.assertEquals(1, generator.generate()); + Assert.assertEquals(2, generator.generate()); + Assert.assertEquals(3, generator.generate()); + + generator = new IDGenerator(2, 3); + + Assert.assertEquals(2, generator.generate()); + Assert.assertEquals(5, generator.generate()); + Assert.assertEquals(8, generator.generate()); + } + } diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/ChunkHeaderTBaseDeserializerFactory.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/ChunkHeaderTBaseDeserializerFactory.java index 4e569ab53..f4c12885b 100644 --- a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/ChunkHeaderTBaseDeserializerFactory.java +++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/ChunkHeaderTBaseDeserializerFactory.java @@ -58,8 +58,8 @@ public final class ChunkHeaderTBaseDeserializerFactory implements DeserializerFa @Override - public ChunkHeaderTBaseDeserializer createDeserializer() { + public ChunkHeaderTBaseDeserializer createDeserializer() { return new ChunkHeaderTBaseDeserializer(protocolFactory, locator); - } + } } diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/CommandHeaderTBaseDeserializerFactory.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/CommandHeaderTBaseDeserializerFactory.java index feef2cb6f..6aaad54bf 100644 --- a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/CommandHeaderTBaseDeserializerFactory.java +++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/CommandHeaderTBaseDeserializerFactory.java @@ -24,20 +24,20 @@ import org.apache.thrift.protocol.TProtocolFactory; */ public final class CommandHeaderTBaseDeserializerFactory implements DeserializerFactory { - private final DeserializerFactory factory; + private final DeserializerFactory factory; - public CommandHeaderTBaseDeserializerFactory(String version) { - TBaseLocator commandTbaseLocator = new TCommandRegistry(TCommandTypeVersion.getVersion(version)); + public CommandHeaderTBaseDeserializerFactory(String version) { + TBaseLocator commandTbaseLocator = new TCommandRegistry(TCommandTypeVersion.getVersion(version)); - TProtocolFactory protocolFactory = new TCompactProtocol.Factory(); - HeaderTBaseDeserializerFactory deserializerFactory = new HeaderTBaseDeserializerFactory(protocolFactory, commandTbaseLocator); + TProtocolFactory protocolFactory = new TCompactProtocol.Factory(); + HeaderTBaseDeserializerFactory deserializerFactory = new HeaderTBaseDeserializerFactory(protocolFactory, commandTbaseLocator); - this.factory = new ThreadLocalHeaderTBaseDeserializerFactory(deserializerFactory); - } + this.factory = new ThreadLocalHeaderTBaseDeserializerFactory(deserializerFactory); + } - @Override - public HeaderTBaseDeserializer createDeserializer() { - return this.factory.createDeserializer(); - } + @Override + public HeaderTBaseDeserializer createDeserializer() { + return this.factory.createDeserializer(); + } } diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/CommandHeaderTBaseSerializerFactory.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/CommandHeaderTBaseSerializerFactory.java index ba2c7bd02..a0d7649c8 100644 --- a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/CommandHeaderTBaseSerializerFactory.java +++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/CommandHeaderTBaseSerializerFactory.java @@ -24,26 +24,26 @@ import org.apache.thrift.protocol.TProtocolFactory; */ public final class CommandHeaderTBaseSerializerFactory implements SerializerFactory { - public static final int DEFAULT_SERIALIZER_MAX_SIZE = 1024 * 64; + public static final int DEFAULT_SERIALIZER_MAX_SIZE = 1024 * 64; - private final SerializerFactory factory; + private final SerializerFactory factory; - public CommandHeaderTBaseSerializerFactory(String version) { - this(version, DEFAULT_SERIALIZER_MAX_SIZE); - } + public CommandHeaderTBaseSerializerFactory(String version) { + this(version, DEFAULT_SERIALIZER_MAX_SIZE); + } - public CommandHeaderTBaseSerializerFactory(String version, int outputStreamSize) { - TBaseLocator commandTbaseLocator = new TCommandRegistry(TCommandTypeVersion.getVersion(version)); + public CommandHeaderTBaseSerializerFactory(String version, int outputStreamSize) { + TBaseLocator commandTbaseLocator = new TCommandRegistry(TCommandTypeVersion.getVersion(version)); - TProtocolFactory protocolFactory = new TCompactProtocol.Factory(); - HeaderTBaseSerializerFactory serializerFactory = new HeaderTBaseSerializerFactory(true, outputStreamSize, protocolFactory, commandTbaseLocator); + TProtocolFactory protocolFactory = new TCompactProtocol.Factory(); + HeaderTBaseSerializerFactory serializerFactory = new HeaderTBaseSerializerFactory(true, outputStreamSize, protocolFactory, commandTbaseLocator); - this.factory = new ThreadLocalHeaderTBaseSerializerFactory(serializerFactory); - } + this.factory = new ThreadLocalHeaderTBaseSerializerFactory(serializerFactory); + } - @Override - public HeaderTBaseSerializer createSerializer() { - return this.factory.createSerializer(); - } + @Override + public HeaderTBaseSerializer createSerializer() { + return this.factory.createSerializer(); + } } diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/DefaultTBaseLocator.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/DefaultTBaseLocator.java index d4b5c2f6e..548b0a929 100644 --- a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/DefaultTBaseLocator.java +++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/DefaultTBaseLocator.java @@ -39,9 +39,9 @@ import com.navercorp.pinpoint.thrift.dto.TStringMetaData; */ class DefaultTBaseLocator implements TBaseLocator { - private static final short NETWORK_CHECK = 10; - private static final Header NETWORK_CHECK_HEADER = createHeader(NETWORK_CHECK); - + private static final short NETWORK_CHECK = 10; + private static final Header NETWORK_CHECK_HEADER = createHeader(NETWORK_CHECK); + private static final short SPAN = 40; private static final Header SPAN_HEADER = createHeader(SPAN); @@ -81,7 +81,7 @@ class DefaultTBaseLocator implements TBaseLocator { case AGENT_STAT: return new TAgentStat(); case AGENT_STAT_BATCH: - return new TAgentStatBatch(); + return new TAgentStatBatch(); case SPANCHUNK: return new TSpanChunk(); case SQLMETADATA: @@ -115,7 +115,7 @@ class DefaultTBaseLocator implements TBaseLocator { return AGENT_STAT_HEADER; } if (tbase instanceof TAgentStatBatch) { - return AGENT_STAT_BATCH_HEADER; + return AGENT_STAT_BATCH_HEADER; } if (tbase instanceof TSqlMetaData) { return SQLMETADATA_HEADER; @@ -138,47 +138,47 @@ class DefaultTBaseLocator implements TBaseLocator { @Override public boolean isSupport(short type) { - try { - tBaseLookup(type); - return true; - } catch (TException ignore) { + try { + tBaseLookup(type); + return true; + } catch (TException ignore) { // skip - } - - return false; + } + + return false; } @Override public boolean isSupport(Class clazz) { if (clazz.equals(TSpan.class)) { - return true; + return true; } if (clazz.equals(TSpanChunk.class)) { - return true; + return true; } if (clazz.equals(TAgentInfo.class)) { - return true; + return true; } if (clazz.equals(TAgentStat.class)) { - return true; + return true; } if (clazz.equals(TAgentStatBatch.class)) { - return true; + return true; } if (clazz.equals(TSqlMetaData.class)) { - return true; + return true; } if (clazz.equals(TApiMetaData.class)) { - return true; + return true; } if (clazz.equals(TResult.class)) { - return true; + return true; } if (clazz.equals(TStringMetaData.class)) { - return true; + return true; } if (clazz.equals(NetworkAvailabilityCheckPacket.class)) { - return true; + return true; } return false; diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/HeaderTBaseDeserializerFactory.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/HeaderTBaseDeserializerFactory.java index 75349fd8c..4e58557d2 100644 --- a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/HeaderTBaseDeserializerFactory.java +++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/HeaderTBaseDeserializerFactory.java @@ -58,8 +58,8 @@ public final class HeaderTBaseDeserializerFactory implements DeserializerFactory @Override - public HeaderTBaseDeserializer createDeserializer() { + public HeaderTBaseDeserializer createDeserializer() { return new HeaderTBaseDeserializer(protocolFactory, locator); - } + } } diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/HeaderTBaseSerializer.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/HeaderTBaseSerializer.java index 636ffe45b..38422e718 100644 --- a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/HeaderTBaseSerializer.java +++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/HeaderTBaseSerializer.java @@ -33,7 +33,7 @@ import org.apache.thrift.transport.TIOStreamTransport; */ public class HeaderTBaseSerializer { - private static final String UTF8 = "UTF8"; + private static final String UTF8 = "UTF8"; private final ByteArrayOutputStream baos; private final TProtocol protocol; @@ -43,12 +43,12 @@ public class HeaderTBaseSerializer { * Create a new HeaderTBaseSerializer. */ HeaderTBaseSerializer(ByteArrayOutputStream bos, TProtocolFactory protocolFactory, TBaseLocator locator) { - this.baos = bos; + this.baos = bos; TIOStreamTransport transport = new TIOStreamTransport(bos); this.protocol = protocolFactory.getProtocol(transport); this.locator = locator; } - + /** * Serialize the Thrift object into a byte array. The process is simple, * just clear the byte array output, write the object into it, and grab the @@ -70,9 +70,9 @@ public class HeaderTBaseSerializer { } private void writeHeader(Header header) throws TException { - protocol.writeByte(header.getSignature()); - protocol.writeByte(header.getVersion()); - // fixed size regardless protocol + protocol.writeByte(header.getSignature()); + protocol.writeByte(header.getVersion()); + // fixed size regardless protocol short type = header.getType(); protocol.writeByte(BytesUtils.writeShort1(type)); protocol.writeByte(BytesUtils.writeShort2(type)); diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/NetworkAvailabilityCheckPacket.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/NetworkAvailabilityCheckPacket.java index 699897151..4a7a241d2 100644 --- a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/NetworkAvailabilityCheckPacket.java +++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/NetworkAvailabilityCheckPacket.java @@ -28,59 +28,59 @@ import java.io.UnsupportedEncodingException; */ public class NetworkAvailabilityCheckPacket implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final long serialVersionUID = -1170704876834222604L; - - public transient static final byte[] DATA_OK = getBytes("OK"); + private static final long serialVersionUID = -1170704876834222604L; - private static byte[] getBytes(String str) { - if (str == null) { - throw new NullPointerException("str must not be null"); - } - try { - return str.getBytes("UTF8"); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("encoding error. Caused:" + e.getMessage(), e); - } - } + public transient static final byte[] DATA_OK = getBytes("OK"); - @Override - public void read(TProtocol tProtocol) throws TException { - } + private static byte[] getBytes(String str) { + if (str == null) { + throw new NullPointerException("str must not be null"); + } + try { + return str.getBytes("UTF8"); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException("encoding error. Caused:" + e.getMessage(), e); + } + } - @Override - public void write(TProtocol tProtocol) throws TException { - } + @Override + public void read(TProtocol tProtocol) throws TException { + } - @Override - public TFieldIdEnum fieldForId(int i) { - return null; - } + @Override + public void write(TProtocol tProtocol) throws TException { + } - @Override - public boolean isSet(TFieldIdEnum tFieldIdEnum) { - return false; - } + @Override + public TFieldIdEnum fieldForId(int i) { + return null; + } - @Override - public Object getFieldValue(TFieldIdEnum tFieldIdEnum) { - return null; - } + @Override + public boolean isSet(TFieldIdEnum tFieldIdEnum) { + return false; + } - @Override - public void setFieldValue(TFieldIdEnum tFieldIdEnum, Object o) { - } + @Override + public Object getFieldValue(TFieldIdEnum tFieldIdEnum) { + return null; + } - @Override - public TBase deepCopy() { - return null; - } + @Override + public void setFieldValue(TFieldIdEnum tFieldIdEnum, Object o) { + } - @Override - public void clear() { - } + @Override + public TBase deepCopy() { + return null; + } - @Override - public int compareTo(NetworkAvailabilityCheckPacket o) { - return 0; - } + @Override + public void clear() { + } + + @Override + public int compareTo(NetworkAvailabilityCheckPacket o) { + return 0; + } } diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TBaseLocator.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TBaseLocator.java index b1b46e3de..9ae961fbe 100644 --- a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TBaseLocator.java +++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TBaseLocator.java @@ -30,11 +30,11 @@ public interface TBaseLocator { Header headerLookup(TBase dto) throws TException; - boolean isSupport(short type); + boolean isSupport(short type); - boolean isSupport(Class clazz); - - Header getChunkHeader(); - - boolean isChunkHeader(short type); + boolean isSupport(Class clazz); + + Header getChunkHeader(); + + boolean isChunkHeader(short type); } diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandRegistry.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandRegistry.java index dfcef10e3..81ed31a98 100644 --- a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandRegistry.java +++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandRegistry.java @@ -28,70 +28,70 @@ import org.apache.thrift.TException; */ public class TCommandRegistry implements TBaseLocator { - private final ConcurrentHashMap commandTBaseRepository = new ConcurrentHashMap(); + private final ConcurrentHashMap commandTBaseRepository = new ConcurrentHashMap(); - public TCommandRegistry(TCommandTypeVersion version) { - this(version.getSupportCommandList()); - } - - public TCommandRegistry(List supportCommandList) { - for (TCommandType type : supportCommandList) { - commandTBaseRepository.put(type.getType(), type); - } - } + public TCommandRegistry(TCommandTypeVersion version) { + this(version.getSupportCommandList()); + } - @Override - public TBase tBaseLookup(short type) throws TException { - TCommandType commandTBaseType = commandTBaseRepository.get(type); - if (commandTBaseType == null) { - throw new TException("Unsupported type:" + type); - } + public TCommandRegistry(List supportCommandList) { + for (TCommandType type : supportCommandList) { + commandTBaseRepository.put(type.getType(), type); + } + } - return commandTBaseType.newObject(); - } + @Override + public TBase tBaseLookup(short type) throws TException { + TCommandType commandTBaseType = commandTBaseRepository.get(type); + if (commandTBaseType == null) { + throw new TException("Unsupported type:" + type); + } - @Override - public Header headerLookup(TBase tbase) throws TException { + return commandTBaseType.newObject(); + } + + @Override + public Header headerLookup(TBase tbase) throws TException { if (tbase == null) { throw new IllegalArgumentException("tbase must not be null"); } // Should we preload commandTBaseList for performance? Collection commandTBaseList = commandTBaseRepository.values(); - + for (TCommandType commandTBase : commandTBaseList) { - if (commandTBase.isInstanceOf(tbase)) { - return commandTBase.getHeader(); - } + if (commandTBase.isInstanceOf(tbase)) { + return commandTBase.getHeader(); + } } throw new TException("Unsupported Type" + tbase.getClass()); - } - - @Override - public boolean isSupport(short type) { - TCommandType commandTBaseType = commandTBaseRepository.get(type); + } - if (commandTBaseType != null) { - return true; - } - - return false; - } - - @Override - public boolean isSupport(Class clazz) { + @Override + public boolean isSupport(short type) { + TCommandType commandTBaseType = commandTBaseRepository.get(type); + + if (commandTBaseType != null) { + return true; + } + + return false; + } + + @Override + public boolean isSupport(Class clazz) { // Should we preload commandTBaseList for performance? Collection commandTBaseList = commandTBaseRepository.values(); - + for (TCommandType commandTBase : commandTBaseList) { - if (commandTBase.getClazz().equals(clazz)) { - return true; - } + if (commandTBase.getClazz().equals(clazz)) { + return true; + } } return false; - } + } @Override public Header getChunkHeader() { diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandType.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandType.java index f861ca7ee..b0ac692bf 100644 --- a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandType.java +++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandType.java @@ -32,69 +32,69 @@ public enum TCommandType { // Using reflection would make code cleaner. // But it also makes it hard to handle exception, constructor and will show relatively low performance. - RESULT((short) 320, TResult.class) { - @Override - public TBase newObject() { - return new TResult(); - } - }, - TRANSFER((short) 700, TCommandTransfer.class) { - @Override - public TBase newObject() { - return new TCommandTransfer(); - } - }, - ECHO((short) 710, TCommandEcho.class) { - @Override - public TBase newObject() { - return new TCommandEcho(); - } - }, - THREAD_DUMP((short) 720, TCommandThreadDump.class) { - @Override - public TBase newObject() { - return new TCommandThreadDump(); - } - }, - THREAD_DUMP_RESPONSE((short) 721, TCommandThreadDumpResponse.class) { - @Override - public TBase newObject() { - return new TCommandThreadDumpResponse(); - } - }; + RESULT((short) 320, TResult.class) { + @Override + public TBase newObject() { + return new TResult(); + } + }, + TRANSFER((short) 700, TCommandTransfer.class) { + @Override + public TBase newObject() { + return new TCommandTransfer(); + } + }, + ECHO((short) 710, TCommandEcho.class) { + @Override + public TBase newObject() { + return new TCommandEcho(); + } + }, + THREAD_DUMP((short) 720, TCommandThreadDump.class) { + @Override + public TBase newObject() { + return new TCommandThreadDump(); + } + }, + THREAD_DUMP_RESPONSE((short) 721, TCommandThreadDumpResponse.class) { + @Override + public TBase newObject() { + return new TCommandThreadDumpResponse(); + } + }; - private final short type; - private final Class clazz; - private final Header header; + private final short type; + private final Class clazz; + private final Header header; - private TCommandType(short type, Class clazz) { - this.type = type; - this.clazz = clazz; - this.header = createHeader(type); - } + private TCommandType(short type, Class clazz) { + this.type = type; + this.clazz = clazz; + this.header = createHeader(type); + } - protected short getType() { - return type; - } - - protected Class getClazz() { - return clazz; - } + protected short getType() { + return type; + } - protected boolean isInstanceOf(Object value) { - return this.clazz.isInstance(value); - } - - protected Header getHeader() { - return header; - } - - public abstract TBase newObject(); - - private static Header createHeader(short type) { - Header header = new Header(); - header.setType(type); - return header; - } + protected Class getClazz() { + return clazz; + } + + protected boolean isInstanceOf(Object value) { + return this.clazz.isInstance(value); + } + + protected Header getHeader() { + return header; + } + + public abstract TBase newObject(); + + private static Header createHeader(short type) { + Header header = new Header(); + header.setType(type); + return header; + } } diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandTypeVersion.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandTypeVersion.java index 4d83669d7..8f885208d 100644 --- a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandTypeVersion.java +++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/TCommandTypeVersion.java @@ -26,76 +26,76 @@ import org.apache.thrift.TBase; */ public enum TCommandTypeVersion { - // Match with agent version - V_1_0_2_SNAPSHOT("1.0.2-SNAPSHOT", TCommandType.RESULT, TCommandType.THREAD_DUMP), - V_1_0_2("1.0.2", V_1_0_2_SNAPSHOT), - V_1_0_3_SNAPSHOT("1.0.3-SNAPSHOT", V_1_0_2, TCommandType.ECHO, TCommandType.TRANSFER, TCommandType.THREAD_DUMP_RESPONSE), - V_1_0_3("1.0.3", V_1_0_3_SNAPSHOT), - V_1_0_4_SNAPSHOT("1.0.4-SNAPSHOT", V_1_0_3), - - UNKNOWN("UNKNOWN"); + // Match with agent version + V_1_0_2_SNAPSHOT("1.0.2-SNAPSHOT", TCommandType.RESULT, TCommandType.THREAD_DUMP), + V_1_0_2("1.0.2", V_1_0_2_SNAPSHOT), + V_1_0_3_SNAPSHOT("1.0.3-SNAPSHOT", V_1_0_2, TCommandType.ECHO, TCommandType.TRANSFER, TCommandType.THREAD_DUMP_RESPONSE), + V_1_0_3("1.0.3", V_1_0_3_SNAPSHOT), + V_1_0_4_SNAPSHOT("1.0.4-SNAPSHOT", V_1_0_3), - private final String versionName; - private final List supportCommandList = new ArrayList(); + UNKNOWN("UNKNOWN"); - private TCommandTypeVersion(String versionName, TCommandTypeVersion version, TCommandType... supportCommandArray) { - this.versionName = versionName; - - for (TCommandType supportCommand : version.getSupportCommandList()) { - supportCommandList.add(supportCommand); - } + private final String versionName; + private final List supportCommandList = new ArrayList(); - for (TCommandType supportCommand : supportCommandArray) { - getSupportCommandList().add(supportCommand); - } - } + private TCommandTypeVersion(String versionName, TCommandTypeVersion version, TCommandType... supportCommandArray) { + this.versionName = versionName; - private TCommandTypeVersion(String versionName, TCommandType... supportCommandArray) { - this.versionName = versionName; + for (TCommandType supportCommand : version.getSupportCommandList()) { + supportCommandList.add(supportCommand); + } - for (TCommandType supportCommand : supportCommandArray) { - getSupportCommandList().add(supportCommand); - } - } + for (TCommandType supportCommand : supportCommandArray) { + getSupportCommandList().add(supportCommand); + } + } - public List getSupportCommandList() { - return supportCommandList; - } - - public boolean isSupportCommand(TBase command) { - if (command == null) { - return false; - } - - for (TCommandType eachCommand : supportCommandList) { - if (eachCommand == null) { - continue; - } + private TCommandTypeVersion(String versionName, TCommandType... supportCommandArray) { + this.versionName = versionName; - if (eachCommand.getClazz() == command.getClass()) { - return true; - } - } + for (TCommandType supportCommand : supportCommandArray) { + getSupportCommandList().add(supportCommand); + } + } - return false; - } + public List getSupportCommandList() { + return supportCommandList; + } - public String getVersionName() { - return versionName; - } - - public static TCommandTypeVersion getVersion(String version) { - if (version == null) { - throw new NullPointerException("version may not be null."); - } - - for (TCommandTypeVersion versionType : TCommandTypeVersion.values()) { - if (versionType.getVersionName().equals(version)) { - return versionType; - } - } - - return UNKNOWN; - } + public boolean isSupportCommand(TBase command) { + if (command == null) { + return false; + } + + for (TCommandType eachCommand : supportCommandList) { + if (eachCommand == null) { + continue; + } + + if (eachCommand.getClazz() == command.getClass()) { + return true; + } + } + + return false; + } + + public String getVersionName() { + return versionName; + } + + public static TCommandTypeVersion getVersion(String version) { + if (version == null) { + throw new NullPointerException("version may not be null."); + } + + for (TCommandTypeVersion versionType : TCommandTypeVersion.values()) { + if (versionType.getVersionName().equals(version)) { + return versionType; + } + } + + return UNKNOWN; + } } diff --git a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/UnsafeByteArrayOutputStream.java b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/UnsafeByteArrayOutputStream.java index 9c61dd53b..72ca2c240 100644 --- a/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/UnsafeByteArrayOutputStream.java +++ b/thrift/src/main/java/com/navercorp/pinpoint/thrift/io/UnsafeByteArrayOutputStream.java @@ -27,164 +27,164 @@ import java.util.Arrays; */ public class UnsafeByteArrayOutputStream extends ByteArrayOutputStream { - private static final String UTF8 = "UTF8"; + private static final String UTF8 = "UTF8"; - /** - * Creates a new byte array output stream. The buffer capacity is - * initially 32 bytes, though its size increases if necessary. - */ - public UnsafeByteArrayOutputStream() { - this(32); - } + /** + * Creates a new byte array output stream. The buffer capacity is + * initially 32 bytes, though its size increases if necessary. + */ + public UnsafeByteArrayOutputStream() { + this(32); + } - /** - * Creates a new byte array output stream, with a buffer capacity of - * the specified size, in bytes. - * - * @param size the initial size. - * @throws IllegalArgumentException if size is negative. - */ - public UnsafeByteArrayOutputStream(int size) { - super(size); - } + /** + * Creates a new byte array output stream, with a buffer capacity of + * the specified size, in bytes. + * + * @param size the initial size. + * @throws IllegalArgumentException if size is negative. + */ + public UnsafeByteArrayOutputStream(int size) { + super(size); + } - /** - * Writes the specified byte to this byte array output stream. - * - * @param b the byte to be written. - */ - public void write(int b) { - int newcount = count + 1; - if (newcount > buf.length) { - buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount)); - } - buf[count] = (byte) b; - count = newcount; - } + /** + * Writes the specified byte to this byte array output stream. + * + * @param b the byte to be written. + */ + public void write(int b) { + int newcount = count + 1; + if (newcount > buf.length) { + buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount)); + } + buf[count] = (byte) b; + count = newcount; + } - /** - * Writes len bytes from the specified byte array - * starting at offset off to this byte array output stream. - * - * @param b the data. - * @param off the start offset in the data. - * @param len the number of bytes to write. - */ - public void write(byte b[], int off, int len) { - if ((off < 0) || (off > b.length) || (len < 0) || - ((off + len) > b.length) || ((off + len) < 0)) { - throw new IndexOutOfBoundsException(); - } else if (len == 0) { - return; - } - int newcount = count + len; - if (newcount > buf.length) { - buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount)); - } - System.arraycopy(b, off, buf, count, len); - count = newcount; - } + /** + * Writes len bytes from the specified byte array + * starting at offset off to this byte array output stream. + * + * @param b the data. + * @param off the start offset in the data. + * @param len the number of bytes to write. + */ + public void write(byte b[], int off, int len) { + if ((off < 0) || (off > b.length) || (len < 0) || + ((off + len) > b.length) || ((off + len) < 0)) { + throw new IndexOutOfBoundsException(); + } else if (len == 0) { + return; + } + int newcount = count + len; + if (newcount > buf.length) { + buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount)); + } + System.arraycopy(b, off, buf, count, len); + count = newcount; + } - /** - * Writes the complete contents of this byte array output stream to - * the specified output stream argument, as if by calling the output - * stream's write method using out.write(buf, 0, count). - * - * @param out the output stream to which to write the data. - * @throws java.io.IOException if an I/O error occurs. - */ - public void writeTo(OutputStream out) throws IOException { - out.write(buf, 0, count); - } + /** + * Writes the complete contents of this byte array output stream to + * the specified output stream argument, as if by calling the output + * stream's write method using out.write(buf, 0, count). + * + * @param out the output stream to which to write the data. + * @throws java.io.IOException if an I/O error occurs. + */ + public void writeTo(OutputStream out) throws IOException { + out.write(buf, 0, count); + } - /** - * Resets the count field of this byte array output - * stream to zero, so that all currently accumulated output in the - * output stream is discarded. The output stream can be used again, - * reusing the already allocated buffer space. - * - * @see java.io.ByteArrayInputStream#count - */ - public void reset() { - count = 0; - } + /** + * Resets the count field of this byte array output + * stream to zero, so that all currently accumulated output in the + * output stream is discarded. The output stream can be used again, + * reusing the already allocated buffer space. + * + * @see java.io.ByteArrayInputStream#count + */ + public void reset() { + count = 0; + } - /** - * Creates a newly allocated byte array. Its size is the current - * size of this output stream and the valid contents of the buffer - * have been copied into it. - * - * @return the current contents of this output stream, as a byte array. - * @see java.io.ByteArrayOutputStream#size() - */ - public byte toByteArray()[] { - return buf; - } + /** + * Creates a newly allocated byte array. Its size is the current + * size of this output stream and the valid contents of the buffer + * have been copied into it. + * + * @return the current contents of this output stream, as a byte array. + * @see java.io.ByteArrayOutputStream#size() + */ + public byte toByteArray()[] { + return buf; + } - /** - * Returns the current size of the buffer. - * - * @return the value of the count field, which is the number - * of valid bytes in this output stream. - * @see java.io.ByteArrayOutputStream#count - */ - public int size() { - return count; - } + /** + * Returns the current size of the buffer. + * + * @return the value of the count field, which is the number + * of valid bytes in this output stream. + * @see java.io.ByteArrayOutputStream#count + */ + public int size() { + return count; + } - /** - * Converts the buffer's contents into a string decoding bytes using the - * platform's default character set. The length of the new String - * is a function of the character set, and hence may not be equal to the - * size of the buffer. - *

- *

This method always replaces malformed-input and unmappable-character - * sequences with the default replacement string for the platform's - * default character set. The {@linkplain java.nio.charset.CharsetDecoder} - * class should be used when more control over the decoding process is - * required. - * - * @return String decoded from the buffer's contents. - * @since JDK1.1 - */ - public String toString() { - try { - return toString(UTF8); - } catch (UnsupportedEncodingException ex) { - throw new RuntimeException("toString() fail. Caused:" + ex.getMessage(), ex); - } - } + /** + * Converts the buffer's contents into a string decoding bytes using the + * platform's default character set. The length of the new String + * is a function of the character set, and hence may not be equal to the + * size of the buffer. + *

+ *

This method always replaces malformed-input and unmappable-character + * sequences with the default replacement string for the platform's + * default character set. The {@linkplain java.nio.charset.CharsetDecoder} + * class should be used when more control over the decoding process is + * required. + * + * @return String decoded from the buffer's contents. + * @since JDK1.1 + */ + public String toString() { + try { + return toString(UTF8); + } catch (UnsupportedEncodingException ex) { + throw new RuntimeException("toString() fail. Caused:" + ex.getMessage(), ex); + } + } - /** - * Converts the buffer's contents into a string by decoding the bytes using - * the specified {@link java.nio.charset.Charset charsetName}. The length of - * the new String is a function of the charset, and hence may not be - * equal to the length of the byte array. - *

- *

This method always replaces malformed-input and unmappable-character - * sequences with this charset's default replacement string. The {@link - * java.nio.charset.CharsetDecoder} class should be used when more control - * over the decoding process is required. - * - * @param charsetName the name of a supported - * {@linkplain java.nio.charset.Charset charset} - * @return String decoded from the buffer's contents. - * @throws java.io.UnsupportedEncodingException - * If the named charset is not supported - * @since JDK1.1 - */ - public String toString(String charsetName) - throws UnsupportedEncodingException { - return new String(buf, 0, count, charsetName); - } + /** + * Converts the buffer's contents into a string by decoding the bytes using + * the specified {@link java.nio.charset.Charset charsetName}. The length of + * the new String is a function of the charset, and hence may not be + * equal to the length of the byte array. + *

+ *

This method always replaces malformed-input and unmappable-character + * sequences with this charset's default replacement string. The {@link + * java.nio.charset.CharsetDecoder} class should be used when more control + * over the decoding process is required. + * + * @param charsetName the name of a supported + * {@linkplain java.nio.charset.Charset charset} + * @return String decoded from the buffer's contents. + * @throws java.io.UnsupportedEncodingException + * If the named charset is not supported + * @since JDK1.1 + */ + public String toString(String charsetName) + throws UnsupportedEncodingException { + return new String(buf, 0, count, charsetName); + } - /** - * Closing a ByteArrayOutputStream has no effect. The methods in - * this class can be called after the stream has been closed without - * generating an IOException. - *

- */ - public void close() throws IOException { - } + /** + * Closing a ByteArrayOutputStream has no effect. The methods in + * this class can be called after the stream has been closed without + * generating an IOException. + *

+ */ + public void close() throws IOException { + } } diff --git a/thrift/src/test/java/com/navercorp/pinpoint/thrift/io/HeaderTBaseDeserializerFactoryTest.java b/thrift/src/test/java/com/navercorp/pinpoint/thrift/io/HeaderTBaseDeserializerFactoryTest.java index c0b3dc231..10bcfbad7 100644 --- a/thrift/src/test/java/com/navercorp/pinpoint/thrift/io/HeaderTBaseDeserializerFactoryTest.java +++ b/thrift/src/test/java/com/navercorp/pinpoint/thrift/io/HeaderTBaseDeserializerFactoryTest.java @@ -24,22 +24,22 @@ import com.navercorp.pinpoint.thrift.io.HeaderTBaseSerializerFactory; public class HeaderTBaseDeserializerFactoryTest { - @Test - public void optionTest1() { + @Test + public void optionTest1() { HeaderTBaseSerializerFactory factory = new HeaderTBaseSerializerFactory(); - Assert.assertTrue(factory.isSafetyGuranteed()); - } - - @Test - public void optionTest2() { + Assert.assertTrue(factory.isSafetyGuranteed()); + } + + @Test + public void optionTest2() { HeaderTBaseSerializerFactory factory = new HeaderTBaseSerializerFactory(true, 1); - Assert.assertTrue(factory.isSafetyGuranteed()); - } - - @Test - public void optionTest() { + Assert.assertTrue(factory.isSafetyGuranteed()); + } + + @Test + public void optionTest() { HeaderTBaseSerializerFactory factory = new HeaderTBaseSerializerFactory(false, 1); - Assert.assertFalse(factory.isSafetyGuranteed()); - } + Assert.assertFalse(factory.isSafetyGuranteed()); + } } diff --git a/thrift/src/test/java/com/navercorp/pinpoint/thrift/io/HeaderTBaseSerializerTest.java b/thrift/src/test/java/com/navercorp/pinpoint/thrift/io/HeaderTBaseSerializerTest.java index b08ba12bc..e212f70cb 100644 --- a/thrift/src/test/java/com/navercorp/pinpoint/thrift/io/HeaderTBaseSerializerTest.java +++ b/thrift/src/test/java/com/navercorp/pinpoint/thrift/io/HeaderTBaseSerializerTest.java @@ -40,18 +40,18 @@ public class HeaderTBaseSerializerTest { @Test public void testSerialize1() throws Exception { - HeaderTBaseSerializer serializer = new HeaderTBaseSerializerFactory(false).createSerializer(); - HeaderTBaseDeserializer deserializer = new HeaderTBaseDeserializerFactory().createDeserializer(); - - test(serializer, deserializer); + HeaderTBaseSerializer serializer = new HeaderTBaseSerializerFactory(false).createSerializer(); + HeaderTBaseDeserializer deserializer = new HeaderTBaseDeserializerFactory().createDeserializer(); + + test(serializer, deserializer); } @Test public void testSerialize2() throws Exception { - HeaderTBaseSerializer serializer = new HeaderTBaseSerializerFactory().createSerializer(); - HeaderTBaseDeserializer deserializer = new HeaderTBaseDeserializerFactory().createDeserializer(); - - test(serializer, deserializer); + HeaderTBaseSerializer serializer = new HeaderTBaseSerializerFactory().createSerializer(); + HeaderTBaseDeserializer deserializer = new HeaderTBaseDeserializerFactory().createDeserializer(); + + test(serializer, deserializer); } private void test(HeaderTBaseSerializer serializer, HeaderTBaseDeserializer deserializer) throws TException { diff --git a/thrift/src/test/java/com/navercorp/pinpoint/thrift/io/TCommandRegistryTest.java b/thrift/src/test/java/com/navercorp/pinpoint/thrift/io/TCommandRegistryTest.java index a7159c112..f594875ba 100644 --- a/thrift/src/test/java/com/navercorp/pinpoint/thrift/io/TCommandRegistryTest.java +++ b/thrift/src/test/java/com/navercorp/pinpoint/thrift/io/TCommandRegistryTest.java @@ -34,59 +34,59 @@ import com.navercorp.pinpoint.thrift.io.TCommandTypeVersion; */ public class TCommandRegistryTest { - @Test - public void registryTest1() { - TCommandRegistry registry = new TCommandRegistry(TCommandTypeVersion.UNKNOWN); + @Test + public void registryTest1() { + TCommandRegistry registry = new TCommandRegistry(TCommandTypeVersion.UNKNOWN); - Assert.assertFalse(registry.isSupport(TCommandType.RESULT.getType())); - Assert.assertFalse(registry.isSupport(TCommandType.THREAD_DUMP.getType())); + Assert.assertFalse(registry.isSupport(TCommandType.RESULT.getType())); + Assert.assertFalse(registry.isSupport(TCommandType.THREAD_DUMP.getType())); - Assert.assertFalse(registry.isSupport(TResult.class)); - Assert.assertFalse(registry.isSupport(TCommandThreadDump.class)); - } + Assert.assertFalse(registry.isSupport(TResult.class)); + Assert.assertFalse(registry.isSupport(TCommandThreadDump.class)); + } - @Test(expected = TException.class) - public void registryTest2() throws TException { - TCommandRegistry registry = new TCommandRegistry(TCommandTypeVersion.UNKNOWN); + @Test(expected = TException.class) + public void registryTest2() throws TException { + TCommandRegistry registry = new TCommandRegistry(TCommandTypeVersion.UNKNOWN); - registry.headerLookup(new TResult()); - } + registry.headerLookup(new TResult()); + } - @Test(expected = TException.class) - public void registryTest3() throws TException { - TCommandRegistry registry = new TCommandRegistry(TCommandTypeVersion.UNKNOWN); + @Test(expected = TException.class) + public void registryTest3() throws TException { + TCommandRegistry registry = new TCommandRegistry(TCommandTypeVersion.UNKNOWN); - registry.tBaseLookup(TCommandType.RESULT.getType()); - } + registry.tBaseLookup(TCommandType.RESULT.getType()); + } - @Test - public void registryTest4() { - TCommandRegistry registry = new TCommandRegistry(TCommandTypeVersion.V_1_0_2_SNAPSHOT); + @Test + public void registryTest4() { + TCommandRegistry registry = new TCommandRegistry(TCommandTypeVersion.V_1_0_2_SNAPSHOT); - Assert.assertTrue(registry.isSupport(TCommandType.RESULT.getType())); - Assert.assertTrue(registry.isSupport(TCommandType.THREAD_DUMP.getType())); + Assert.assertTrue(registry.isSupport(TCommandType.RESULT.getType())); + Assert.assertTrue(registry.isSupport(TCommandType.THREAD_DUMP.getType())); - Assert.assertTrue(registry.isSupport(TResult.class)); - Assert.assertTrue(registry.isSupport(TCommandThreadDump.class)); - } - - @Test - public void registryTest5() throws TException { - TCommandRegistry registry = new TCommandRegistry(TCommandTypeVersion.V_1_0_2_SNAPSHOT); + Assert.assertTrue(registry.isSupport(TResult.class)); + Assert.assertTrue(registry.isSupport(TCommandThreadDump.class)); + } - Header header = registry.headerLookup(new TResult()); - Assert.assertNotNull(header); - } - - @Test - public void registryTest6() throws TException { - TCommandRegistry registry = new TCommandRegistry(TCommandTypeVersion.V_1_0_2_SNAPSHOT); + @Test + public void registryTest5() throws TException { + TCommandRegistry registry = new TCommandRegistry(TCommandTypeVersion.V_1_0_2_SNAPSHOT); - TBase tBase = registry.tBaseLookup(TCommandType.RESULT.getType()); - Assert.assertEquals(tBase.getClass(), TResult.class); - - tBase = registry.tBaseLookup(TCommandType.THREAD_DUMP.getType()); - Assert.assertEquals(tBase.getClass(), TCommandThreadDump.class); - } + Header header = registry.headerLookup(new TResult()); + Assert.assertNotNull(header); + } + + @Test + public void registryTest6() throws TException { + TCommandRegistry registry = new TCommandRegistry(TCommandTypeVersion.V_1_0_2_SNAPSHOT); + + TBase tBase = registry.tBaseLookup(TCommandType.RESULT.getType()); + Assert.assertEquals(tBase.getClass(), TResult.class); + + tBase = registry.tBaseLookup(TCommandType.THREAD_DUMP.getType()); + Assert.assertEquals(tBase.getClass(), TCommandThreadDump.class); + } } diff --git a/thrift/src/test/java/com/navercorp/pinpoint/thrift/io/TCommandTypeVersionTest.java b/thrift/src/test/java/com/navercorp/pinpoint/thrift/io/TCommandTypeVersionTest.java index f0d25b83c..970c6b264 100644 --- a/thrift/src/test/java/com/navercorp/pinpoint/thrift/io/TCommandTypeVersionTest.java +++ b/thrift/src/test/java/com/navercorp/pinpoint/thrift/io/TCommandTypeVersionTest.java @@ -30,34 +30,34 @@ import com.navercorp.pinpoint.thrift.io.TCommandTypeVersion; */ public class TCommandTypeVersionTest { - @Test - public void versionTest1() { - TCommandTypeVersion version = TCommandTypeVersion.V_1_0_2_SNAPSHOT; - - List supportTypeList = version.getSupportCommandList(); + @Test + public void versionTest1() { + TCommandTypeVersion version = TCommandTypeVersion.V_1_0_2_SNAPSHOT; - Assert.assertEquals(2, supportTypeList.size()); - Assert.assertTrue(supportTypeList.contains(TCommandType.THREAD_DUMP)); - Assert.assertTrue(supportTypeList.contains(TCommandType.RESULT)); - } + List supportTypeList = version.getSupportCommandList(); + + Assert.assertEquals(2, supportTypeList.size()); + Assert.assertTrue(supportTypeList.contains(TCommandType.THREAD_DUMP)); + Assert.assertTrue(supportTypeList.contains(TCommandType.RESULT)); + } + + @Test + public void versionTest2() { + TCommandTypeVersion version = TCommandTypeVersion.UNKNOWN; + + List supportTypeList = version.getSupportCommandList(); + + Assert.assertEquals(0, supportTypeList.size()); + } + + @Test + public void versionTest3() { + TCommandTypeVersion version = TCommandTypeVersion.getVersion("1.0.0"); + Assert.assertEquals(TCommandTypeVersion.UNKNOWN, version); + + version = TCommandTypeVersion.getVersion(TCommandTypeVersion.V_1_0_2_SNAPSHOT.getVersionName()); + Assert.assertEquals(TCommandTypeVersion.V_1_0_2_SNAPSHOT, version); + } - @Test - public void versionTest2() { - TCommandTypeVersion version = TCommandTypeVersion.UNKNOWN; - - List supportTypeList = version.getSupportCommandList(); - Assert.assertEquals(0, supportTypeList.size()); - } - - @Test - public void versionTest3() { - TCommandTypeVersion version = TCommandTypeVersion.getVersion("1.0.0"); - Assert.assertEquals(TCommandTypeVersion.UNKNOWN, version); - - version = TCommandTypeVersion.getVersion(TCommandTypeVersion.V_1_0_2_SNAPSHOT.getVersionName()); - Assert.assertEquals(TCommandTypeVersion.V_1_0_2_SNAPSHOT, version); - } - - } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/alarm/checker/SlowRateChecker.java b/web/src/main/java/com/navercorp/pinpoint/web/alarm/checker/SlowRateChecker.java index b855f778d..3877c26db 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/alarm/checker/SlowRateChecker.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/alarm/checker/SlowRateChecker.java @@ -25,11 +25,11 @@ import com.navercorp.pinpoint.web.alarm.vo.Rule; */ public class SlowRateChecker extends AlarmChecker { - public SlowRateChecker(ResponseTimeDataCollector dataCollector, Rule rule) { + public SlowRateChecker(ResponseTimeDataCollector dataCollector, Rule rule) { super(rule, "%", dataCollector); - } + } - @Override + @Override protected long getDetectedValue() { return ((ResponseTimeDataCollector)dataCollector).getSlowRate(); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/alarm/vo/Rule.java b/web/src/main/java/com/navercorp/pinpoint/web/alarm/vo/Rule.java index 15793115b..410af44fb 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/alarm/vo/Rule.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/alarm/vo/Rule.java @@ -24,83 +24,83 @@ import org.apache.ibatis.type.Alias; @Alias(value = "rule") public class Rule { - private String id; - private String applicationId; - private String CheckerName; - private Integer threshold; - private String empGroup; - private boolean smsSend; - private boolean emailSend; - private String notes; - - public Rule() { - } - - public Rule(String applicationId, String checkerName, Integer Threshold, String empGroup, boolean smsSend, boolean emailSend, String notes) { - this.applicationId = applicationId; - this.CheckerName = checkerName; - this.threshold = Threshold; - this.empGroup = empGroup; - this.smsSend = smsSend; - this.emailSend = emailSend; - this.notes = notes; - } - - public String getApplicationId() { - return applicationId; - } - - public void setApplicationId(String applicationId) { - this.applicationId = applicationId; - } - - public String getCheckerName() { - return CheckerName; - } - - public void setCheckerName(String checkerName) { - CheckerName = checkerName; - } - - public Integer getThreshold() { - return threshold; - } - - public void setThreshold(Integer threshold) { - this.threshold = threshold; - } - - public String getEmpGroup() { - return empGroup; - } - - public void setEmpGroup(String empGroup) { - this.empGroup = empGroup; - } + private String id; + private String applicationId; + private String CheckerName; + private Integer threshold; + private String empGroup; + private boolean smsSend; + private boolean emailSend; + private String notes; - public boolean isSmsSend() { - return smsSend; - } + public Rule() { + } - public void setSmsSend(boolean smsSend) { - this.smsSend = smsSend; - } + public Rule(String applicationId, String checkerName, Integer Threshold, String empGroup, boolean smsSend, boolean emailSend, String notes) { + this.applicationId = applicationId; + this.CheckerName = checkerName; + this.threshold = Threshold; + this.empGroup = empGroup; + this.smsSend = smsSend; + this.emailSend = emailSend; + this.notes = notes; + } - public boolean isEmailSend() { - return emailSend; - } + public String getApplicationId() { + return applicationId; + } - public void setEmailSend(boolean emailSend) { - this.emailSend = emailSend; - } + public void setApplicationId(String applicationId) { + this.applicationId = applicationId; + } - public String getId() { - return id; - } + public String getCheckerName() { + return CheckerName; + } - public void setId(String id) { - this.id = id; - } + public void setCheckerName(String checkerName) { + CheckerName = checkerName; + } + + public Integer getThreshold() { + return threshold; + } + + public void setThreshold(Integer threshold) { + this.threshold = threshold; + } + + public String getEmpGroup() { + return empGroup; + } + + public void setEmpGroup(String empGroup) { + this.empGroup = empGroup; + } + + public boolean isSmsSend() { + return smsSend; + } + + public void setSmsSend(boolean smsSend) { + this.smsSend = smsSend; + } + + public boolean isEmailSend() { + return emailSend; + } + + public void setEmailSend(boolean emailSend) { + this.emailSend = emailSend; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } public String getNotes() { return notes; diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMap.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMap.java index a8a51f637..668d5fc2c 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMap.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMap.java @@ -34,7 +34,7 @@ import org.slf4j.LoggerFactory; */ public class ApplicationMap { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final NodeList nodeList; private final LinkList linkList; @@ -44,7 +44,7 @@ public class ApplicationMap { private List applicationScatterScanResultList; - ApplicationMap(Range range, NodeList nodeList, LinkList linkList) { + ApplicationMap(Range range, NodeList nodeList, LinkList linkList) { if (range == null) { throw new NullPointerException("range must not be null"); } @@ -57,17 +57,17 @@ public class ApplicationMap { this.range = range; this.nodeList = nodeList; this.linkList = linkList; - } + } @JsonProperty("nodeDataArray") public Collection getNodes() { - return this.nodeList.getNodeList(); - } + return this.nodeList.getNodeList(); + } @JsonProperty("linkDataArray") - public Collection getLinks() { - return this.linkList.getLinkList(); - } + public Collection getLinks() { + return this.linkList.getLinkList(); + } public void setApplicationScatterScanResult(List applicationScatterScanResultList) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/Link.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/Link.java index 0e1f67cb7..c5a71ccaf 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/Link.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/Link.java @@ -101,17 +101,17 @@ public class Link { } - public LinkKey getLinkKey() { - return new LinkKey(fromNode.getApplication(), toNode.getApplication()); - } + public LinkKey getLinkKey() { + return new LinkKey(fromNode.getApplication(), toNode.getApplication()); + } - public Node getFrom() { - return fromNode; - } + public Node getFrom() { + return fromNode; + } - public Node getTo() { - return toNode; - } + public Node getTo() { + return toNode; + } public String getLinkName() { return fromNode.getNodeName() + LINK_DELIMITER + toNode.getNodeName(); @@ -134,17 +134,17 @@ public class Link { } } - public AgentHistogramList getTargetList() { - return sourceLinkCallDataMap.getTargetList(); - } + public AgentHistogramList getTargetList() { + return sourceLinkCallDataMap.getTargetList(); + } - public Histogram getHistogram() { + public Histogram getHistogram() { if (linkHistogram == null) { linkHistogram = createHistogram0(); } return linkHistogram; - } + } private Histogram createHistogram0() { // need serviceType of target (callee) diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/Node.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/Node.java index 43ae09a6a..5d9fa0780 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/Node.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/Node.java @@ -80,8 +80,8 @@ public class Node { } public ServerInstanceList getServerInstanceList() { - return serverInstanceList; - } + return serverInstanceList; + } @JsonIgnore public String getNodeJson() { @@ -109,13 +109,13 @@ public class Node { } - public String getNodeName() { - return application.getName() + NODE_DELIMITER + application.getServiceType(); - } + public String getNodeName() { + return application.getName() + NODE_DELIMITER + application.getServiceType(); + } - public ServiceType getServiceType() { - return application.getServiceType(); - } + public ServiceType getServiceType() { + return application.getServiceType(); + } public NodeHistogram getNodeHistogram() { return nodeHistogram; @@ -125,8 +125,8 @@ public class Node { this.nodeHistogram = nodeHistogram; } - @Override - public String toString() { - return "Node [" + application + "]"; - } + @Override + public String toString() { + return "Node [" + application + "]"; + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstance.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstance.java index 1965c4422..4f105fc19 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstance.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstance.java @@ -33,11 +33,11 @@ public class ServerInstance { private final String hostName; private final String name; - private final ServiceType serviceType; + private final ServiceType serviceType; private final ServerType serverType; - private final AgentInfoBo agentInfo; + private final AgentInfoBo agentInfo; // it is better for something else to inject this. @@ -46,19 +46,19 @@ public class ServerInstance { private ServerMatcher match; - public ServerInstance(AgentInfoBo agentInfo) { + public ServerInstance(AgentInfoBo agentInfo) { if (agentInfo == null) { throw new NullPointerException("agentInfo must not be null"); } this.hostName = agentInfo.getHostName(); this.name = agentInfo.getAgentId(); - this.serviceType = agentInfo.getServiceType(); - this.agentInfo = agentInfo; + this.serviceType = agentInfo.getServiceType(); + this.agentInfo = agentInfo; this.serverType = ServerType.Physical; this.match = MATCHER_GROUP.match(hostName); - } + } - public ServerInstance(String hostName, String physicalName, ServiceType serviceType) { + public ServerInstance(String hostName, String physicalName, ServiceType serviceType) { if (hostName == null) { throw new NullPointerException("hostName must not be null"); } @@ -70,11 +70,11 @@ public class ServerInstance { } this.hostName = hostName; this.name = physicalName; - this.serviceType = serviceType; - this.agentInfo = null; + this.serviceType = serviceType; + this.agentInfo = null; this.serverType = ServerType.Logical; this.match = MATCHER_GROUP.match(hostName); - } + } @JsonIgnore public String getHostName() { @@ -97,9 +97,9 @@ public class ServerInstance { } @JsonProperty("agentInfo") - public AgentInfoBo getAgentInfo() { - return agentInfo; - } + public AgentInfoBo getAgentInfo() { + return agentInfo; + } @JsonProperty("linkName") public String getLinkName() { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceList.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceList.java index f731e018d..c90bcc6bd 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceList.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerInstanceList.java @@ -38,14 +38,14 @@ import com.navercorp.pinpoint.web.view.ServerInstanceListSerializer; @JsonSerialize(using = ServerInstanceListSerializer.class) public class ServerInstanceList { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final Map> serverInstanceList = new TreeMap>(); + private final Map> serverInstanceList = new TreeMap>(); private MatcherGroup matcherGroup = new MatcherGroup(); - public ServerInstanceList() { - } + public ServerInstanceList() { + } public ServerInstanceList(MatcherGroup matcherGroup) { if (matcherGroup != null) { @@ -53,42 +53,42 @@ public class ServerInstanceList { } } - public Map> getServerInstanceList() { - // XXX list sorting problem exist - return serverInstanceList; - } + public Map> getServerInstanceList() { + // XXX list sorting problem exist + return serverInstanceList; + } - public int getInstanceCount() { - int count = 0; - for (List entry : serverInstanceList.values()) { - count += entry.size(); - } - return count; - } + public int getInstanceCount() { + int count = 0; + for (List entry : serverInstanceList.values()) { + count += entry.size(); + } + return count; + } - private void addServerInstance(List nodeList, ServerInstance serverInstance) { - for (ServerInstance node : nodeList) { - boolean equalsNode = node.equals(serverInstance); - if (equalsNode) { - return; - } - } - nodeList.add(serverInstance); - } + private void addServerInstance(List nodeList, ServerInstance serverInstance) { + for (ServerInstance node : nodeList) { + boolean equalsNode = node.equals(serverInstance); + if (equalsNode) { + return; + } + } + nodeList.add(serverInstance); + } - private List getServerInstanceList(String hostName) { - List find = serverInstanceList.get(hostName); - if (find == null) { - find = new ArrayList(); - serverInstanceList.put(hostName, find); - } - return find; - } + private List getServerInstanceList(String hostName) { + List find = serverInstanceList.get(hostName); + if (find == null) { + find = new ArrayList(); + serverInstanceList.put(hostName, find); + } + return find; + } - void addServerInstance(ServerInstance serverInstance) { - List find = getServerInstanceList(serverInstance.getHostName()); - addServerInstance(find, serverInstance); - } + void addServerInstance(ServerInstance serverInstance) { + List find = getServerInstanceList(serverInstance.getHostName()); + addServerInstance(find, serverInstance); + } public Map getLink(String serverName) { ServerMatcher serverMatcher = matcherGroup.match(serverName); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/Histogram.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/Histogram.java index 7130b4b31..ab198ce8f 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/Histogram.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/Histogram.java @@ -32,22 +32,22 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize; @JsonSerialize(using=HistogramSerializer.class) public class Histogram { - private final HistogramSchema schema; + private final HistogramSchema schema; private long fastCount; private long normalCount; private long slowCount; private long verySlowCount; - private long errorCount; + private long errorCount; public Histogram(ServiceType serviceType) { if (serviceType == null) { throw new NullPointerException("serviceType must not be null"); } - this.schema = serviceType.getHistogramSchema(); - } + this.schema = serviceType.getHistogramSchema(); + } public Histogram(HistogramSchema schema) { if (schema == null) { @@ -67,18 +67,18 @@ public class Histogram { this(ServiceType.findServiceType(serviceType)); } - // TODO one may extract slot number from this class - public void addCallCount(final short slotTime, final long count) { + // TODO one may extract slot number from this class + public void addCallCount(final short slotTime, final long count) { final HistogramSchema schema = this.schema; - if (slotTime == schema.getVerySlowSlot().getSlotTime()) { // 0 is slow slotTime - this.verySlowCount += count; + if (slotTime == schema.getVerySlowSlot().getSlotTime()) { // 0 is slow slotTime + this.verySlowCount += count; return; - } + } if (slotTime == schema.getErrorSlot().getSlotTime()) { // -1 is error - this.errorCount += count; - return; - } - // TODO if clause condition should be "==", not "<=" + this.errorCount += count; + return; + } + // TODO if clause condition should be "==", not "<=" if (slotTime <= schema.getFastSlot().getSlotTime()) { this.fastCount += count; return; @@ -92,16 +92,16 @@ public class Histogram { return; } throw new IllegalArgumentException("slot not found slotTime:" + slotTime + " count:" + count); - } + } - public HistogramSchema getHistogramSchema() { - return this.schema; - } + public HistogramSchema getHistogramSchema() { + return this.schema; + } - public long getErrorCount() { - return errorCount; - } + public long getErrorCount() { + return errorCount; + } public long getFastCount() { return fastCount; @@ -116,12 +116,12 @@ public class Histogram { } public long getVerySlowCount() { - return verySlowCount; - } + return verySlowCount; + } - public long getTotalCount() { - return errorCount + fastCount + normalCount + slowCount + verySlowCount; - } + public long getTotalCount() { + return errorCount + fastCount + normalCount + slowCount + verySlowCount; + } public long getSuccessCount() { return fastCount + normalCount + slowCount + verySlowCount; @@ -147,7 +147,7 @@ public class Histogram { throw new IllegalArgumentException("slotType:" + slotType); } - public void add(final Histogram histogram) { + public void add(final Histogram histogram) { if (histogram == null) { throw new NullPointerException("histogram must not be null"); } @@ -161,7 +161,7 @@ public class Histogram { this.verySlowCount += histogram.verySlowCount; this.errorCount += histogram.errorCount; - } + } @Override diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/AgentHistogram.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/AgentHistogram.java index 821b199d4..95227fdca 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/AgentHistogram.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/AgentHistogram.java @@ -34,21 +34,21 @@ import java.util.Map; */ public class AgentHistogram { - /** - * to uniquely identify a host from UI, we can use things like hostname, agentId, endpoint, etc - */ - private final Application agentId; + /** + * to uniquely identify a host from UI, we can use things like hostname, agentId, endpoint, etc + */ + private final Application agentId; private final Map timeHistogramMap; - public AgentHistogram(Application agentId) { + public AgentHistogram(Application agentId) { if (agentId == null) { throw new NullPointerException("agentId must not be null"); } this.agentId = agentId; this.timeHistogramMap = new HashMap(); - } + } public AgentHistogram(AgentHistogram copyAgentHistogram) { if (copyAgentHistogram == null) { @@ -63,8 +63,8 @@ public class AgentHistogram { @JsonProperty("name") public String getId() { - return agentId.getName(); - } + return agentId.getName(); + } @JsonIgnore public Application getAgentId() { @@ -72,18 +72,18 @@ public class AgentHistogram { } @JsonIgnore - public ServiceType getServiceType() { - return agentId.getServiceType(); - } + public ServiceType getServiceType() { + return agentId.getServiceType(); + } @JsonProperty("histogram") - public Histogram getHistogram() { + public Histogram getHistogram() { Histogram histogram = new Histogram(agentId.getServiceType()); for (TimeHistogram timeHistogram : timeHistogramMap.values()) { histogram.add(timeHistogram); } return histogram; - } + } @JsonIgnore public Collection getTimeHistogram() { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkCallData.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkCallData.java index 585956512..a9bd65042 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkCallData.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkCallData.java @@ -32,10 +32,10 @@ public class LinkCallData { private final String source; private final ServiceType sourceServiceType; - private final String target; - private final ServiceType targetServiceType; + private final String target; + private final ServiceType targetServiceType; - private final Map targetHistogramTimeMap; + private final Map targetHistogramTimeMap; public LinkCallData(LinkKey linkKey) { if (linkKey == null) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkData.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkData.java index 205546911..afd57a20b 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkData.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkData.java @@ -36,7 +36,7 @@ public class LinkData { private LinkCallDataMap linkCallDataMap; - public LinkData(Application fromApplication, Application toApplication) { + public LinkData(Application fromApplication, Application toApplication) { if (fromApplication == null) { throw new NullPointerException("fromApplication must not be null"); } @@ -45,10 +45,10 @@ public class LinkData { } this.fromApplication = fromApplication; - this.toApplication = toApplication; + this.toApplication = toApplication; this.linkCallDataMap = new LinkCallDataMap(); - } + } // deliberately not implemented as a copy constructor public LinkData(Application fromApplication, Application toApplication, LinkCallDataMap linkCallDataMap) { @@ -65,18 +65,18 @@ public class LinkData { } /** - * - * @param hostname - * host name or endpoint - * @param slot - * @param count - */ - public void addLinkData(String callerAgentId, short callerServiceTypeCode, String hostname, short serviceTypeCode, long timestamp, short slot, long count) { + * + * @param hostname + * host name or endpoint + * @param slot + * @param count + */ + public void addLinkData(String callerAgentId, short callerServiceTypeCode, String hostname, short serviceTypeCode, long timestamp, short slot, long count) { if (hostname == null) { throw new NullPointerException("hostname must not be null"); } this.linkCallDataMap.addCallData(callerAgentId, callerServiceTypeCode, hostname, serviceTypeCode, timestamp, slot, count); - } + } public void resetLinkData() { this.linkCallDataMap = new LinkCallDataMap(); @@ -98,22 +98,22 @@ public class LinkData { public AgentHistogramList getTargetList() { return linkCallDataMap.getTargetList(); - } + } public AgentHistogramList getSourceList() { return linkCallDataMap.getSourceList(); } - public void add(final LinkData linkData) { + public void add(final LinkData linkData) { if (linkData == null) { throw new NullPointerException("linkData must not be null"); } if (!this.equals(linkData)) { throw new IllegalArgumentException("Can't merge with different link."); - } + } final LinkCallDataMap target = linkData.linkCallDataMap; this.linkCallDataMap.addLinkDataMap(target); - } + } @Override public String toString() { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkDataDuplexMap.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkDataDuplexMap.java index b81afaeb7..bb3893891 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkDataDuplexMap.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkDataDuplexMap.java @@ -29,10 +29,10 @@ public class LinkDataDuplexMap { private final LinkDataMap targetLinkDataMap; - public LinkDataDuplexMap() { + public LinkDataDuplexMap() { this.sourceLinkDataMap = new LinkDataMap(); this.targetLinkDataMap = new LinkDataMap(); - } + } public LinkDataMap getSourceLinkDataMap() { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkDataMap.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkDataMap.java index cb34e1532..c135d5d7c 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkDataMap.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkDataMap.java @@ -24,8 +24,8 @@ import com.navercorp.pinpoint.web.vo.LinkKey; public class LinkDataMap { private final Map linkDataMap = new HashMap(); - public LinkDataMap() { - } + public LinkDataMap() { + } public LinkDataMap(LinkDataMap copyLinkDataMap) { if (copyLinkDataMap == null) { @@ -44,10 +44,10 @@ public class LinkDataMap { } - @Override - public String toString() { - return "LinkDataMap [" + linkDataMap + "]"; - } + @Override + public String toString() { + return "LinkDataMap [" + linkDataMap + "]"; + } public void addLinkDataMap(LinkDataMap linkDataMap) { if (linkDataMap == null) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/batch/JobLaunchSupport.java b/web/src/main/java/com/navercorp/pinpoint/web/batch/JobLaunchSupport.java index 75d1a5707..53a7471c0 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/batch/JobLaunchSupport.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/batch/JobLaunchSupport.java @@ -34,63 +34,63 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.Assert; public class JobLaunchSupport implements InitializingBean { - - private final Logger logger = LoggerFactory.getLogger(getClass()); - - @Autowired - private JobLocator locator; - @Autowired - private JobLauncher launcher; - - private String batchServerIp; - public void setBatchServerIp(String batchServerIp) { - this.batchServerIp = batchServerIp; - } + private final Logger logger = LoggerFactory.getLogger(getClass()); - public JobExecution run(String jobName, JobParameters params) { - if(!decisionBatchServer()) { - return null; - } - try { - Job job = locator.getJob(jobName); - return launcher.run(job, params); - } catch (Exception e) { - throw new IllegalStateException(e); - } - } + @Autowired + private JobLocator locator; + @Autowired + private JobLauncher launcher; - private boolean decisionBatchServer() { - Enumeration interfaces; - - try { - interfaces = NetworkInterface.getNetworkInterfaces(); - } catch (SocketException e) { - logger.error("not found network nterface", e); - return false; - } + private String batchServerIp; - while (interfaces.hasMoreElements()) { - NetworkInterface network = interfaces.nextElement(); - Enumeration inets = network.getInetAddresses(); - - while (inets.hasMoreElements()) { - InetAddress next = inets.nextElement(); - - if (next instanceof Inet4Address) { - if (next.getHostAddress().equals(batchServerIp)) { - return true; - } - } - } - } - - return false; - } + public void setBatchServerIp(String batchServerIp) { + this.batchServerIp = batchServerIp; + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(locator, "jobLocator name must be provided"); - Assert.notNull(launcher, "jobLauncher name must be provided"); - } + public JobExecution run(String jobName, JobParameters params) { + if(!decisionBatchServer()) { + return null; + } + try { + Job job = locator.getJob(jobName); + return launcher.run(job, params); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private boolean decisionBatchServer() { + Enumeration interfaces; + + try { + interfaces = NetworkInterface.getNetworkInterfaces(); + } catch (SocketException e) { + logger.error("not found network nterface", e); + return false; + } + + while (interfaces.hasMoreElements()) { + NetworkInterface network = interfaces.nextElement(); + Enumeration inets = network.getInetAddresses(); + + while (inets.hasMoreElements()) { + InetAddress next = inets.nextElement(); + + if (next instanceof Inet4Address) { + if (next.getHostAddress().equals(batchServerIp)) { + return true; + } + } + } + } + + return false; + } + + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(locator, "jobLocator name must be provided"); + Assert.notNull(launcher, "jobLauncher name must be provided"); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanAlign.java b/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanAlign.java index 5fac07a63..8ce71d5ea 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanAlign.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanAlign.java @@ -23,22 +23,22 @@ import com.navercorp.pinpoint.common.bo.SpanEventBo; * @author emeroad */ public class SpanAlign { - private int depth; - private SpanBo spanBo; - private SpanEventBo spanEventBo; - private boolean span = true; - private boolean hasChild = false; + private int depth; + private SpanBo spanBo; + private SpanEventBo spanEventBo; + private boolean span = true; + private boolean hasChild = false; - public SpanAlign(int depth, SpanBo spanBo) { + public SpanAlign(int depth, SpanBo spanBo) { if (spanBo == null) { throw new NullPointerException("spanBo must not be null"); } this.depth = depth; - this.spanBo = spanBo; - this.span = true; - } - - public SpanAlign(int depth, SpanBo spanBo, SpanEventBo spanEventBo) { + this.spanBo = spanBo; + this.span = true; + } + + public SpanAlign(int depth, SpanBo spanBo, SpanEventBo spanEventBo) { if (spanBo == null) { throw new NullPointerException("spanBo must not be null"); } @@ -46,38 +46,38 @@ public class SpanAlign { throw new NullPointerException("spanEventBo must not be null"); } this.depth = depth; - this.spanBo = spanBo; - this.spanEventBo = spanEventBo; - this.span = false; - } + this.spanBo = spanBo; + this.spanEventBo = spanEventBo; + this.span = false; + } - public void setSpan(boolean span) { - this.span = span; - } + public void setSpan(boolean span) { + this.span = span; + } - public boolean isSpan() { - return span; - } + public boolean isSpan() { + return span; + } - public int getDepth() { - return depth; - } + public int getDepth() { + return depth; + } - public SpanBo getSpanBo() { - return spanBo; - } + public SpanBo getSpanBo() { + return spanBo; + } - public SpanEventBo getSpanEventBo() { - return spanEventBo; - } + public SpanEventBo getSpanEventBo() { + return spanEventBo; + } public boolean isHasChild() { - return hasChild; - } + return hasChild; + } - public void setHasChild(boolean hasChild) { - this.hasChild = hasChild; - } + public void setHasChild(boolean hasChild) { + this.hasChild = hasChild; + } @Override public String toString() { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanAligner2.java b/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanAligner2.java index 1b67450fc..b4fd2c216 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanAligner2.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanAligner2.java @@ -41,11 +41,11 @@ public class SpanAligner2 { private static final Long ROOT = -1L; - private final Map> spanIdMap; - private Long rootSpanId = null; + private final Map> spanIdMap; + private Long rootSpanId = null; private int matchType = FAIL_MATCH; - public SpanAligner2(List spans, long collectorAcceptTime) { + public SpanAligner2(List spans, long collectorAcceptTime) { this.spanIdMap = buildSpanMap(spans); this.rootSpanId = findRootSpanId(spans, collectorAcceptTime); } @@ -127,10 +127,10 @@ public class SpanAligner2 { } public List sort() { - final List rootList = spanIdMap.remove(rootSpanId); - if (rootList == null || rootList.size() == 0) { - throw new IllegalStateException("rootList span not found. rootSpanId=" + rootSpanId + ", map=" + spanIdMap.keySet()); - } + final List rootList = spanIdMap.remove(rootSpanId); + if (rootList == null || rootList.size() == 0) { + throw new IllegalStateException("rootList span not found. rootSpanId=" + rootSpanId + ", map=" + spanIdMap.keySet()); + } if (rootList.size() > 1) { throw new IllegalStateException("duplicate rootList span found. rootSpanId=" + rootSpanId + ", map=" + spanIdMap.keySet()); } @@ -138,8 +138,8 @@ public class SpanAligner2 { final List list = new ArrayList(); populate(rootSpanBo, 0, list); - return list; - } + return list; + } public int getMatchType() { return matchType; @@ -147,33 +147,33 @@ public class SpanAligner2 { private void populate(SpanBo span, int spanDepth, List container) { logger.debug("populate start"); - int currentDepth = spanDepth; + int currentDepth = spanDepth; if (logger.isDebugEnabled()) { logger.debug("span type:{} depth:{} spanDepth:{} ", currentDepth, span.getServiceType(), spanDepth); } - SpanAlign spanAlign = new SpanAlign(currentDepth, span); - container.add(spanAlign); + SpanAlign spanAlign = new SpanAlign(currentDepth, span); + container.add(spanAlign); - List spanEventBoList = span.getSpanEventBoList(); + List spanEventBoList = span.getSpanEventBoList(); if (spanEventBoList == null) { return; } spanAlign.setHasChild(true); - for (SpanEventBo spanEventBo : spanEventBoList) { - if (spanEventBo. getDepth() != -1) { - currentDepth = spanDepth + spanEventBo.getDepth(); - } + for (SpanEventBo spanEventBo : spanEventBoList) { + if (spanEventBo. getDepth() != -1) { + currentDepth = spanDepth + spanEventBo.getDepth(); + } if (logger.isDebugEnabled()) { logger.debug("spanEvent type:{} depth:{} spanEventDepth:{} ", spanEventBo.getServiceType(), currentDepth, spanEventBo.getDepth()); } - SpanAlign spanEventAlign = new SpanAlign(currentDepth, span, spanEventBo); - container.add(spanEventAlign); + SpanAlign spanEventAlign = new SpanAlign(currentDepth, span, spanEventBo); + container.add(spanEventAlign); - final long nextSpanId = spanEventBo.getNextSpanId(); + final long nextSpanId = spanEventBo.getNextSpanId(); final List nextSpanBoList = spanIdMap.remove(nextSpanId); if (nextSpanId != ROOT && nextSpanBoList != null) { int childDepth = currentDepth + 1; @@ -184,10 +184,10 @@ public class SpanAligner2 { } else { logger.debug("nextSpanId not found. {}", nextSpanId); } - } - } + } + } logger.debug("populate end"); - } + } // fix nextSpan collision problem private SpanBo getNextSpan(SpanBo span, SpanEventBo beforeSpanEventBo, List nextSpanBoList) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/cluster/ClusterManager.java b/web/src/main/java/com/navercorp/pinpoint/web/cluster/ClusterManager.java index 756cd9d4e..186daaa2a 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/cluster/ClusterManager.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/cluster/ClusterManager.java @@ -23,10 +23,10 @@ import java.util.List; */ public interface ClusterManager { - boolean registerWebCluster(String zNodeName, byte[] contents); + boolean registerWebCluster(String zNodeName, byte[] contents); - void close(); + void close(); - List getRegisteredAgentList(String applicationName, String agentId, long startTimeStamp); + List getRegisteredAgentList(String applicationName, String agentId, long startTimeStamp); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/cluster/CollectorClusterInfoRepository.java b/web/src/main/java/com/navercorp/pinpoint/web/cluster/CollectorClusterInfoRepository.java index 2d60c4fe9..213fb3091 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/cluster/CollectorClusterInfoRepository.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/cluster/CollectorClusterInfoRepository.java @@ -28,75 +28,75 @@ import java.util.Map; */ public class CollectorClusterInfoRepository { - private static final Charset charser = Charset.forName("UTF-8"); + private static final Charset charser = Charset.forName("UTF-8"); - private static final String PROFILER_SEPERATOR = "\r\n"; + private static final String PROFILER_SEPERATOR = "\r\n"; - private final Map> repository = new HashMap>(); + private final Map> repository = new HashMap>(); - private final Object lock = new Object(); + private final Object lock = new Object(); - public void put(String id, byte[] data) { - synchronized (lock) { - Map newMap = new HashMap(); + public void put(String id, byte[] data) { + synchronized (lock) { + Map newMap = new HashMap(); - String[] profilerInfoList = new String(data, charser).split(PROFILER_SEPERATOR); + String[] profilerInfoList = new String(data, charser).split(PROFILER_SEPERATOR); - for (String profilerInfo : profilerInfoList) { - if (profilerInfo == null || profilerInfo.trim().equals("")) { - continue; - } + for (String profilerInfo : profilerInfoList) { + if (profilerInfo == null || profilerInfo.trim().equals("")) { + continue; + } - newMap.put(profilerInfo, id); - } + newMap.put(profilerInfo, id); + } - repository.put(id, newMap); - } - } + repository.put(id, newMap); + } + } - public void remove(String id) { - synchronized (lock) { - repository.remove(id); - } - } + public void remove(String id) { + synchronized (lock) { + repository.remove(id); + } + } - public List get(String applicationName, String agentId, long startTimeStamp) { - List result = new ArrayList(); + public List get(String applicationName, String agentId, long startTimeStamp) { + List result = new ArrayList(); - synchronized (lock) { - String key = bindingKey(applicationName, agentId, startTimeStamp); - for (Map eachCollectorClusterInfo : repository.values()) { - String collectorId = eachCollectorClusterInfo.get(key); - if (collectorId != null) { - result.add(collectorId); - } - } - } + synchronized (lock) { + String key = bindingKey(applicationName, agentId, startTimeStamp); + for (Map eachCollectorClusterInfo : repository.values()) { + String collectorId = eachCollectorClusterInfo.get(key); + if (collectorId != null) { + result.add(collectorId); + } + } + } - return result; - } + return result; + } - public void clear() { - synchronized (lock) { - repository.clear(); - } - } + public void clear() { + synchronized (lock) { + repository.clear(); + } + } - private String bindingKey(String applicationName, String agentId, long startTimeStamp) { - StringBuilder key = new StringBuilder(); + private String bindingKey(String applicationName, String agentId, long startTimeStamp) { + StringBuilder key = new StringBuilder(); - key.append(applicationName); - key.append(":"); - key.append(agentId); - key.append(":"); - key.append(startTimeStamp); + key.append(applicationName); + key.append(":"); + key.append(agentId); + key.append(":"); + key.append(startTimeStamp); - return key.toString(); - } + return key.toString(); + } - @Override - public String toString() { - return repository.toString(); - } + @Override + public String toString() { + return repository.toString(); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClient.java b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClient.java index 98eec50b3..26126eb8b 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClient.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClient.java @@ -44,172 +44,172 @@ import com.navercorp.pinpoint.web.cluster.zookeeper.exception.UnknownException; */ public class ZookeeperClient { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - // ZK client is thread-safe - private final ZookeeperClusterManager manager; + // ZK client is thread-safe + private final ZookeeperClusterManager manager; - private final ZooKeeper zookeeper; - private final AtomicBoolean clientState = new AtomicBoolean(true); + private final ZooKeeper zookeeper; + private final AtomicBoolean clientState = new AtomicBoolean(true); - // hmm this structure should contain all necessary information - public ZookeeperClient(String hostPort, int sessionTimeout, ZookeeperClusterManager manager) throws KeeperException, IOException, InterruptedException { - this.manager = manager; - zookeeper = new ZooKeeper(hostPort, sessionTimeout, this.manager); // server - } + // hmm this structure should contain all necessary information + public ZookeeperClient(String hostPort, int sessionTimeout, ZookeeperClusterManager manager) throws KeeperException, IOException, InterruptedException { + this.manager = manager; + zookeeper = new ZooKeeper(hostPort, sessionTimeout, this.manager); // server + } - /** - * do not create node in path suffix - * - * @throws PinpointZookeeperException - * @throws InterruptedException - */ - public void createPath(String path) throws PinpointZookeeperException, InterruptedException { - checkState(); + /** + * do not create node in path suffix + * + * @throws PinpointZookeeperException + * @throws InterruptedException + */ + public void createPath(String path) throws PinpointZookeeperException, InterruptedException { + checkState(); - int pos = 1; - do { - pos = path.indexOf('/', pos + 1); + int pos = 1; + do { + pos = path.indexOf('/', pos + 1); - if (pos == -1) { - pos = path.length(); - return; - } + if (pos == -1) { + pos = path.length(); + return; + } - try { - String subPath = path.substring(0, pos); - if (zookeeper.exists(subPath, false) != null) { - continue; - } + try { + String subPath = path.substring(0, pos); + if (zookeeper.exists(subPath, false) != null) { + continue; + } - zookeeper.create(subPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); - } catch (KeeperException exception) { - if (exception.code() != Code.NODEEXISTS) { - handleException(exception); - } - } + zookeeper.create(subPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + } catch (KeeperException exception) { + if (exception.code() != Code.NODEEXISTS) { + handleException(exception); + } + } - } while (pos < path.length()); - } + } while (pos < path.length()); + } - // we need deep node inspection for verification purpose (node content) - public String createNode(String znodePath, byte[] data, CreateMode createMode) throws PinpointZookeeperException, InterruptedException { - checkState(); + // we need deep node inspection for verification purpose (node content) + public String createNode(String znodePath, byte[] data, CreateMode createMode) throws PinpointZookeeperException, InterruptedException { + checkState(); - try { - if (zookeeper.exists(znodePath, false) != null) { - return znodePath; - } + try { + if (zookeeper.exists(znodePath, false) != null) { + return znodePath; + } - String pathName = zookeeper.create(znodePath, data, Ids.OPEN_ACL_UNSAFE, createMode); - return pathName; - } catch (KeeperException exception) { - if (exception.code() != Code.NODEEXISTS) { - handleException(exception); - } - } - return znodePath; - } + String pathName = zookeeper.create(znodePath, data, Ids.OPEN_ACL_UNSAFE, createMode); + return pathName; + } catch (KeeperException exception) { + if (exception.code() != Code.NODEEXISTS) { + handleException(exception); + } + } + return znodePath; + } - public List getChildren(String path, boolean watch) throws PinpointZookeeperException, InterruptedException { - checkState(); + public List getChildren(String path, boolean watch) throws PinpointZookeeperException, InterruptedException { + checkState(); - try { - return zookeeper.getChildren(path, watch); - } catch (KeeperException exception) { - if (exception.code() != Code.NONODE) { - handleException(exception); - } - } + try { + return zookeeper.getChildren(path, watch); + } catch (KeeperException exception) { + if (exception.code() != Code.NONODE) { + handleException(exception); + } + } - return Collections.emptyList(); - } + return Collections.emptyList(); + } - public byte[] getData(String path) throws PinpointZookeeperException, InterruptedException { - return getData(path, false); - } + public byte[] getData(String path) throws PinpointZookeeperException, InterruptedException { + return getData(path, false); + } - public byte[] getData(String path, boolean watch) throws PinpointZookeeperException, InterruptedException { - checkState(); + public byte[] getData(String path, boolean watch) throws PinpointZookeeperException, InterruptedException { + checkState(); - try { - return zookeeper.getData(path, watch, null); - } catch (KeeperException exception) { - handleException(exception); - } + try { + return zookeeper.getData(path, watch, null); + } catch (KeeperException exception) { + handleException(exception); + } - throw new UnknownException("UnknownException."); - } + throw new UnknownException("UnknownException."); + } - public void delete(String path) throws PinpointZookeeperException, InterruptedException { - checkState(); + public void delete(String path) throws PinpointZookeeperException, InterruptedException { + checkState(); - try { - zookeeper.delete(path, -1); - } catch (KeeperException exception) { - if (exception.code() != Code.NONODE) { - handleException(exception); - } - } - } + try { + zookeeper.delete(path, -1); + } catch (KeeperException exception) { + if (exception.code() != Code.NONODE) { + handleException(exception); + } + } + } - public boolean exists(String path) throws PinpointZookeeperException, InterruptedException { - checkState(); + public boolean exists(String path) throws PinpointZookeeperException, InterruptedException { + checkState(); - try { - Stat stat = zookeeper.exists(path, false); - if (stat == null) { - return false; - } - } catch (KeeperException exception) { - if (exception.code() != Code.NODEEXISTS) { - handleException(exception); - } - } - return true; - } + try { + Stat stat = zookeeper.exists(path, false); + if (stat == null) { + return false; + } + } catch (KeeperException exception) { + if (exception.code() != Code.NODEEXISTS) { + handleException(exception); + } + } + return true; + } - private void checkState() throws PinpointZookeeperException { - if (!this.manager.isConnected() || !clientState.get()) { - throw new ConnectionException("instance must be connected."); - } - } + private void checkState() throws PinpointZookeeperException { + if (!this.manager.isConnected() || !clientState.get()) { + throw new ConnectionException("instance must be connected."); + } + } - private void handleException(KeeperException keeperException) throws PinpointZookeeperException { - switch (keeperException.code()) { - case CONNECTIONLOSS: - case SESSIONEXPIRED: - throw new ConnectionException(keeperException.getMessage(), keeperException); - case AUTHFAILED: - case INVALIDACL: - case NOAUTH: - throw new AuthException(keeperException.getMessage(), keeperException); - case BADARGUMENTS: - case BADVERSION: - case NOCHILDRENFOREPHEMERALS: - case NOTEMPTY: - case NODEEXISTS: - throw new BadOperationException(keeperException.getMessage(), keeperException); - case NONODE: - throw new NoNodeException(keeperException.getMessage(), keeperException); - case OPERATIONTIMEOUT: - throw new TimeoutException(keeperException.getMessage(), keeperException); - default: - throw new UnknownException(keeperException.getMessage(), keeperException); - } - } + private void handleException(KeeperException keeperException) throws PinpointZookeeperException { + switch (keeperException.code()) { + case CONNECTIONLOSS: + case SESSIONEXPIRED: + throw new ConnectionException(keeperException.getMessage(), keeperException); + case AUTHFAILED: + case INVALIDACL: + case NOAUTH: + throw new AuthException(keeperException.getMessage(), keeperException); + case BADARGUMENTS: + case BADVERSION: + case NOCHILDRENFOREPHEMERALS: + case NOTEMPTY: + case NODEEXISTS: + throw new BadOperationException(keeperException.getMessage(), keeperException); + case NONODE: + throw new NoNodeException(keeperException.getMessage(), keeperException); + case OPERATIONTIMEOUT: + throw new TimeoutException(keeperException.getMessage(), keeperException); + default: + throw new UnknownException(keeperException.getMessage(), keeperException); + } + } - public void close() { - if (clientState.compareAndSet(true, false)) { - if (zookeeper != null) { - try { - zookeeper.close(); - } catch (InterruptedException ignore) { - logger.debug(ignore.getMessage(), ignore); - } - } - } - } + public void close() { + if (clientState.compareAndSet(true, false)) { + if (zookeeper != null) { + try { + zookeeper.close(); + } catch (InterruptedException ignore) { + logger.debug(ignore.getMessage(), ignore); + } + } + } + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClusterManager.java b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClusterManager.java index 5cbbcabf9..e6fbde170 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClusterManager.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClusterManager.java @@ -47,354 +47,354 @@ import com.navercorp.pinpoint.web.cluster.zookeeper.exception.NoNodeException; */ public class ZookeeperClusterManager implements ClusterManager, Watcher { - private static final String PINPOINT_CLUSTER_PATH = "/pinpoint-cluster"; - private static final String PINPOINT_WEB_CLUSTER_PATh = PINPOINT_CLUSTER_PATH + "/web"; - private static final String PINPOINT_COLLECTOR_CLUSTER_PATH = PINPOINT_CLUSTER_PATH + "/collector"; + private static final String PINPOINT_CLUSTER_PATH = "/pinpoint-cluster"; + private static final String PINPOINT_WEB_CLUSTER_PATh = PINPOINT_CLUSTER_PATH + "/web"; + private static final String PINPOINT_COLLECTOR_CLUSTER_PATH = PINPOINT_CLUSTER_PATH + "/collector"; - private static final long SYNC_INTERVAL_TIME_MILLIS = 15 * 1000; + private static final long SYNC_INTERVAL_TIME_MILLIS = 15 * 1000; - private static final String PATH_SEPERATOR = "/"; + private static final String PATH_SEPERATOR = "/"; - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final AtomicBoolean connected = new AtomicBoolean(false); - private final ZookeeperClient client; + private final AtomicBoolean connected = new AtomicBoolean(false); + private final ZookeeperClient client; - private final int retryInterval; + private final int retryInterval; - private final Timer timer; + private final Timer timer; - private final AtomicReference job = new AtomicReference(); + private final AtomicReference job = new AtomicReference(); - private final CollectorClusterInfoRepository collectorClusterInfo = new CollectorClusterInfoRepository(); + private final CollectorClusterInfoRepository collectorClusterInfo = new CollectorClusterInfoRepository(); - public ZookeeperClusterManager(String zookeeperAddress, int sessionTimeout, int retryInterval) throws KeeperException, IOException, InterruptedException { - this.client = new ZookeeperClient(zookeeperAddress, sessionTimeout, this); - this.retryInterval = retryInterval; - // it could be better to create upon failure - this.timer = createTimer(); - } + public ZookeeperClusterManager(String zookeeperAddress, int sessionTimeout, int retryInterval) throws KeeperException, IOException, InterruptedException { + this.client = new ZookeeperClient(zookeeperAddress, sessionTimeout, this); + this.retryInterval = retryInterval; + // it could be better to create upon failure + this.timer = createTimer(); + } - // Retry upon failure (1 min retry period) - // not too much overhead, just logging - @Override - public boolean registerWebCluster(String zNodeName, byte[] contents) { - String zNodePath = bindingPathAndZnode(PINPOINT_WEB_CLUSTER_PATh, zNodeName); + // Retry upon failure (1 min retry period) + // not too much overhead, just logging + @Override + public boolean registerWebCluster(String zNodeName, byte[] contents) { + String zNodePath = bindingPathAndZnode(PINPOINT_WEB_CLUSTER_PATh, zNodeName); - logger.info("Create Web Cluster Zookeeper UniqPath = {}", zNodePath); + logger.info("Create Web Cluster Zookeeper UniqPath = {}", zNodePath); - PushWebClusterJob job = new PushWebClusterJob(zNodePath, contents, retryInterval); - if (!this.job.compareAndSet(null, job)) { - logger.warn("Already Register Web Cluster Node."); - return false; - } + PushWebClusterJob job = new PushWebClusterJob(zNodePath, contents, retryInterval); + if (!this.job.compareAndSet(null, job)) { + logger.warn("Already Register Web Cluster Node."); + return false; + } - // successful even for schedular registration completion - if (!isConnected()) { - logger.info("Zookeeper is Disconnected."); - return true; - } + // successful even for schedular registration completion + if (!isConnected()) { + logger.info("Zookeeper is Disconnected."); + return true; + } - if (!syncWebCluster(job)) { - timer.newTimeout(job, job.getRetryInterval(), TimeUnit.MILLISECONDS); - } + if (!syncWebCluster(job)) { + timer.newTimeout(job, job.getRetryInterval(), TimeUnit.MILLISECONDS); + } - return true; - } + return true; + } - @Override - public void process(WatchedEvent event) { - logger.info("Zookeepr Event({}) ocurred.", event); + @Override + public void process(WatchedEvent event) { + logger.info("Zookeepr Event({}) ocurred.", event); - KeeperState state = event.getState(); - EventType eventType = event.getType(); - String path = event.getPath(); + KeeperState state = event.getState(); + EventType eventType = event.getType(); + String path = event.getPath(); - boolean result = false; + boolean result = false; - // when this happens, ephemeral node disappears - // reconnects automatically, and process gets notified for all events - if (state == KeeperState.Disconnected || state == KeeperState.Expired) { - result = handleDisconnected(); - } else if ((state == KeeperState.SyncConnected || state == KeeperState.NoSyncConnected) && eventType == EventType.None) { - result = handleConnected(); - } else if ((state == KeeperState.SyncConnected || state == KeeperState.NoSyncConnected) && eventType == EventType.NodeChildrenChanged) { - result = handleNodeChildrenChanged(path); - } else if ((state == KeeperState.SyncConnected || state == KeeperState.NoSyncConnected) && eventType == EventType.NodeDeleted) { - result = handleNodeDeleted(path); - } else if ((state == KeeperState.SyncConnected || state == KeeperState.NoSyncConnected) && eventType == EventType.NodeDataChanged) { - result = handleNodeDataChanged(path); - } + // when this happens, ephemeral node disappears + // reconnects automatically, and process gets notified for all events + if (state == KeeperState.Disconnected || state == KeeperState.Expired) { + result = handleDisconnected(); + } else if ((state == KeeperState.SyncConnected || state == KeeperState.NoSyncConnected) && eventType == EventType.None) { + result = handleConnected(); + } else if ((state == KeeperState.SyncConnected || state == KeeperState.NoSyncConnected) && eventType == EventType.NodeChildrenChanged) { + result = handleNodeChildrenChanged(path); + } else if ((state == KeeperState.SyncConnected || state == KeeperState.NoSyncConnected) && eventType == EventType.NodeDeleted) { + result = handleNodeDeleted(path); + } else if ((state == KeeperState.SyncConnected || state == KeeperState.NoSyncConnected) && eventType == EventType.NodeDataChanged) { + result = handleNodeDataChanged(path); + } - if (result) { - logger.info("Zookeeper Event({}) successed.", event); - } else { - logger.info("Zookeeper Event({}) failed.", event); - } - } + if (result) { + logger.info("Zookeeper Event({}) successed.", event); + } else { + logger.info("Zookeeper Event({}) failed.", event); + } + } - private boolean handleDisconnected() { - connected.compareAndSet(true, false); - collectorClusterInfo.clear(); - return true; - } + private boolean handleDisconnected() { + connected.compareAndSet(true, false); + collectorClusterInfo.clear(); + return true; + } - private boolean handleConnected() { - boolean result = true; + private boolean handleConnected() { + boolean result = true; - // is it ok to keep this since previous condition was possibly RUN - boolean changed = connected.compareAndSet(false, true); - if (changed) { - PushWebClusterJob job = this.job.get(); - if (job != null) { - if (!syncWebCluster(job)) { - timer.newTimeout(job, job.getRetryInterval(), TimeUnit.MILLISECONDS); - result = false; - } - } + // is it ok to keep this since previous condition was possibly RUN + boolean changed = connected.compareAndSet(false, true); + if (changed) { + PushWebClusterJob job = this.job.get(); + if (job != null) { + if (!syncWebCluster(job)) { + timer.newTimeout(job, job.getRetryInterval(), TimeUnit.MILLISECONDS); + result = false; + } + } - if (!syncCollectorCluster()) { - timer.newTimeout(new FetchCollectorClusterJob(), SYNC_INTERVAL_TIME_MILLIS, TimeUnit.MILLISECONDS); - result = false; - } - } else { - result = false; - } + if (!syncCollectorCluster()) { + timer.newTimeout(new FetchCollectorClusterJob(), SYNC_INTERVAL_TIME_MILLIS, TimeUnit.MILLISECONDS); + result = false; + } + } else { + result = false; + } - return result; - } + return result; + } - private boolean handleNodeChildrenChanged(String path) { - if (PINPOINT_COLLECTOR_CLUSTER_PATH.equals(path)) { - if (syncCollectorCluster()) { - return true; - } - timer.newTimeout(new FetchCollectorClusterJob(), SYNC_INTERVAL_TIME_MILLIS, TimeUnit.MILLISECONDS); - } + private boolean handleNodeChildrenChanged(String path) { + if (PINPOINT_COLLECTOR_CLUSTER_PATH.equals(path)) { + if (syncCollectorCluster()) { + return true; + } + timer.newTimeout(new FetchCollectorClusterJob(), SYNC_INTERVAL_TIME_MILLIS, TimeUnit.MILLISECONDS); + } - return false; - } + return false; + } - private boolean handleNodeDeleted(String path) { - if (path != null) { - String id = extractCollectorClusterId(path); - if (id != null) { - collectorClusterInfo.remove(id); - return true; - } - } - return false; - } + private boolean handleNodeDeleted(String path) { + if (path != null) { + String id = extractCollectorClusterId(path); + if (id != null) { + collectorClusterInfo.remove(id); + return true; + } + } + return false; + } - private boolean handleNodeDataChanged(String path) { - if (path != null) { - String id = extractCollectorClusterId(path); - if (id != null) { - if (syncCollectorCluster(id)) { - return true; - } - timer.newTimeout(new FetchCollectorClusterJob(), SYNC_INTERVAL_TIME_MILLIS, TimeUnit.MILLISECONDS); - } - } + private boolean handleNodeDataChanged(String path) { + if (path != null) { + String id = extractCollectorClusterId(path); + if (id != null) { + if (syncCollectorCluster(id)) { + return true; + } + timer.newTimeout(new FetchCollectorClusterJob(), SYNC_INTERVAL_TIME_MILLIS, TimeUnit.MILLISECONDS); + } + } - return false; - } + return false; + } - @Override - public void close() { - if (timer != null) { - timer.stop(); - } + @Override + public void close() { + if (timer != null) { + timer.stop(); + } - if (client != null) { - this.client.close(); - } - } + if (client != null) { + this.client.close(); + } + } - @Override - public List getRegisteredAgentList(String applicationName, String agentId, long startTimeStamp) { - return collectorClusterInfo.get(applicationName, agentId, startTimeStamp); - } + @Override + public List getRegisteredAgentList(String applicationName, String agentId, long startTimeStamp) { + return collectorClusterInfo.get(applicationName, agentId, startTimeStamp); + } - private Timer createTimer() { - HashedWheelTimer timer = TimerFactory.createHashedWheelTimer("Pinpoint-Web-Cluster-Timer", 100, TimeUnit.MILLISECONDS, 512); - timer.start(); - return timer; - } + private Timer createTimer() { + HashedWheelTimer timer = TimerFactory.createHashedWheelTimer("Pinpoint-Web-Cluster-Timer", 100, TimeUnit.MILLISECONDS, 512); + timer.start(); + return timer; + } - private boolean syncWebCluster(PushWebClusterJob job) { - String zNodePath = job.getZnodePath(); - byte[] contents = job.getContents(); + private boolean syncWebCluster(PushWebClusterJob job) { + String zNodePath = job.getZnodePath(); + byte[] contents = job.getContents(); - try { - if (!client.exists(zNodePath)) { - client.createPath(zNodePath); - } + try { + if (!client.exists(zNodePath)) { + client.createPath(zNodePath); + } - // ip:port zNode naming scheme - String nodeName = client.createNode(zNodePath, contents, CreateMode.EPHEMERAL); - logger.info("Register Web Cluster Zookeeper UniqPath = {}.", zNodePath); - return true; - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } - return false; - } + // ip:port zNode naming scheme + String nodeName = client.createNode(zNodePath, contents, CreateMode.EPHEMERAL); + logger.info("Register Web Cluster Zookeeper UniqPath = {}.", zNodePath); + return true; + } catch (Exception e) { + logger.warn(e.getMessage(), e); + } + return false; + } - public boolean isConnected() { - return connected.get(); - } + public boolean isConnected() { + return connected.get(); + } - private String bindingPathAndZnode(String path, String znodeName) { - StringBuilder fullPath = new StringBuilder(); + private String bindingPathAndZnode(String path, String znodeName) { + StringBuilder fullPath = new StringBuilder(); - fullPath.append(path); - if (!path.endsWith(PATH_SEPERATOR)) { - fullPath.append(PATH_SEPERATOR); - } - fullPath.append(znodeName); + fullPath.append(path); + if (!path.endsWith(PATH_SEPERATOR)) { + fullPath.append(PATH_SEPERATOR); + } + fullPath.append(znodeName); - return fullPath.toString(); - } + return fullPath.toString(); + } - private String extractCollectorClusterId(String path) { - int index = path.indexOf(PINPOINT_COLLECTOR_CLUSTER_PATH); + private String extractCollectorClusterId(String path) { + int index = path.indexOf(PINPOINT_COLLECTOR_CLUSTER_PATH); - int startPosition = index + PINPOINT_COLLECTOR_CLUSTER_PATH.length() + 1; + int startPosition = index + PINPOINT_COLLECTOR_CLUSTER_PATH.length() + 1; - if (path.length() > startPosition) { - String id = path.substring(startPosition); - return id; - } + if (path.length() > startPosition) { + String id = path.substring(startPosition); + return id; + } - return null; - } + return null; + } - private boolean syncCollectorCluster() { - synchronized (this) { - Map map = getCollectorData(); + private boolean syncCollectorCluster() { + synchronized (this) { + Map map = getCollectorData(); - if (map == null) { - return false; - } + if (map == null) { + return false; + } - for (Map.Entry entry : map.entrySet()) { - String key = entry.getKey(); - byte[] value = entry.getValue(); + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey(); + byte[] value = entry.getValue(); - String id = extractCollectorClusterId(key); - if (id == null) { - logger.error("Illegal Collector Path({}) finded.", key); - continue; - } - collectorClusterInfo.put(id, value); - } + String id = extractCollectorClusterId(key); + if (id == null) { + logger.error("Illegal Collector Path({}) finded.", key); + continue; + } + collectorClusterInfo.put(id, value); + } - return true; - } - } + return true; + } + } - private boolean syncCollectorCluster(String id) { - String path = bindingPathAndZnode(PINPOINT_COLLECTOR_CLUSTER_PATH, id); - synchronized (this) { - try { - byte[] data = client.getData(path, true); + private boolean syncCollectorCluster(String id) { + String path = bindingPathAndZnode(PINPOINT_COLLECTOR_CLUSTER_PATH, id); + synchronized (this) { + try { + byte[] data = client.getData(path, true); - collectorClusterInfo.put(id, data); - return true; - } catch(NoNodeException e) { + collectorClusterInfo.put(id, data); + return true; + } catch(NoNodeException e) { logger.warn("No node path({}).", path); - collectorClusterInfo.remove(id); - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } + collectorClusterInfo.remove(id); + } catch (Exception e) { + logger.warn(e.getMessage(), e); + } - return false; - } - } + return false; + } + } - private Map getCollectorData() { - try { - List collectorList = client.getChildren(PINPOINT_COLLECTOR_CLUSTER_PATH, true); + private Map getCollectorData() { + try { + List collectorList = client.getChildren(PINPOINT_COLLECTOR_CLUSTER_PATH, true); - Map map = new HashMap(); + Map map = new HashMap(); - for (String collector : collectorList) { - String node = bindingPathAndZnode(PINPOINT_COLLECTOR_CLUSTER_PATH, collector); + for (String collector : collectorList) { + String node = bindingPathAndZnode(PINPOINT_COLLECTOR_CLUSTER_PATH, collector); - byte[] data = client.getData(node, true); - map.put(node, data); - } + byte[] data = client.getData(node, true); + map.put(node, data); + } - return map; - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } + return map; + } catch (Exception e) { + logger.warn(e.getMessage(), e); + } - return null; - } + return null; + } - class PushWebClusterJob implements TimerTask { - private final String znodeName; - private final byte[] contents; - private final int retryInterval; + class PushWebClusterJob implements TimerTask { + private final String znodeName; + private final byte[] contents; + private final int retryInterval; - public PushWebClusterJob(String znodeName, byte[] contents, int retryInterval) { - this.znodeName = znodeName; - this.contents = contents; - this.retryInterval = retryInterval; - } + public PushWebClusterJob(String znodeName, byte[] contents, int retryInterval) { + this.znodeName = znodeName; + this.contents = contents; + this.retryInterval = retryInterval; + } - public String getZnodePath() { - return znodeName; - } + public String getZnodePath() { + return znodeName; + } - public byte[] getContents() { - return contents; - } + public byte[] getContents() { + return contents; + } - public int getRetryInterval() { - return retryInterval; - } + public int getRetryInterval() { + return retryInterval; + } - @Override - public String toString() { - StringBuilder toString = new StringBuilder(); - toString.append(this.getClass().getSimpleName()); - toString.append(", Znode=").append(getZnodePath()); + @Override + public String toString() { + StringBuilder toString = new StringBuilder(); + toString.append(this.getClass().getSimpleName()); + toString.append(", Znode=").append(getZnodePath()); - return toString.toString(); - } + return toString.toString(); + } - @Override - public void run(Timeout timeout) throws Exception { - logger.info("Reservation Job({}) started.", this.getClass().getSimpleName()); + @Override + public void run(Timeout timeout) throws Exception { + logger.info("Reservation Job({}) started.", this.getClass().getSimpleName()); - if (!isConnected()) { - return; - } + if (!isConnected()) { + return; + } - if (!syncWebCluster(this)) { - timer.newTimeout(this, getRetryInterval(), TimeUnit.MILLISECONDS); - } - } - } + if (!syncWebCluster(this)) { + timer.newTimeout(this, getRetryInterval(), TimeUnit.MILLISECONDS); + } + } + } - class FetchCollectorClusterJob implements TimerTask { + class FetchCollectorClusterJob implements TimerTask { - @Override - public void run(Timeout timeout) throws Exception { - logger.info("Reservation Job({}) started.", this.getClass().getSimpleName()); + @Override + public void run(Timeout timeout) throws Exception { + logger.info("Reservation Job({}) started.", this.getClass().getSimpleName()); - if (!isConnected()) { - return; - } + if (!isConnected()) { + return; + } - if (!syncCollectorCluster()) { - timer.newTimeout(new FetchCollectorClusterJob(), SYNC_INTERVAL_TIME_MILLIS, TimeUnit.MILLISECONDS); - } - } - } + if (!syncCollectorCluster()) { + timer.newTimeout(new FetchCollectorClusterJob(), SYNC_INTERVAL_TIME_MILLIS, TimeUnit.MILLISECONDS); + } + } + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/AuthException.java b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/AuthException.java index 70c14adb9..e76c5af81 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/AuthException.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/AuthException.java @@ -21,19 +21,19 @@ package com.navercorp.pinpoint.web.cluster.zookeeper.exception; */ public class AuthException extends PinpointZookeeperException { - public AuthException() { - } + public AuthException() { + } - public AuthException(String message) { - super(message); - } + public AuthException(String message) { + super(message); + } - public AuthException(String message, Throwable cause) { - super(message, cause); - } + public AuthException(String message, Throwable cause) { + super(message, cause); + } - public AuthException(Throwable cause) { - super(cause); - } + public AuthException(Throwable cause) { + super(cause); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/BadOperationException.java b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/BadOperationException.java index 5821f1d22..cda08a0cf 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/BadOperationException.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/BadOperationException.java @@ -21,19 +21,19 @@ package com.navercorp.pinpoint.web.cluster.zookeeper.exception; */ public class BadOperationException extends PinpointZookeeperException { - public BadOperationException() { - } + public BadOperationException() { + } - public BadOperationException(String message) { - super(message); - } + public BadOperationException(String message) { + super(message); + } - public BadOperationException(String message, Throwable cause) { - super(message, cause); - } + public BadOperationException(String message, Throwable cause) { + super(message, cause); + } - public BadOperationException(Throwable cause) { - super(cause); - } + public BadOperationException(Throwable cause) { + super(cause); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/ConnectionException.java b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/ConnectionException.java index 6dec9eafb..cbae894b4 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/ConnectionException.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/ConnectionException.java @@ -21,19 +21,19 @@ package com.navercorp.pinpoint.web.cluster.zookeeper.exception; */ public class ConnectionException extends PinpointZookeeperException { - public ConnectionException() { - } + public ConnectionException() { + } - public ConnectionException(String message) { - super(message); - } + public ConnectionException(String message) { + super(message); + } - public ConnectionException(String message, Throwable cause) { - super(message, cause); - } + public ConnectionException(String message, Throwable cause) { + super(message, cause); + } - public ConnectionException(Throwable cause) { - super(cause); - } + public ConnectionException(Throwable cause) { + super(cause); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/PinpointZookeeperException.java b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/PinpointZookeeperException.java index 6e0717fe8..674736a64 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/PinpointZookeeperException.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/PinpointZookeeperException.java @@ -21,19 +21,19 @@ package com.navercorp.pinpoint.web.cluster.zookeeper.exception; */ public class PinpointZookeeperException extends Exception { - public PinpointZookeeperException() { - } + public PinpointZookeeperException() { + } - public PinpointZookeeperException(String message) { - super(message); - } + public PinpointZookeeperException(String message) { + super(message); + } - public PinpointZookeeperException(String message, Throwable cause) { - super(message, cause); - } + public PinpointZookeeperException(String message, Throwable cause) { + super(message, cause); + } - public PinpointZookeeperException(Throwable cause) { - super(cause); - } + public PinpointZookeeperException(Throwable cause) { + super(cause); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/TimeoutException.java b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/TimeoutException.java index c5aea558b..c4b6fef9a 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/TimeoutException.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/TimeoutException.java @@ -21,19 +21,19 @@ package com.navercorp.pinpoint.web.cluster.zookeeper.exception; */ public class TimeoutException extends PinpointZookeeperException { - public TimeoutException() { - } + public TimeoutException() { + } - public TimeoutException(String message) { - super(message); - } + public TimeoutException(String message) { + super(message); + } - public TimeoutException(String message, Throwable cause) { - super(message, cause); - } + public TimeoutException(String message, Throwable cause) { + super(message, cause); + } - public TimeoutException(Throwable cause) { - super(cause); - } + public TimeoutException(Throwable cause) { + super(cause); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/UnknownException.java b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/UnknownException.java index 69ffc650e..ca69f63b2 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/UnknownException.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/cluster/zookeeper/exception/UnknownException.java @@ -21,19 +21,19 @@ package com.navercorp.pinpoint.web.cluster.zookeeper.exception; */ public class UnknownException extends PinpointZookeeperException { - public UnknownException() { - } + public UnknownException() { + } - public UnknownException(String message) { - super(message); - } + public UnknownException(String message) { + super(message); + } - public UnknownException(String message, Throwable cause) { - super(message, cause); - } + public UnknownException(String message, Throwable cause) { + super(message, cause); + } - public UnknownException(Throwable cause) { - super(cause); - } + public UnknownException(Throwable cause) { + super(cause); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/config/WebConfig.java b/web/src/main/java/com/navercorp/pinpoint/web/config/WebConfig.java index 71222343c..ddb9cca0e 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/config/WebConfig.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/config/WebConfig.java @@ -28,84 +28,84 @@ import org.springframework.beans.factory.annotation.Value; */ public class WebConfig { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Value("#{pinpointWebProps['cluster.enable'] ?: false}") - private boolean clusterEnable; + @Value("#{pinpointWebProps['cluster.enable'] ?: false}") + private boolean clusterEnable; - @Value("#{pinpointWebProps['cluster.web.tcp.port'] ?: 0}") - private int clusterTcpPort; + @Value("#{pinpointWebProps['cluster.web.tcp.port'] ?: 0}") + private int clusterTcpPort; - @Value("#{pinpointWebProps['cluster.zookeeper.address'] ?: ''}") - private String clusterZookeeperAddress; + @Value("#{pinpointWebProps['cluster.zookeeper.address'] ?: ''}") + private String clusterZookeeperAddress; - @Value("#{pinpointWebProps['cluster.zookeeper.sessiontimeout'] ?: -1}") - private int clusterZookeeperSessionTimeout; + @Value("#{pinpointWebProps['cluster.zookeeper.sessiontimeout'] ?: -1}") + private int clusterZookeeperSessionTimeout; - @Value("#{pinpointWebProps['cluster.zookeeper.retry.interval'] ?: 60000}") - private int clusterZookeeperRetryInterval; + @Value("#{pinpointWebProps['cluster.zookeeper.retry.interval'] ?: 60000}") + private int clusterZookeeperRetryInterval; - @PostConstruct - public void validation() { - if (isClusterEnable()) { - assertPort(clusterTcpPort); - if(StringUtils.isEmpty(clusterZookeeperAddress)) { - throw new IllegalArgumentException("clusterZookeeperAddress may not be empty =" + clusterZookeeperAddress); - } - assertPositiveNumber(clusterZookeeperSessionTimeout); - assertPositiveNumber(clusterZookeeperRetryInterval); - } + @PostConstruct + public void validation() { + if (isClusterEnable()) { + assertPort(clusterTcpPort); + if(StringUtils.isEmpty(clusterZookeeperAddress)) { + throw new IllegalArgumentException("clusterZookeeperAddress may not be empty =" + clusterZookeeperAddress); + } + assertPositiveNumber(clusterZookeeperSessionTimeout); + assertPositiveNumber(clusterZookeeperRetryInterval); + } - logger.info("{}", toString()); - } + logger.info("{}", toString()); + } - private boolean assertPort(int port) { - if (port > 0 && 65535 > port) { - return true; - } + private boolean assertPort(int port) { + if (port > 0 && 65535 > port) { + return true; + } - throw new IllegalArgumentException("Invalid Port =" + port); - } + throw new IllegalArgumentException("Invalid Port =" + port); + } - private boolean assertPositiveNumber(int number) { - if (number >= 0) { - return true; - } + private boolean assertPositiveNumber(int number) { + if (number >= 0) { + return true; + } - throw new IllegalArgumentException("Invalid Positive Number =" + number); - } + throw new IllegalArgumentException("Invalid Positive Number =" + number); + } - public boolean isClusterEnable() { - return clusterEnable; - } + public boolean isClusterEnable() { + return clusterEnable; + } - public int getClusterTcpPort() { - return clusterTcpPort; - } + public int getClusterTcpPort() { + return clusterTcpPort; + } - public String getClusterZookeeperAddress() { - return clusterZookeeperAddress; - } + public String getClusterZookeeperAddress() { + return clusterZookeeperAddress; + } - public int getClusterZookeeperSessionTimeout() { - return clusterZookeeperSessionTimeout; - } + public int getClusterZookeeperSessionTimeout() { + return clusterZookeeperSessionTimeout; + } - @Override - public String toString() { - return "WebConfig [clusterEnable=" + clusterEnable - + ", clusterTcpPort=" + clusterTcpPort - + ", clusterZookeeperAddress=" + clusterZookeeperAddress - + ", clusterZookeeperSessionTimeout=" - + clusterZookeeperSessionTimeout + "]"; - } + @Override + public String toString() { + return "WebConfig [clusterEnable=" + clusterEnable + + ", clusterTcpPort=" + clusterTcpPort + + ", clusterZookeeperAddress=" + clusterZookeeperAddress + + ", clusterZookeeperSessionTimeout=" + + clusterZookeeperSessionTimeout + "]"; + } - public int getClusterZookeeperRetryInterval() { - return clusterZookeeperRetryInterval; - } + public int getClusterZookeeperRetryInterval() { + return clusterZookeeperRetryInterval; + } - public void setClusterZookeeperRetryInterval(int clusterZookeeperRetryInterval) { - this.clusterZookeeperRetryInterval = clusterZookeeperRetryInterval; - } + public void setClusterZookeeperRetryInterval(int clusterZookeeperRetryInterval) { + this.clusterZookeeperRetryInterval = clusterZookeeperRetryInterval; + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/controller/AdminController.java b/web/src/main/java/com/navercorp/pinpoint/web/controller/AdminController.java index 4821f5f84..90570d0b6 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/controller/AdminController.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/controller/AdminController.java @@ -34,36 +34,36 @@ import com.navercorp.pinpoint.web.service.AdminService; @RequestMapping("/admin") public class AdminController { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private AdminService adminService; + @Autowired + private AdminService adminService; - @RequestMapping(value = "/removeApplicationName", method = RequestMethod.GET) - @ResponseBody - public String removeApplicationName(@RequestParam("applicationName") String applicationName) { - logger.info("remove application name. {}", applicationName); - try { - adminService.removeApplicationName(applicationName); - return "OK"; - } catch (Exception e) { - logger.error("error while removing applicationName", e); - return e.getMessage(); - } - } - - @RequestMapping(value = "/removeAgentId", method = RequestMethod.GET) - @ResponseBody - public String removeAgentId( - @RequestParam(value = "applicationName", required = true) String applicationName, - @RequestParam(value = "agentId", required = true) String agentId) { - logger.info("remove agent id - ApplicationName: [{}], Agent ID: [{}]", applicationName, agentId); - try { - adminService.removeAgentId(applicationName, agentId); - return "OK"; - } catch (Exception e) { - logger.error("error while removing agentId", e); - return e.getMessage(); - } - } + @RequestMapping(value = "/removeApplicationName", method = RequestMethod.GET) + @ResponseBody + public String removeApplicationName(@RequestParam("applicationName") String applicationName) { + logger.info("remove application name. {}", applicationName); + try { + adminService.removeApplicationName(applicationName); + return "OK"; + } catch (Exception e) { + logger.error("error while removing applicationName", e); + return e.getMessage(); + } + } + + @RequestMapping(value = "/removeAgentId", method = RequestMethod.GET) + @ResponseBody + public String removeAgentId( + @RequestParam(value = "applicationName", required = true) String applicationName, + @RequestParam(value = "agentId", required = true) String agentId) { + logger.info("remove agent id - ApplicationName: [{}], Agent ID: [{}]", applicationName, agentId); + try { + adminService.removeAgentId(applicationName, agentId); + return "OK"; + } catch (Exception e) { + logger.error("error while removing agentId", e); + return e.getMessage(); + } + } } \ No newline at end of file diff --git a/web/src/main/java/com/navercorp/pinpoint/web/controller/BusinessTransactionController.java b/web/src/main/java/com/navercorp/pinpoint/web/controller/BusinessTransactionController.java index 5bbe231bc..015af8204 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/controller/BusinessTransactionController.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/controller/BusinessTransactionController.java @@ -55,77 +55,77 @@ import org.springframework.web.servlet.ModelAndView; @Controller public class BusinessTransactionController { - private Logger logger = LoggerFactory.getLogger(this.getClass()); + private Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private SpanService spanService; + @Autowired + private SpanService spanService; - @Autowired - private TransactionInfoService transactionInfoService; + @Autowired + private TransactionInfoService transactionInfoService; - @Autowired - private FilteredMapService filteredMapService; + @Autowired + private FilteredMapService filteredMapService; @Autowired private FilterBuilder filterBuilder; /** - * executed URLs in applicationname query within from ~ to timeframe - * - * @param model - * @param applicationName - * @param from - * @param to - * @return - */ + * executed URLs in applicationname query within from ~ to timeframe + * + * @param model + * @param applicationName + * @param from + * @param to + * @return + */ @Deprecated - @RequestMapping(value = "/transactionList", method = RequestMethod.GET) + @RequestMapping(value = "/transactionList", method = RequestMethod.GET) @ResponseBody - public Model getBusinessTransactionsData(Model model, - @RequestParam("application") String applicationName, - @RequestParam("from") long from, - @RequestParam("to") long to, - @RequestParam(value = "filter", required = false) String filterText, - @RequestParam(value = "limit", required = false, defaultValue = "10000") int limit) { + public Model getBusinessTransactionsData(Model model, + @RequestParam("application") String applicationName, + @RequestParam("from") long from, + @RequestParam("to") long to, + @RequestParam(value = "filter", required = false) String filterText, + @RequestParam(value = "limit", required = false, defaultValue = "10000") int limit) { limit = LimitUtils.checkRange(limit); - Range range = new Range(from, to); - // TODO more refactoring needed: partially separated out server map lookup logic. - LimitedScanResult> traceIdList = filteredMapService.selectTraceIdsFromApplicationTraceIndex(applicationName, range, limit); + Range range = new Range(from, to); + // TODO more refactoring needed: partially separated out server map lookup logic. + LimitedScanResult> traceIdList = filteredMapService.selectTraceIdsFromApplicationTraceIndex(applicationName, range, limit); - Filter filter = filterBuilder.build(filterText); - BusinessTransactions selectBusinessTransactions = transactionInfoService.selectBusinessTransactions(traceIdList.getScanData(), applicationName, range, filter); + Filter filter = filterBuilder.build(filterText); + BusinessTransactions selectBusinessTransactions = transactionInfoService.selectBusinessTransactions(traceIdList.getScanData(), applicationName, range, filter); - model.addAttribute("lastFetchedTimestamp", traceIdList.getLimitedTime()); - model.addAttribute("rpcList", selectBusinessTransactions.getBusinessTransaction()); - model.addAttribute("requestList", selectBusinessTransactions.getBusinessTransaction()); - model.addAttribute("scatterList", selectBusinessTransactions.getBusinessTransaction()); - model.addAttribute("applicationName", applicationName); - model.addAttribute("from", new Date(from)); - model.addAttribute("to", new Date(to)); - model.addAttribute("urlCount", selectBusinessTransactions.getURLCount()); - model.addAttribute("totalCount", selectBusinessTransactions.getTotalCallCount()); - model.addAttribute("filterText", filterText); - model.addAttribute("filter", filter); + model.addAttribute("lastFetchedTimestamp", traceIdList.getLimitedTime()); + model.addAttribute("rpcList", selectBusinessTransactions.getBusinessTransaction()); + model.addAttribute("requestList", selectBusinessTransactions.getBusinessTransaction()); + model.addAttribute("scatterList", selectBusinessTransactions.getBusinessTransaction()); + model.addAttribute("applicationName", applicationName); + model.addAttribute("from", new Date(from)); + model.addAttribute("to", new Date(to)); + model.addAttribute("urlCount", selectBusinessTransactions.getURLCount()); + model.addAttribute("totalCount", selectBusinessTransactions.getTotalCallCount()); + model.addAttribute("filterText", filterText); + model.addAttribute("filter", filter); // Deprecated jsp -> need json dump - return model; - } + return model; + } @Deprecated - @RequestMapping(value = "/lastTransactionList", method = RequestMethod.GET) + @RequestMapping(value = "/lastTransactionList", method = RequestMethod.GET) @ResponseBody - public Model getLastBusinessTransactionsData(Model model, HttpServletResponse response, - @RequestParam("application") String applicationName, - @RequestParam("period") long period, - @RequestParam(value = "filter", required = false) String filterText, - @RequestParam(value = "limit", required = false, defaultValue = "10000") int limit) { + public Model getLastBusinessTransactionsData(Model model, HttpServletResponse response, + @RequestParam("application") String applicationName, + @RequestParam("period") long period, + @RequestParam(value = "filter", required = false) String filterText, + @RequestParam(value = "limit", required = false, defaultValue = "10000") int limit) { limit = LimitUtils.checkRange(limit); long to = TimeUtils.getDelayLastTime(); - long from = to - period; - return getBusinessTransactionsData(model, applicationName, from, to, filterText, limit); - } + long from = to - period; + return getBusinessTransactionsData(model, applicationName, from, to, filterText, limit); + } /** - * info lookup for a selected transaction + * info lookup for a selected transaction * * @param traceIdParam * @param focusTimestamp diff --git a/web/src/main/java/com/navercorp/pinpoint/web/controller/CommandController.java b/web/src/main/java/com/navercorp/pinpoint/web/controller/CommandController.java index 7cd11fa41..a4d516d66 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/controller/CommandController.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/controller/CommandController.java @@ -54,219 +54,219 @@ import com.navercorp.pinpoint.web.server.PinpointSocketManager; @RequestMapping("/command") public class CommandController { - // FIX ME: created for a simple ping/pong test for now - // need a formal set of APIs and proper code + // FIX ME: created for a simple ping/pong test for now + // need a formal set of APIs and proper code - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private SerializerFactory commandSerializerFactory; + @Autowired + private SerializerFactory commandSerializerFactory; - @Autowired - private DeserializerFactory commandDeserializerFactory; + @Autowired + private DeserializerFactory commandDeserializerFactory; - @Autowired - private PinpointSocketManager socketManager; + @Autowired + private PinpointSocketManager socketManager; - @RequestMapping(value = "/echo", method = RequestMethod.GET) - public ModelAndView echo(@RequestParam("application") String applicationName, @RequestParam("agent") String agentId, - @RequestParam("startTimeStamp") long startTimeStamp, @RequestParam("message") String message) throws TException { + @RequestMapping(value = "/echo", method = RequestMethod.GET) + public ModelAndView echo(@RequestParam("application") String applicationName, @RequestParam("agent") String agentId, + @RequestParam("startTimeStamp") long startTimeStamp, @RequestParam("message") String message) throws TException { - ChannelContext context = socketManager.getCollectorChannelContext(applicationName, agentId, startTimeStamp); + ChannelContext context = socketManager.getCollectorChannelContext(applicationName, agentId, startTimeStamp); - if (context == null) { - return createResponse(false, String.format("Can't find suitable ChannelContext(%s/%s/%d).", applicationName, agentId, startTimeStamp)); - } + if (context == null) { + return createResponse(false, String.format("Can't find suitable ChannelContext(%s/%s/%d).", applicationName, agentId, startTimeStamp)); + } - TCommandEcho echo = new TCommandEcho(); - echo.setMessage(message); + TCommandEcho echo = new TCommandEcho(); + echo.setMessage(message); - byte[] payload = serialize(echo); + byte[] payload = serialize(echo); - TCommandTransfer transfer = new TCommandTransfer(); - transfer.setApplicationName(applicationName); - transfer.setAgentId(agentId); - transfer.setStartTime(startTimeStamp); - transfer.setPayload(payload); + TCommandTransfer transfer = new TCommandTransfer(); + transfer.setApplicationName(applicationName); + transfer.setAgentId(agentId); + transfer.setStartTime(startTimeStamp); + transfer.setPayload(payload); - Future future = context.getSocketChannel().sendRequestMessage(serialize(transfer)); - future.await(); + Future future = context.getSocketChannel().sendRequestMessage(serialize(transfer)); + future.await(); - String exceptionMessage = StringUtils.EMPTY; + String exceptionMessage = StringUtils.EMPTY; - ResponseMessage responseMessage = future.getResult(); - try { - TBase result = deserialize(responseMessage.getMessage()); + ResponseMessage responseMessage = future.getResult(); + try { + TBase result = deserialize(responseMessage.getMessage()); - if (result == null) { - return createResponse(false, String.format("Can't get message from %s.", context)); - } else if (result instanceof TCommandEcho) { - return createResponse(true, ((TCommandEcho) result).getMessage()); - } else if (result instanceof TResult) { - return createResponse(false, ((TResult) result).getMessage()); - } else { - return createResponse(false, result.toString()); - } + if (result == null) { + return createResponse(false, String.format("Can't get message from %s.", context)); + } else if (result instanceof TCommandEcho) { + return createResponse(true, ((TCommandEcho) result).getMessage()); + } else if (result instanceof TResult) { + return createResponse(false, ((TResult) result).getMessage()); + } else { + return createResponse(false, result.toString()); + } - } catch (TException e) { - exceptionMessage = e.getMessage(); - } + } catch (TException e) { + exceptionMessage = e.getMessage(); + } - return createResponse(false, exceptionMessage); - } + return createResponse(false, exceptionMessage); + } - @RequestMapping(value = "/threadDump", method = RequestMethod.GET) - public ModelAndView echo(@RequestParam("application") String applicationName, @RequestParam("agent") String agentId, - @RequestParam("startTimeStamp") long startTimeStamp) throws TException { + @RequestMapping(value = "/threadDump", method = RequestMethod.GET) + public ModelAndView echo(@RequestParam("application") String applicationName, @RequestParam("agent") String agentId, + @RequestParam("startTimeStamp") long startTimeStamp) throws TException { - ChannelContext context = socketManager.getCollectorChannelContext(applicationName, agentId, startTimeStamp); + ChannelContext context = socketManager.getCollectorChannelContext(applicationName, agentId, startTimeStamp); - if (context == null) { - return createResponse(false, String.format("Can't find suitable ChannelContext(%s/%s/%d).", applicationName, agentId, startTimeStamp)); - } + if (context == null) { + return createResponse(false, String.format("Can't find suitable ChannelContext(%s/%s/%d).", applicationName, agentId, startTimeStamp)); + } - TCommandThreadDump threadDump = new TCommandThreadDump(); + TCommandThreadDump threadDump = new TCommandThreadDump(); - byte[] payload = serialize(threadDump); + byte[] payload = serialize(threadDump); - TCommandTransfer transfer = new TCommandTransfer(); - transfer.setApplicationName(applicationName); - transfer.setAgentId(agentId); - transfer.setStartTime(startTimeStamp); - transfer.setPayload(payload); + TCommandTransfer transfer = new TCommandTransfer(); + transfer.setApplicationName(applicationName); + transfer.setAgentId(agentId); + transfer.setStartTime(startTimeStamp); + transfer.setPayload(payload); - Future future = context.getSocketChannel().sendRequestMessage(serialize(transfer)); - future.await(); + Future future = context.getSocketChannel().sendRequestMessage(serialize(transfer)); + future.await(); - String exceptionMessage = StringUtils.EMPTY; + String exceptionMessage = StringUtils.EMPTY; - ResponseMessage responseMessage = future.getResult(); - try { - TBase result = deserialize(responseMessage.getMessage()); + ResponseMessage responseMessage = future.getResult(); + try { + TBase result = deserialize(responseMessage.getMessage()); - if (result == null) { - return createResponse(false, String.format("Can't get message from %s.", context)); - } else if (result instanceof TCommandThreadDumpResponse) { - Map map = createThreadDump((TCommandThreadDumpResponse) result); + if (result == null) { + return createResponse(false, String.format("Can't get message from %s.", context)); + } else if (result instanceof TCommandThreadDumpResponse) { + Map map = createThreadDump((TCommandThreadDumpResponse) result); - logger.debug("{}", map.toString()); + logger.debug("{}", map.toString()); - return createResponse(true, map); - } else if (result instanceof TResult) { - return createResponse(false, ((TResult) result).getMessage()); - } else { - return createResponse(false, result.toString()); - } + return createResponse(true, map); + } else if (result instanceof TResult) { + return createResponse(false, ((TResult) result).getMessage()); + } else { + return createResponse(false, result.toString()); + } - } catch (TException e) { - exceptionMessage = e.getMessage(); - } + } catch (TException e) { + exceptionMessage = e.getMessage(); + } - return createResponse(false, exceptionMessage); - } + return createResponse(false, exceptionMessage); + } - private ModelAndView createResponse(boolean success, Object message) { - ModelAndView mv = new ModelAndView(); - mv.setViewName("jsonView"); + private ModelAndView createResponse(boolean success, Object message) { + ModelAndView mv = new ModelAndView(); + mv.setViewName("jsonView"); - if (success) { - mv.addObject("code", 0); - } else { - mv.addObject("code", -1); - } + if (success) { + mv.addObject("code", 0); + } else { + mv.addObject("code", -1); + } - mv.addObject("message", message); + mv.addObject("message", message); - return mv; - } + return mv; + } - private Map createThreadDump(TCommandThreadDumpResponse threadDumps) { + private Map createThreadDump(TCommandThreadDumpResponse threadDumps) { - Map map = new HashMap(); + Map map = new HashMap(); - for (TThreadDump threadDump : threadDumps.getThreadDumps()) { - String dump = threadDumptoString(threadDump); + for (TThreadDump threadDump : threadDumps.getThreadDumps()) { + String dump = threadDumptoString(threadDump); - map.put(threadDump.getThreadName(), dump); - } + map.put(threadDump.getThreadName(), dump); + } - return map; - } + return map; + } - public String threadDumptoString(TThreadDump threadDump) { - StringBuilder sb = new StringBuilder("\"" + threadDump.getThreadName() + "\"" + " Id=" + threadDump.getThreadId() + " " - + threadDump.getThreadState().name()); - if (!StringUtils.isBlank(threadDump.getLockName())) { - sb.append(" on ").append(threadDump.getLockName()); - } + public String threadDumptoString(TThreadDump threadDump) { + StringBuilder sb = new StringBuilder("\"" + threadDump.getThreadName() + "\"" + " Id=" + threadDump.getThreadId() + " " + + threadDump.getThreadState().name()); + if (!StringUtils.isBlank(threadDump.getLockName())) { + sb.append(" on ").append(threadDump.getLockName()); + } - if (!StringUtils.isBlank(threadDump.getLockOwnerName())) { - sb.append(" owned by \"").append(threadDump.getLockOwnerName()).append("\" Id=").append(threadDump.getLockOwnerId()); - } + if (!StringUtils.isBlank(threadDump.getLockOwnerName())) { + sb.append(" owned by \"").append(threadDump.getLockOwnerName()).append("\" Id=").append(threadDump.getLockOwnerId()); + } - if (threadDump.isSuspended()) { - sb.append(" (suspended)"); - } - if (threadDump.isInNative()) { - sb.append(" (in native)"); - } - sb.append('\n'); + if (threadDump.isSuspended()) { + sb.append(" (suspended)"); + } + if (threadDump.isInNative()) { + sb.append(" (in native)"); + } + sb.append('\n'); - for (int i = 0; i < threadDump.getStackTraceSize(); i++) { - String ste = threadDump.getStackTrace().get(i); - sb.append("\tat ").append(ste); - sb.append('\n'); + for (int i = 0; i < threadDump.getStackTraceSize(); i++) { + String ste = threadDump.getStackTrace().get(i); + sb.append("\tat ").append(ste); + sb.append('\n'); - if (i == 0 && !StringUtils.isBlank(threadDump.getLockName())) { - TThreadState ts = threadDump.getThreadState(); - switch (ts) { - case BLOCKED: - sb.append("\t- blocked on ").append(threadDump.getLockName()); - sb.append('\n'); - break; - case WAITING: - sb.append("\t- waiting on ").append(threadDump.getLockName()); - sb.append('\n'); - break; - case TIMED_WAITING: - sb.append("\t- waiting on ").append(threadDump.getLockName()); - sb.append('\n'); - break; - default: - } - } + if (i == 0 && !StringUtils.isBlank(threadDump.getLockName())) { + TThreadState ts = threadDump.getThreadState(); + switch (ts) { + case BLOCKED: + sb.append("\t- blocked on ").append(threadDump.getLockName()); + sb.append('\n'); + break; + case WAITING: + sb.append("\t- waiting on ").append(threadDump.getLockName()); + sb.append('\n'); + break; + case TIMED_WAITING: + sb.append("\t- waiting on ").append(threadDump.getLockName()); + sb.append('\n'); + break; + default: + } + } - if (threadDump.getLockedMonitors() != null) { - for (TMonitorInfo mi : threadDump.getLockedMonitors()) { - if (mi.getStackDepth() == i) { - sb.append("\t- locked ").append(mi.getStackFrame()); - sb.append('\n'); - } - } - } - } + if (threadDump.getLockedMonitors() != null) { + for (TMonitorInfo mi : threadDump.getLockedMonitors()) { + if (mi.getStackDepth() == i) { + sb.append("\t- locked ").append(mi.getStackFrame()); + sb.append('\n'); + } + } + } + } - List locks = threadDump.getLockedSynchronizers(); - if (locks != null) { - if (locks.size() > 0) { - sb.append("\n\tNumber of locked synchronizers = ").append(locks.size()); - sb.append('\n'); - for (String li : locks) { - sb.append("\t- ").append(li); - sb.append('\n'); - } - } - } - sb.append('\n'); - return sb.toString(); - } + List locks = threadDump.getLockedSynchronizers(); + if (locks != null) { + if (locks.size() > 0) { + sb.append("\n\tNumber of locked synchronizers = ").append(locks.size()); + sb.append('\n'); + for (String li : locks) { + sb.append("\t- ").append(li); + sb.append('\n'); + } + } + } + sb.append('\n'); + return sb.toString(); + } - private byte[] serialize(TBase result) throws TException { - return SerializationUtils.serialize(result, commandSerializerFactory); - } + private byte[] serialize(TBase result) throws TException { + return SerializationUtils.serialize(result, commandSerializerFactory); + } - private TBase deserialize(byte[] objectData) throws TException { - return SerializationUtils.deserialize(objectData, commandDeserializerFactory); - } + private TBase deserialize(byte[] objectData) throws TException { + return SerializationUtils.deserialize(objectData, commandDeserializerFactory); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/controller/FilteredMapController.java b/web/src/main/java/com/navercorp/pinpoint/web/controller/FilteredMapController.java index 784d76e53..cb3592059 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/controller/FilteredMapController.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/controller/FilteredMapController.java @@ -49,34 +49,34 @@ public class FilteredMapController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private FilteredMapService filteredMapService; + @Autowired + private FilteredMapService filteredMapService; @Autowired private FilterBuilder filterBuilder; - /** + /** * filtered server map data query within from ~ to timeframe - * - * @param applicationName - * @param serviceTypeCode - * @param from - * @param to - * @param filterText - * @param limit - * @return - */ - @RequestMapping(value = "/getFilteredServerMapData", method = RequestMethod.GET) + * + * @param applicationName + * @param serviceTypeCode + * @param from + * @param to + * @param filterText + * @param limit + * @return + */ + @RequestMapping(value = "/getFilteredServerMapData", method = RequestMethod.GET) @ResponseBody - public FilterMapWrap getFilteredServerMapData( - @RequestParam("applicationName") String applicationName, - @RequestParam("serviceTypeCode") short serviceTypeCode, - @RequestParam("from") long from, - @RequestParam("to") long to, + public FilterMapWrap getFilteredServerMapData( + @RequestParam("applicationName") String applicationName, + @RequestParam("serviceTypeCode") short serviceTypeCode, + @RequestParam("from") long from, + @RequestParam("to") long to, @RequestParam("originTo") long originTo, - @RequestParam(value = "filter", required = false) String filterText, - @RequestParam(value = "hint", required = false) String filterHint, - @RequestParam(value = "limit", required = false, defaultValue = "10000") int limit) { + @RequestParam(value = "filter", required = false) String filterText, + @RequestParam(value = "hint", required = false) String filterHint, + @RequestParam(value = "limit", required = false, defaultValue = "10000") int limit) { limit = LimitUtils.checkRange(limit); final Filter filter = filterBuilder.build(filterText, filterHint); final Range range = new Range(from, to); @@ -97,35 +97,35 @@ public class FilteredMapController { FilterMapWrap mapWrap = new FilterMapWrap(map); mapWrap.setLastFetchedTimestamp(lastScanTime); return mapWrap; - } + } - /** + /** * filtered server map data query for the last "Period" up to now * - * - * @param applicationName - * @param serviceTypeCode - * @param filterText - * @param limit - * @return - */ - @RequestMapping(value = "/getLastFilteredServerMapData", method = RequestMethod.GET) + * + * @param applicationName + * @param serviceTypeCode + * @param filterText + * @param limit + * @return + */ + @RequestMapping(value = "/getLastFilteredServerMapData", method = RequestMethod.GET) @ResponseBody - public FilterMapWrap getLastFilteredServerMapData( - @RequestParam("applicationName") String applicationName, - @RequestParam("serviceTypeCode") short serviceTypeCode, - @RequestParam("period") long period, - @RequestParam(value = "filter", required = false) String filterText, - @RequestParam(value = "hint", required = false) String filterHint, - @RequestParam(value = "limit", required = false, defaultValue = "1000000") int limit) { + public FilterMapWrap getLastFilteredServerMapData( + @RequestParam("applicationName") String applicationName, + @RequestParam("serviceTypeCode") short serviceTypeCode, + @RequestParam("period") long period, + @RequestParam(value = "filter", required = false) String filterText, + @RequestParam(value = "hint", required = false) String filterHint, + @RequestParam(value = "limit", required = false, defaultValue = "1000000") int limit) { limit = LimitUtils.checkRange(limit); - long to = TimeUtils.getDelayLastTime(); - long from = to - period; + long to = TimeUtils.getDelayLastTime(); + long from = to - period; // TODO: since realtime query is enabled for now, calling parameters are fixed as "..., to, to, ..." // may need additional @RequestParam("originTo") - return getFilteredServerMapData(applicationName, serviceTypeCode, from, to, to, filterText, filterHint, limit); - } + return getFilteredServerMapData(applicationName, serviceTypeCode, from, to, to, filterText, filterHint, limit); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/controller/MainController.java b/web/src/main/java/com/navercorp/pinpoint/web/controller/MainController.java index 1afdf72da..aa2b8823e 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/controller/MainController.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/controller/MainController.java @@ -38,23 +38,23 @@ import org.springframework.web.bind.annotation.ResponseBody; @Controller public class MainController { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private CommonService commonService; + @Autowired + private CommonService commonService; - @RequestMapping(value = "/applications", method = RequestMethod.GET) + @RequestMapping(value = "/applications", method = RequestMethod.GET) @ResponseBody - public ApplicationGroup getApplicationGroup() { - List applicationList = commonService.selectAllApplicationNames(); + public ApplicationGroup getApplicationGroup() { + List applicationList = commonService.selectAllApplicationNames(); logger.debug("/applications {}", applicationList); return new ApplicationGroup(applicationList); - } + } - @RequestMapping(value = "/serverTime", method = RequestMethod.GET) + @RequestMapping(value = "/serverTime", method = RequestMethod.GET) @ResponseBody - public ServerTime getServerTime() { - return new ServerTime(); - } + public ServerTime getServerTime() { + return new ServerTime(); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/controller/MapController.java b/web/src/main/java/com/navercorp/pinpoint/web/controller/MapController.java index ab2e345da..5b3d7e291 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/controller/MapController.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/controller/MapController.java @@ -53,27 +53,27 @@ public class MapController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired - private MapService mapService; + private MapService mapService; @Autowired private Limiter dateLimit; - /** + /** * Server map data query within from ~ to timeframe - * - * @param applicationName - * @param serviceTypeCode - * @param from - * @param to - * @return - */ - @RequestMapping(value = "/getServerMapData", method = RequestMethod.GET) + * + * @param applicationName + * @param serviceTypeCode + * @param from + * @param to + * @return + */ + @RequestMapping(value = "/getServerMapData", method = RequestMethod.GET) @ResponseBody - public MapWrap getServerMapData( - @RequestParam("applicationName") String applicationName, - @RequestParam("serviceTypeCode") short serviceTypeCode, - @RequestParam("from") long from, - @RequestParam("to") long to) { + public MapWrap getServerMapData( + @RequestParam("applicationName") String applicationName, + @RequestParam("serviceTypeCode") short serviceTypeCode, + @RequestParam("from") long from, + @RequestParam("to") long to) { final Range range = new Range(from, to); this.dateLimit.limit(from, to); logger.debug("range:{}", TimeUnit.MILLISECONDS.toMinutes(range.getRange())); @@ -81,51 +81,51 @@ public class MapController { ApplicationMap map = mapService.selectApplicationMap(application, range); - return new MapWrap(map); - } + return new MapWrap(map); + } - /** + /** * Server map data query for the last "Period" timeframe - * - * @param applicationName - * @param serviceTypeCode - * @param period - * @return - */ - @RequestMapping(value = "/getLastServerMapData", method = RequestMethod.GET) + * + * @param applicationName + * @param serviceTypeCode + * @param period + * @return + */ + @RequestMapping(value = "/getLastServerMapData", method = RequestMethod.GET) @ResponseBody - public MapWrap getLastServerMapData( - @RequestParam("applicationName") String applicationName, - @RequestParam("serviceTypeCode") short serviceTypeCode, - @RequestParam("period") long period) { + public MapWrap getLastServerMapData( + @RequestParam("applicationName") String applicationName, + @RequestParam("serviceTypeCode") short serviceTypeCode, + @RequestParam("period") long period) { - long to = TimeUtils.getDelayLastTime(); - long from = to - period; - return getServerMapData(applicationName, serviceTypeCode, from, to); - } + long to = TimeUtils.getDelayLastTime(); + long from = to - period; + return getServerMapData(applicationName, serviceTypeCode, from, to); + } - /** + /** * Possible deprecation expected when UI change push forward to pick a map first from UI * Unfiltered server map request data query - * - * @param model - * @param from - * @param to - * @param sourceApplicationName - * @param sourceServiceType - * @param targetApplicationName - * @param targetServiceType - * @return - */ + * + * @param model + * @param from + * @param to + * @param sourceApplicationName + * @param sourceServiceType + * @param targetApplicationName + * @param targetServiceType + * @return + */ @Deprecated - @RequestMapping(value = "/linkStatistics", method = RequestMethod.GET) - public String getLinkStatistics(Model model, - @RequestParam("from") long from, - @RequestParam("to") long to, - @RequestParam("sourceApplicationName") String sourceApplicationName, - @RequestParam("sourceServiceType") short sourceServiceType, - @RequestParam("targetApplicationName") String targetApplicationName, - @RequestParam("targetServiceType") short targetServiceType) { + @RequestMapping(value = "/linkStatistics", method = RequestMethod.GET) + public String getLinkStatistics(Model model, + @RequestParam("from") long from, + @RequestParam("to") long to, + @RequestParam("sourceApplicationName") String sourceApplicationName, + @RequestParam("sourceServiceType") short sourceServiceType, + @RequestParam("targetApplicationName") String targetApplicationName, + @RequestParam("targetServiceType") short targetServiceType) { final Application sourceApplication = new Application(sourceApplicationName, sourceServiceType); final Application destinationApplication = new Application(targetApplicationName, targetServiceType); @@ -133,14 +133,14 @@ public class MapController { NodeHistogram nodeHistogram = mapService.linkStatistics(sourceApplication, destinationApplication, range); - model.addAttribute("range", range); + model.addAttribute("range", range); model.addAttribute("sourceApplication", sourceApplication); model.addAttribute("targetApplication", destinationApplication); Histogram applicationHistogram = nodeHistogram.getApplicationHistogram(); - model.addAttribute("linkStatistics", applicationHistogram); + model.addAttribute("linkStatistics", applicationHistogram); List applicationTimeSeriesHistogram = nodeHistogram.getApplicationTimeHistogram(); @@ -153,12 +153,12 @@ public class MapController { model.addAttribute("timeSeriesHistogram", applicationTimeSeriesHistogramJson); // looks like we need to specify "from, to" to the result. but data got passed thru as it is. - model.addAttribute("resultFrom", from); - model.addAttribute("resultTo", to); + model.addAttribute("resultFrom", from); + model.addAttribute("resultTo", to); - return "linkStatistics"; - } + return "linkStatistics"; + } private final static ObjectMapper MAPPER = new ObjectMapper(); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/controller/ScatterChartController.java b/web/src/main/java/com/navercorp/pinpoint/web/controller/ScatterChartController.java index cdd7999c5..86ae08b4f 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/controller/ScatterChartController.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/controller/ScatterChartController.java @@ -54,13 +54,13 @@ import org.springframework.web.servlet.ModelAndView; @Controller public class ScatterChartController { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private ScatterChartService scatter; + @Autowired + private ScatterChartService scatter; - @Autowired - private FilteredMapService flow; + @Autowired + private FilteredMapService flow; @Autowired private FilterBuilder filterBuilder; @@ -70,64 +70,64 @@ public class ScatterChartController { private static final String PREFIX_RESPONSE_TIME = "R"; @Deprecated - @RequestMapping(value = "/scatterpopup", method = RequestMethod.GET) - public String scatterPopup(Model model, - @RequestParam("application") String applicationName, - @RequestParam("from") long from, - @RequestParam("to") long to, - @RequestParam("period") long period, - @RequestParam("usePeriod") boolean usePeriod, - @RequestParam(value = "filter", required = false) String filterText) { - model.addAttribute("applicationName", applicationName); - model.addAttribute("from", from); - model.addAttribute("to", to); - model.addAttribute("period", period); - model.addAttribute("usePeriod", usePeriod); - model.addAttribute("filter", filterText); - return "scatterPopup"; - } + @RequestMapping(value = "/scatterpopup", method = RequestMethod.GET) + public String scatterPopup(Model model, + @RequestParam("application") String applicationName, + @RequestParam("from") long from, + @RequestParam("to") long to, + @RequestParam("period") long period, + @RequestParam("usePeriod") boolean usePeriod, + @RequestParam(value = "filter", required = false) String filterText) { + model.addAttribute("applicationName", applicationName); + model.addAttribute("from", from); + model.addAttribute("to", to); + model.addAttribute("period", period); + model.addAttribute("usePeriod", usePeriod); + model.addAttribute("filter", filterText); + return "scatterPopup"; + } - /** - * - * @param applicationName - * @param from - * @param to - * @param limit - * max number of data return. if the requested data exceed this limit, we need additional calls to - * fetch the rest of the data - * @return - */ - @RequestMapping(value = "/getScatterData", method = RequestMethod.GET) - public ModelAndView getScatterData( - @RequestParam("application") String applicationName, - @RequestParam("from") long from, - @RequestParam("to") long to, - @RequestParam("limit") int limit, - @RequestParam(value = "filter", required = false) String filterText, - @RequestParam(value = "_callback", required = false) String jsonpCallback, - @RequestParam(value = "v", required = false, defaultValue = "2") int version) { + /** + * + * @param applicationName + * @param from + * @param to + * @param limit + * max number of data return. if the requested data exceed this limit, we need additional calls to + * fetch the rest of the data + * @return + */ + @RequestMapping(value = "/getScatterData", method = RequestMethod.GET) + public ModelAndView getScatterData( + @RequestParam("application") String applicationName, + @RequestParam("from") long from, + @RequestParam("to") long to, + @RequestParam("limit") int limit, + @RequestParam(value = "filter", required = false) String filterText, + @RequestParam(value = "_callback", required = false) String jsonpCallback, + @RequestParam(value = "v", required = false, defaultValue = "2") int version) { limit = LimitUtils.checkRange(limit); - StopWatch watch = new StopWatch(); - watch.start("selectScatterData"); + StopWatch watch = new StopWatch(); + watch.start("selectScatterData"); - // TODO range check verification exception occurs. "from" is bigger than "to" + // TODO range check verification exception occurs. "from" is bigger than "to" final Range range = Range.createUncheckedRange(from, to); logger.debug("fetch scatter data. {}, LIMIT={}, FILTER={}", range, limit, filterText); ModelAndView mv; - if (filterText == null) { + if (filterText == null) { mv = selectScatterData(applicationName, range, limit, jsonpCallback); } else { mv = selectFilterScatterDataData(applicationName, range, filterText, limit, jsonpCallback); - } + } - watch.stop(); + watch.stop(); - logger.info("Fetch scatterData time : {}ms", watch.getLastTaskTimeMillis()); + logger.info("Fetch scatterData time : {}ms", watch.getLastTaskTimeMillis()); return mv; - } + } private ModelAndView selectFilterScatterDataData(String applicationName, Range range, String filterText, int limit, String jsonpCallback) { @@ -136,7 +136,7 @@ public class ScatterChartController { final List traceIdList = limitedScanResult.getScanData(); logger.trace("submitted transactionId count={}", traceIdList.size()); - // TODO just need sorted? we need range check with tree-based structure. + // TODO just need sorted? we need range check with tree-based structure. SortedSet traceIdSet = new TreeSet(traceIdList); logger.debug("unified traceIdSet size={}", traceIdSet.size()); @@ -183,48 +183,48 @@ public class ScatterChartController { } /** - * scatter chart data query for "NOW" button - * - * @param applicationName - * @param limit - * @return - */ - @RequestMapping(value = "/getLastScatterData", method = RequestMethod.GET) - public ModelAndView getLastScatterData( - @RequestParam("application") String applicationName, - @RequestParam("period") long period, - @RequestParam("limit") int limit, - @RequestParam(value = "filter", required = false) String filterText, - @RequestParam(value = "_callback", required = false) String jsonpCallback, - @RequestParam(value = "v", required = false, defaultValue = "1") int version) { + * scatter chart data query for "NOW" button + * + * @param applicationName + * @param limit + * @return + */ + @RequestMapping(value = "/getLastScatterData", method = RequestMethod.GET) + public ModelAndView getLastScatterData( + @RequestParam("application") String applicationName, + @RequestParam("period") long period, + @RequestParam("limit") int limit, + @RequestParam(value = "filter", required = false) String filterText, + @RequestParam(value = "_callback", required = false) String jsonpCallback, + @RequestParam(value = "v", required = false, defaultValue = "1") int version) { limit = LimitUtils.checkRange(limit); long to = TimeUtils.getDelayLastTime(); - long from = to - period; + long from = to - period; - // TODO versioning is temporary. to sync template change and server dev - return getScatterData(applicationName, from, to, limit, filterText, jsonpCallback, version); - } + // TODO versioning is temporary. to sync template change and server dev + return getScatterData(applicationName, from, to, limit, filterText, jsonpCallback, version); + } - /** - * selected points from scatter chart data query - * - * @param model - * @param request - * @param response - * @return - */ - @RequestMapping(value = "/transactionmetadata", method = RequestMethod.POST) - public String transactionmetadata(Model model, HttpServletRequest request, HttpServletResponse response) { + /** + * selected points from scatter chart data query + * + * @param model + * @param request + * @param response + * @return + */ + @RequestMapping(value = "/transactionmetadata", method = RequestMethod.POST) + public String transactionmetadata(Model model, HttpServletRequest request, HttpServletResponse response) { TransactionMetadataQuery query = parseSelectTransaction(request); if (query.size() > 0) { - List metadata = scatter.selectTransactionMetadata(query); - model.addAttribute("metadata", metadata); - } + List metadata = scatter.selectTransactionMetadata(query); + model.addAttribute("metadata", metadata); + } - return "transactionmetadata"; - } + return "transactionmetadata"; + } private TransactionMetadataQuery parseSelectTransaction(HttpServletRequest request) { final TransactionMetadataQuery query = new TransactionMetadataQuery(); @@ -246,7 +246,7 @@ public class ScatterChartController { } /** - * trasaction list query for selected points in scatter chart + * trasaction list query for selected points in scatter chart * *

      * TEST URL = http://localhost:7080/transactionmetadata2.pinpoint?application=FRONT-WEB&from=1394432299032&to=1394433498269&responseFrom=100&responseTo=200&responseOffset=100&limit=10
@@ -257,75 +257,75 @@ public class ScatterChartController {
      * @param response
      * @return
      */
-	@RequestMapping(value = "/transactionmetadata2", method = RequestMethod.GET)
-	public String getTransaction(Model model,
-								@RequestParam("application") String applicationName,
-								@RequestParam("from") long from,
-								@RequestParam("to") long to,
-								@RequestParam("responseFrom") int responseFrom,
-								@RequestParam("responseTo") int responseTo,
-								@RequestParam("limit") int limit,
-								@RequestParam(value = "offsetTime", required = false, defaultValue = "-1") long offsetTime,
-								@RequestParam(value = "offsetTransactionId", required = false) String offsetTransactionId,
-								@RequestParam(value = "offsetTransactionElapsed", required = false, defaultValue = "-1") int offsetTransactionElapsed,
-								@RequestParam(value = "filter", required = false) String filterText) {
+    @RequestMapping(value = "/transactionmetadata2", method = RequestMethod.GET)
+    public String getTransaction(Model model,
+                                @RequestParam("application") String applicationName,
+                                @RequestParam("from") long from,
+                                @RequestParam("to") long to,
+                                @RequestParam("responseFrom") int responseFrom,
+                                @RequestParam("responseTo") int responseTo,
+                                @RequestParam("limit") int limit,
+                                @RequestParam(value = "offsetTime", required = false, defaultValue = "-1") long offsetTime,
+                                @RequestParam(value = "offsetTransactionId", required = false) String offsetTransactionId,
+                                @RequestParam(value = "offsetTransactionElapsed", required = false, defaultValue = "-1") int offsetTransactionElapsed,
+                                @RequestParam(value = "filter", required = false) String filterText) {
 
-		limit = LimitUtils.checkRange(limit);
+        limit = LimitUtils.checkRange(limit);
 
-		StopWatch watch = new StopWatch();
-		watch.start("selectScatterData");
+        StopWatch watch = new StopWatch();
+        watch.start("selectScatterData");
 
-		final SelectedScatterArea area = SelectedScatterArea.createUncheckedArea(from, to, responseFrom, responseTo);
+        final SelectedScatterArea area = SelectedScatterArea.createUncheckedArea(from, to, responseFrom, responseTo);
         logger.debug("fetch scatter data. {}, LIMIT={}, FILTER={}", area, limit, filterText);
 
-		if (filterText == null) {
+        if (filterText == null) {
 
-			// query data above "limit" first
-			TransactionId offsetId = null;
-			List extraMetadata = null;
-			if (offsetTransactionId != null) {
-				offsetId = new TransactionId(offsetTransactionId);
+            // query data above "limit" first
+            TransactionId offsetId = null;
+            List extraMetadata = null;
+            if (offsetTransactionId != null) {
+                offsetId = new TransactionId(offsetTransactionId);
 
-				SelectedScatterArea extraArea = SelectedScatterArea.createUncheckedArea(offsetTime, offsetTime, responseFrom, responseTo);
-				List extraAreaDotList = scatter.selectScatterData(applicationName, extraArea, offsetId, offsetTransactionElapsed, limit);
-				extraMetadata = scatter.selectTransactionMetadata(parseSelectTransaction(extraAreaDotList));
-				model.addAttribute("extraMetadata", extraMetadata);
-			}
+                SelectedScatterArea extraArea = SelectedScatterArea.createUncheckedArea(offsetTime, offsetTime, responseFrom, responseTo);
+                List extraAreaDotList = scatter.selectScatterData(applicationName, extraArea, offsetId, offsetTransactionElapsed, limit);
+                extraMetadata = scatter.selectTransactionMetadata(parseSelectTransaction(extraAreaDotList));
+                model.addAttribute("extraMetadata", extraMetadata);
+            }
 
-			// query data up to limit
-			if (extraMetadata == null || extraMetadata.size() < limit) {
-				int newlimit = limit - ((extraMetadata == null) ? 0 : extraMetadata.size());
-				List selectedDotList = scatter.selectScatterData(applicationName, area, null, -1, newlimit);
-				List metadata = scatter.selectTransactionMetadata(parseSelectTransaction(selectedDotList));
-				model.addAttribute("metadata", metadata);
-			}
-		} else {
-			final LimitedScanResult> limitedScanResult = flow.selectTraceIdsFromApplicationTraceIndex(applicationName, area, limit);
-			final List traceIdList = limitedScanResult.getScanData();
-			logger.trace("submitted transactionId count={}", traceIdList.size());
+            // query data up to limit
+            if (extraMetadata == null || extraMetadata.size() < limit) {
+                int newlimit = limit - ((extraMetadata == null) ? 0 : extraMetadata.size());
+                List selectedDotList = scatter.selectScatterData(applicationName, area, null, -1, newlimit);
+                List metadata = scatter.selectTransactionMetadata(parseSelectTransaction(selectedDotList));
+                model.addAttribute("metadata", metadata);
+            }
+        } else {
+            final LimitedScanResult> limitedScanResult = flow.selectTraceIdsFromApplicationTraceIndex(applicationName, area, limit);
+            final List traceIdList = limitedScanResult.getScanData();
+            logger.trace("submitted transactionId count={}", traceIdList.size());
 
-			// TODO: just sorted?  we need range check based on tree structure
-			SortedSet traceIdSet = new TreeSet(traceIdList);
-			logger.debug("unified traceIdSet size={}", traceIdSet.size());
+            // TODO: just sorted?  we need range check based on tree structure
+            SortedSet traceIdSet = new TreeSet(traceIdList);
+            logger.debug("unified traceIdSet size={}", traceIdSet.size());
 
             List dots = scatter.selectScatterData(traceIdSet, applicationName, filterBuilder.build(filterText));
-		}
+        }
 
         watch.stop();
-		logger.info("Fetch scatterData time : {}ms", watch.getLastTaskTimeMillis());
+        logger.info("Fetch scatterData time : {}ms", watch.getLastTaskTimeMillis());
 
-		return "transactionmetadata2";
-	}
+        return "transactionmetadata2";
+    }
 
-	private TransactionMetadataQuery parseSelectTransaction(List dotList) {
-		TransactionMetadataQuery query = new TransactionMetadataQuery();
-		if (dotList == null) {
-			return query;
-		}
-		for (Dot dot : dotList) {
-			query.addQueryCondition(dot.getTransactionId(), dot.getAcceptedTime(), dot.getElapsedTime());
-		}
-		logger.debug("query:{}", query);
-		return query;
-	}
+    private TransactionMetadataQuery parseSelectTransaction(List dotList) {
+        TransactionMetadataQuery query = new TransactionMetadataQuery();
+        if (dotList == null) {
+            return query;
+        }
+        for (Dot dot : dotList) {
+            query.addQueryCondition(dot.getTransactionId(), dot.getAcceptedTime(), dot.getElapsedTime());
+        }
+        logger.debug("query:{}", query);
+        return query;
+    }
 }
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationIndexDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationIndexDao.java
index 49cf9bd32..59810d1ee 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationIndexDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationIndexDao.java
@@ -26,11 +26,11 @@ import com.navercorp.pinpoint.web.vo.Application;
  * 
  */
 public interface ApplicationIndexDao {
-	List selectAllApplicationNames();
+    List selectAllApplicationNames();
 
-	List selectAgentIds(String applicationName);
-	
-	void deleteApplicationName(String applicationName);
-	
-	void deleteAgentId(String applicationName, String agentId);
+    List selectAgentIds(String applicationName);
+
+    void deleteApplicationName(String applicationName);
+
+    void deleteAgentId(String applicationName, String agentId);
 }
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationTraceIndexDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationTraceIndexDao.java
index 7c5a02824..24760ddf2 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationTraceIndexDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationTraceIndexDao.java
@@ -30,22 +30,22 @@ import com.navercorp.pinpoint.web.vo.scatter.Dot;
  */
 public interface ApplicationTraceIndexDao {
 
-	LimitedScanResult> scanTraceIndex(String applicationName, Range range, int limit);
+    LimitedScanResult> scanTraceIndex(String applicationName, Range range, int limit);
 
-	LimitedScanResult> scanTraceIndex(String applicationName, SelectedScatterArea range, int limit);
+    LimitedScanResult> scanTraceIndex(String applicationName, SelectedScatterArea range, int limit);
 
-	List scanTraceScatter(String applicationName, Range range, int limit);
+    List scanTraceScatter(String applicationName, Range range, int limit);
 
-	/**
-	 *
-	 * select transactions in a selection range(box) in the scatter chart.
-	 * 
-	 * @param applicationName
-	 * @param area
-	 * @param offsetTransactionId
-	 * @param offsetTransactionElapsed
-	 * @param limit
-	 * @return
-	 */
-	List scanTraceScatter(String applicationName, SelectedScatterArea area, TransactionId offsetTransactionId, int offsetTransactionElapsed, int limit);
+    /**
+     *
+     * select transactions in a selection range(box) in the scatter chart.
+     *
+     * @param applicationName
+     * @param area
+     * @param offsetTransactionId
+     * @param offsetTransactionElapsed
+     * @param limit
+     * @return
+     */
+    List scanTraceScatter(String applicationName, SelectedScatterArea area, TransactionId offsetTransactionId, int offsetTransactionElapsed, int limit);
 }
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/MapStatisticsCalleeDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/MapStatisticsCalleeDao.java
index 755b03978..a80e6fc65 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/MapStatisticsCalleeDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/MapStatisticsCalleeDao.java
@@ -28,8 +28,8 @@ import com.navercorp.pinpoint.web.vo.Range;
  * 
  */
 public interface MapStatisticsCalleeDao {
-	LinkDataMap selectCallee(Application calleeApplication, Range range);
+    LinkDataMap selectCallee(Application calleeApplication, Range range);
 
     @Deprecated
-	List selectCalleeStatistics(Application callerApplication, Application calleeApplication, Range range);
+    List selectCalleeStatistics(Application callerApplication, Application calleeApplication, Range range);
 }
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/MapStatisticsCallerDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/MapStatisticsCallerDao.java
index 3b016c015..5654b4041 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/MapStatisticsCallerDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/MapStatisticsCallerDao.java
@@ -28,7 +28,7 @@ import com.navercorp.pinpoint.web.vo.Range;
  * 
  */
 public interface MapStatisticsCallerDao {
-	LinkDataMap selectCaller(Application callerApplication, Range range);
+    LinkDataMap selectCaller(Application callerApplication, Range range);
 
-	List selectCallerStatistics(Application callerApplication, Application calleeApplication, Range range);
+    List selectCallerStatistics(Application callerApplication, Application calleeApplication, Range range);
 }
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentInfoDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentInfoDao.java
index e8489c64c..f99b47ebd 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentInfoDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentInfoDao.java
@@ -55,7 +55,7 @@ public class HbaseAgentInfoDao implements AgentInfoDao {
      * @return
      */
     @Override
-	public List getAgentInfo(final String agentId, final Range range) {
+    public List getAgentInfo(final String agentId, final Range range) {
         if (agentId == null) {
             throw new NullPointerException("agentId must not be null");
         }
@@ -69,8 +69,8 @@ public class HbaseAgentInfoDao implements AgentInfoDao {
         Scan scan = new Scan();
         scan.setCaching(20);
 
-		long fromTime = TimeUtils.reverseTimeMillis(range.getTo());
-		long toTime = TimeUtils.reverseTimeMillis(1);
+        long fromTime = TimeUtils.reverseTimeMillis(range.getTo());
+        long toTime = TimeUtils.reverseTimeMillis(1);
 
         byte[] agentIdBytes = Bytes.toBytes(agentId);
         byte[] startKeyBytes = RowKeyUtils.concatFixedByteAndLong(agentIdBytes, HBaseTables.AGENT_NAME_MAX_LEN, fromTime);
@@ -81,41 +81,41 @@ public class HbaseAgentInfoDao implements AgentInfoDao {
         scan.addFamily(HBaseTables.AGENTINFO_CF_INFO);
 
         List found = hbaseOperations2.find(HBaseTables.AGENTINFO, scan, new ResultsExtractor>() {
-			@Override
-			public List extractData(ResultScanner results) throws Exception {
-				final List result = new ArrayList();
-				int found = 0;
+            @Override
+            public List extractData(ResultScanner results) throws Exception {
+                final List result = new ArrayList();
+                int found = 0;
                 for (Result next : results) {
-					found++;
-					byte[] row = next.getRow();
-					long reverseStartTime = BytesUtils.bytesToLong(row, HBaseTables.AGENT_NAME_MAX_LEN);
-					long startTime = TimeUtils.recoveryTimeMillis(reverseStartTime);
-					byte[] serializedAgentInfo = next.getValue(HBaseTables.AGENTINFO_CF_INFO, HBaseTables.AGENTINFO_CF_INFO_IDENTIFIER);
-					byte[] serializedServerMetaData = next.getValue(HBaseTables.AGENTINFO_CF_INFO, HBaseTables.AGENTINFO_CF_INFO_SERVER_META_DATA);
+                    found++;
+                    byte[] row = next.getRow();
+                    long reverseStartTime = BytesUtils.bytesToLong(row, HBaseTables.AGENT_NAME_MAX_LEN);
+                    long startTime = TimeUtils.recoveryTimeMillis(reverseStartTime);
+                    byte[] serializedAgentInfo = next.getValue(HBaseTables.AGENTINFO_CF_INFO, HBaseTables.AGENTINFO_CF_INFO_IDENTIFIER);
+                    byte[] serializedServerMetaData = next.getValue(HBaseTables.AGENTINFO_CF_INFO, HBaseTables.AGENTINFO_CF_INFO_SERVER_META_DATA);
 
-					logger.debug("found={}, {}, start={}", found, range, startTime);
+                    logger.debug("found={}, {}, start={}", found, range, startTime);
 
-					if (found > 1 && startTime <= range.getFrom()) {
-						logger.debug("stop finding agentInfo.");
-						break;
-					}
+                    if (found > 1 && startTime <= range.getFrom()) {
+                        logger.debug("stop finding agentInfo.");
+                        break;
+                    }
 
                     final AgentInfoBo.Builder agentInfoBoBuilder = new AgentInfoBo.Builder(serializedAgentInfo);
                     agentInfoBoBuilder.agentId(agentId);
                     agentInfoBoBuilder.startTime(startTime);
 
-					if (serializedServerMetaData != null) {
-					    agentInfoBoBuilder.serverMetaData(new ServerMetaDataBo.Builder(serializedServerMetaData).build());
-					}
-					final AgentInfoBo agentInfoBo = agentInfoBoBuilder.build();
+                    if (serializedServerMetaData != null) {
+                        agentInfoBoBuilder.serverMetaData(new ServerMetaDataBo.Builder(serializedServerMetaData).build());
+                    }
+                    final AgentInfoBo agentInfoBo = agentInfoBoBuilder.build();
 
-					logger.debug("found agentInfoBo {}", agentInfoBo);
-					result.add(agentInfoBo);
-				}
-				logger.debug("extracted agentInfoBo {}", result);
-				return result;
-			}
-		});
+                    logger.debug("found agentInfoBo {}", agentInfoBo);
+                    result.add(agentInfoBo);
+                }
+                logger.debug("extracted agentInfoBo {}", result);
+                return result;
+            }
+        });
 
         logger.debug("get agentInfo result, {}", found);
 
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDao.java
index 258e0932d..2caaed459 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentStatDao.java
@@ -116,7 +116,7 @@ public class HbaseAgentStatDao implements AgentStatDao {
         scan.setStartRow(endKey);
         scan.setStopRow(startKey);
 
-        //		scan.addColumn(HBaseTables.AGENT_STAT_CF_STATISTICS, HBaseTables.AGENT_STAT_CF_STATISTICS_V1);
+        //        scan.addColumn(HBaseTables.AGENT_STAT_CF_STATISTICS, HBaseTables.AGENT_STAT_CF_STATISTICS_V1);
         scan.addFamily(HBaseTables.AGENT_STAT_CF_STATISTICS);
         scan.setId("AgentStatScan");
 
@@ -125,36 +125,36 @@ public class HbaseAgentStatDao implements AgentStatDao {
         return scan;
     }
 
-    //	public List scanAgentStatList(String agentId, long start, long end, final int limit) {
-    //		if (logger.isDebugEnabled()) {
-    //			logger.debug("scanAgentStatList");
-    //		}
-    //		Scan scan = createScan(agentId, start, end);
-    //		
-    //		List list = hbaseOperations2.find(HBaseTables.AGENT_STAT, scan, rowKeyDistributor, new ResultsExtractor>() {
-    //			@Override
-    //			public List extractData(ResultScanner results) throws Exception {
-    //				TDeserializer deserializer = new TDeserializer();
-    //				List list = new ArrayList();
-    //				for (Result result : results) {
-    //					if (result == null) {
-    //						continue;
-    //					}
-    //					
-    //					if (list.size() >= limit) {
-    //						break;
-    //					}
-    //					
-    //					for (KeyValue kv : result.raw()) {
-    //						AgentStat agentStat = new AgentStat();
-    //						deserializer.deserialize(agentStat, kv.getBuffer());
-    //						list.add(agentStat);
-    //					}
-    //				}
-    //				return list;
-    //			}
-    //		});
-    //		return list;
-    //	}
+    //    public List scanAgentStatList(String agentId, long start, long end, final int limit) {
+    //        if (logger.isDebugEnabled()) {
+    //            logger.debug("scanAgentStatList");
+    //        }
+    //        Scan scan = createScan(agentId, start, end);
+    //
+    //        List list = hbaseOperations2.find(HBaseTables.AGENT_STAT, scan, rowKeyDistributor, new ResultsExtractor>() {
+    //            @Override
+    //            public List extractData(ResultScanner results) throws Exception {
+    //                TDeserializer deserializer = new TDeserializer();
+    //                List list = new ArrayList();
+    //                for (Result result : results) {
+    //                    if (result == null) {
+    //                        continue;
+    //                    }
+    //
+    //                    if (list.size() >= limit) {
+    //                        break;
+    //                    }
+    //
+    //                    for (KeyValue kv : result.raw()) {
+    //                        AgentStat agentStat = new AgentStat();
+    //                        deserializer.deserialize(agentStat, kv.getBuffer());
+    //                        list.add(agentStat);
+    //                    }
+    //                }
+    //                return list;
+    //            }
+    //        });
+    //        return list;
+    //    }
 
 }
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java
index 603cdf3bd..2526d9137 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java
@@ -40,43 +40,43 @@ import com.navercorp.pinpoint.web.vo.Application;
 @Repository
 public class HbaseApplicationIndexDao implements ApplicationIndexDao {
 
-	@Autowired
-	private HbaseOperations2 hbaseOperations2;
+    @Autowired
+    private HbaseOperations2 hbaseOperations2;
 
-	@Autowired
-	@Qualifier("applicationNameMapper")
-	private RowMapper applicationNameMapper;
+    @Autowired
+    @Qualifier("applicationNameMapper")
+    private RowMapper applicationNameMapper;
 
-	@Autowired
-	@Qualifier("agentIdMapper")
-	private RowMapper> agentIdMapper;
+    @Autowired
+    @Qualifier("agentIdMapper")
+    private RowMapper> agentIdMapper;
 
-	@Override
-	public List selectAllApplicationNames() {
-		Scan scan = new Scan();
-		scan.setCaching(30);
-		return hbaseOperations2.find(HBaseTables.APPLICATION_INDEX, scan, applicationNameMapper);
-	}
+    @Override
+    public List selectAllApplicationNames() {
+        Scan scan = new Scan();
+        scan.setCaching(30);
+        return hbaseOperations2.find(HBaseTables.APPLICATION_INDEX, scan, applicationNameMapper);
+    }
 
-	@Override
-	public List selectAgentIds(String applicationName) {
+    @Override
+    public List selectAgentIds(String applicationName) {
         if (applicationName == null) {
             throw new NullPointerException("applicationName must not be null");
         }
         byte[] rowKey = Bytes.toBytes(applicationName);
 
-		Get get = new Get(rowKey);
-		get.addFamily(HBaseTables.APPLICATION_INDEX_CF_AGENTS);
+        Get get = new Get(rowKey);
+        get.addFamily(HBaseTables.APPLICATION_INDEX_CF_AGENTS);
 
-		return hbaseOperations2.get(HBaseTables.APPLICATION_INDEX, get, agentIdMapper);
-	}
-	
-	@Override
-	public void deleteApplicationName(String applicationName) {
-		byte[] rowKey = Bytes.toBytes(applicationName);
-		Delete delete = new Delete(rowKey);
-		hbaseOperations2.delete(HBaseTables.APPLICATION_INDEX, delete);
-	}
+        return hbaseOperations2.get(HBaseTables.APPLICATION_INDEX, get, agentIdMapper);
+    }
+
+    @Override
+    public void deleteApplicationName(String applicationName) {
+        byte[] rowKey = Bytes.toBytes(applicationName);
+        Delete delete = new Delete(rowKey);
+        hbaseOperations2.delete(HBaseTables.APPLICATION_INDEX, delete);
+    }
 
     @Override
     public void deleteAgentId(String applicationName, String agentId) {
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationTraceIndexDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationTraceIndexDao.java
index 266bcd83b..e21138e45 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationTraceIndexDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationTraceIndexDao.java
@@ -64,31 +64,31 @@ import com.sematext.hbase.wd.AbstractRowKeyDistributor;
 @Repository
 public class HbaseApplicationTraceIndexDao implements ApplicationTraceIndexDao {
 
-	private final Logger logger = LoggerFactory.getLogger(this.getClass());
+    private final Logger logger = LoggerFactory.getLogger(this.getClass());
 
-	@Autowired
-	private HbaseOperations2 hbaseOperations2;
+    @Autowired
+    private HbaseOperations2 hbaseOperations2;
 
-	@Autowired
-	@Qualifier("transactionIdMapper")
-	private RowMapper> traceIndexMapper;
+    @Autowired
+    @Qualifier("transactionIdMapper")
+    private RowMapper> traceIndexMapper;
 
-	@Autowired
-	@Qualifier("traceIndexScatterMapper")
-	private RowMapper> traceIndexScatterMapper;
+    @Autowired
+    @Qualifier("traceIndexScatterMapper")
+    private RowMapper> traceIndexScatterMapper;
 
     @Autowired
     @Qualifier("applicationTraceIndexDistributor")
     private AbstractRowKeyDistributor traceIdRowKeyDistributor;
 
-	private int scanCacheSize = 256;
+    private int scanCacheSize = 256;
 
-	public void setScanCacheSize(int scanCacheSize) {
-		this.scanCacheSize = scanCacheSize;
-	}
+    public void setScanCacheSize(int scanCacheSize) {
+        this.scanCacheSize = scanCacheSize;
+    }
 
-	@Override
-	public LimitedScanResult> scanTraceIndex(final String applicationName, Range range, int limit) {
+    @Override
+    public LimitedScanResult> scanTraceIndex(final String applicationName, Range range, int limit) {
         if (applicationName == null) {
             throw new NullPointerException("applicationName must not be null");
         }
@@ -99,9 +99,9 @@ public class HbaseApplicationTraceIndexDao implements ApplicationTraceIndexDao {
             throw new IllegalArgumentException("negative limit:" + limit);
         }
         logger.debug("scanTraceIndex");
-		Scan scan = createScan(applicationName, range);
-		
-		final LimitedScanResult> limitedScanResult = new LimitedScanResult>();
+        Scan scan = createScan(applicationName, range);
+
+        final LimitedScanResult> limitedScanResult = new LimitedScanResult>();
         LastRowAccessor lastRowAccessor = new LastRowAccessor();
         List> traceIndexList = hbaseOperations2.find(HBaseTables.APPLICATION_TRACE_INDEX,
                 scan, traceIdRowKeyDistributor, limit, traceIndexMapper, lastRowAccessor);
@@ -110,7 +110,7 @@ public class HbaseApplicationTraceIndexDao implements ApplicationTraceIndexDao {
         for(List transactionId: traceIndexList) {
             transactionIdSum.addAll(transactionId);
         }
-		limitedScanResult.setScanData(transactionIdSum);
+        limitedScanResult.setScanData(transactionIdSum);
 
         if (transactionIdSum.size() >= limit) {
             Long lastRowTimestamp = lastRowAccessor.getLastRowTimestamp();
@@ -125,11 +125,11 @@ public class HbaseApplicationTraceIndexDao implements ApplicationTraceIndexDao {
             limitedScanResult.setLimitedTime(range.getFrom());
         }
 
-		return limitedScanResult;
-	}
+        return limitedScanResult;
+    }
 
-	@Override
-	public LimitedScanResult> scanTraceIndex(final String applicationName, SelectedScatterArea area, int limit) {
+    @Override
+    public LimitedScanResult> scanTraceIndex(final String applicationName, SelectedScatterArea area, int limit) {
         if (applicationName == null) {
             throw new NullPointerException("applicationName must not be null");
         }
@@ -140,9 +140,9 @@ public class HbaseApplicationTraceIndexDao implements ApplicationTraceIndexDao {
             throw new IllegalArgumentException("negative limit:" + limit);
         }
         logger.debug("scanTraceIndex");
-		Scan scan = createScan(applicationName, area.getTimeRange());
-		
-		final LimitedScanResult> limitedScanResult = new LimitedScanResult>();
+        Scan scan = createScan(applicationName, area.getTimeRange());
+
+        final LimitedScanResult> limitedScanResult = new LimitedScanResult>();
         LastRowAccessor lastRowAccessor = new LastRowAccessor();
         List> traceIndexList = hbaseOperations2.find(HBaseTables.APPLICATION_TRACE_INDEX,
                 scan, traceIdRowKeyDistributor, limit, traceIndexMapper, lastRowAccessor);
@@ -151,7 +151,7 @@ public class HbaseApplicationTraceIndexDao implements ApplicationTraceIndexDao {
         for(List transactionId: traceIndexList) {
             transactionIdSum.addAll(transactionId);
         }
-		limitedScanResult.setScanData(transactionIdSum);
+        limitedScanResult.setScanData(transactionIdSum);
 
         if (transactionIdSum.size() >= limit) {
             Long lastRowTimestamp = lastRowAccessor.getLastRowTimestamp();
@@ -166,8 +166,8 @@ public class HbaseApplicationTraceIndexDao implements ApplicationTraceIndexDao {
             limitedScanResult.setLimitedTime(area.getTimeRange().getFrom());
         }
 
-		return limitedScanResult;
-	}
+        return limitedScanResult;
+    }
 
     private class LastRowAccessor implements LimitEventHandler {
         private Long lastRowTimestamp = -1L;
@@ -186,9 +186,9 @@ public class HbaseApplicationTraceIndexDao implements ApplicationTraceIndexDao {
             long reverseStartTime = BytesUtils.bytesToLong(originalRow, PinpointConstants.APPLICATION_NAME_MAX_LEN);
             this.lastRowTimestamp = TimeUtils.recoveryTimeMillis(reverseStartTime);
             
-			byte[] qualifier = last.getQualifier();
-			this.lastTransactionId = TransactionIdMapper.parseVarTransactionId(qualifier, 0);
-			this.lastTransactionElapsed = BytesUtils.bytesToInt(qualifier, 0);
+            byte[] qualifier = last.getQualifier();
+            this.lastTransactionId = TransactionIdMapper.parseVarTransactionId(qualifier, 0);
+            this.lastTransactionElapsed = BytesUtils.bytesToInt(qualifier, 0);
             
             if (logger.isDebugEnabled()) {
                 logger.debug("lastRowTimestamp={}, lastTransactionId={}, lastTransactionElapsed={}", DateUtils.longToDateStr(lastRowTimestamp), lastTransactionId, lastTransactionElapsed);
@@ -199,37 +199,37 @@ public class HbaseApplicationTraceIndexDao implements ApplicationTraceIndexDao {
             return lastRowTimestamp;
         }
 
-		public TransactionId getLastTransactionId() {
-			return lastTransactionId;
-		}
+        public TransactionId getLastTransactionId() {
+            return lastTransactionId;
+        }
 
-		public int getLastTransactionElapsed() {
-			return lastTransactionElapsed;
-		}
+        public int getLastTransactionElapsed() {
+            return lastTransactionElapsed;
+        }
     }
 
-	private Scan createScan(String applicationName, Range range) {
-		Scan scan = new Scan();
-		scan.setCaching(this.scanCacheSize);
+    private Scan createScan(String applicationName, Range range) {
+        Scan scan = new Scan();
+        scan.setCaching(this.scanCacheSize);
 
-		byte[] bAgent = Bytes.toBytes(applicationName);
-		byte[] traceIndexStartKey = SpanUtils.getTraceIndexRowKey(bAgent, range.getFrom());
-		byte[] traceIndexEndKey = SpanUtils.getTraceIndexRowKey(bAgent, range.getTo());
+        byte[] bAgent = Bytes.toBytes(applicationName);
+        byte[] traceIndexStartKey = SpanUtils.getTraceIndexRowKey(bAgent, range.getFrom());
+        byte[] traceIndexEndKey = SpanUtils.getTraceIndexRowKey(bAgent, range.getTo());
 
         // start key is replaced by end key because key has been reversed
-		scan.setStartRow(traceIndexEndKey);
-		scan.setStopRow(traceIndexStartKey);
+        scan.setStartRow(traceIndexEndKey);
+        scan.setStopRow(traceIndexStartKey);
 
-		scan.addFamily(HBaseTables.APPLICATION_TRACE_INDEX_CF_TRACE);
-		scan.setId("ApplicationTraceIndexScan");
+        scan.addFamily(HBaseTables.APPLICATION_TRACE_INDEX_CF_TRACE);
+        scan.setId("ApplicationTraceIndexScan");
 
         // toString() method of Scan converts a message to json format so it is slow for the first time.
-		logger.trace("create scan:{}", scan);
-		return scan;
-	}
+        logger.trace("create scan:{}", scan);
+        return scan;
+    }
 
-	@Override
-	public List scanTraceScatter(String applicationName, Range range, final int limit) {
+    @Override
+    public List scanTraceScatter(String applicationName, Range range, final int limit) {
         if (applicationName == null) {
             throw new NullPointerException("applicationName must not be null");
         }
@@ -248,72 +248,72 @@ public class HbaseApplicationTraceIndexDao implements ApplicationTraceIndexDao {
             mergeList.addAll(dotList);
         }
         return mergeList;
-	}
-	
-	/**
-	 * 
-	 */
-	@Override
-	public List scanTraceScatter(String applicationName, SelectedScatterArea area, TransactionId offsetTransactionId, int offsetTransactionElapsed, int limit) {
-		if (applicationName == null) {
-			throw new NullPointerException("applicationName must not be null");
-		}
-		if (area == null) {
-			throw new NullPointerException("range must not be null");
-		}
-		if (limit < 0) {
-			throw new IllegalArgumentException("negative limit:" + limit);
-		}
-		logger.debug("scanTraceScatter");
-		Scan scan = createScan(applicationName, area.getTimeRange());
+    }
 
-		// method 1
+    /**
+     *
+     */
+    @Override
+    public List scanTraceScatter(String applicationName, SelectedScatterArea area, TransactionId offsetTransactionId, int offsetTransactionElapsed, int limit) {
+        if (applicationName == null) {
+            throw new NullPointerException("applicationName must not be null");
+        }
+        if (area == null) {
+            throw new NullPointerException("range must not be null");
+        }
+        if (limit < 0) {
+            throw new IllegalArgumentException("negative limit:" + limit);
+        }
+        logger.debug("scanTraceScatter");
+        Scan scan = createScan(applicationName, area.getTimeRange());
+
+        // method 1
         // not used yet. instead, use another row mapper (testing)
-		// scan.setFilter(makeResponseTimeFilter(area, offsetTransactionId, offsetTransactionElapsed));
-		
-		// method 2
-		ResponseTimeRange responseTimeRange = area.getResponseTimeRange();
-		TraceIndexScatterMapper2 mapper = new TraceIndexScatterMapper2(responseTimeRange.getFrom(), responseTimeRange.getTo());
-		
-		List> dotListList = hbaseOperations2.find(HBaseTables.APPLICATION_TRACE_INDEX, scan, traceIdRowKeyDistributor, limit, mapper);
-		
-		List result = new ArrayList();
-		for(List dotList : dotListList) {
-			result.addAll(dotList);
-		}
-		
-		return result;
-	}
-	
-	/**
+        // scan.setFilter(makeResponseTimeFilter(area, offsetTransactionId, offsetTransactionElapsed));
+
+        // method 2
+        ResponseTimeRange responseTimeRange = area.getResponseTimeRange();
+        TraceIndexScatterMapper2 mapper = new TraceIndexScatterMapper2(responseTimeRange.getFrom(), responseTimeRange.getTo());
+
+        List> dotListList = hbaseOperations2.find(HBaseTables.APPLICATION_TRACE_INDEX, scan, traceIdRowKeyDistributor, limit, mapper);
+
+        List result = new ArrayList();
+        for(List dotList : dotListList) {
+            result.addAll(dotList);
+        }
+
+        return result;
+    }
+
+    /**
      * make the hbase filter for selecting values of y-axis(response time) in order to select transactions in scatter chart.
      * 4 bytes for elapsed time should be attached for the prefix of column qualifier for to use this filter.
-	 *
-	 * @param area
-	 * @param offsetTransactionId
-	 * @param offsetTransactionElapsed
-	 * @return
-	 */
-	private Filter makeResponseTimeFilter(final SelectedScatterArea area, final TransactionId offsetTransactionId, int offsetTransactionElapsed) {
-		// filter by response time
-		ResponseTimeRange responseTimeRange = area.getResponseTimeRange();
-		byte[] responseFrom = Bytes.toBytes(responseTimeRange.getFrom());
-		byte[] responseTo = Bytes.toBytes(responseTimeRange.getTo());
-		FilterList filterList = new FilterList(Operator.MUST_PASS_ALL);
-		filterList.addFilter(new QualifierFilter(CompareOp.GREATER_OR_EQUAL, new BinaryPrefixComparator(responseFrom)));
-		filterList.addFilter(new QualifierFilter(CompareOp.LESS_OR_EQUAL, new BinaryPrefixComparator(responseTo)));
-		
-		// add offset
-		if (offsetTransactionId != null) {
-			final Buffer buffer = new AutomaticBuffer(32);
-			buffer.put(offsetTransactionElapsed);
-			buffer.putPrefixedString(offsetTransactionId.getAgentId());
-			buffer.putSVar(offsetTransactionId.getAgentStartTime());
-			buffer.putVar(offsetTransactionId.getTransactionSequence());
-			byte[] qualifierOffset = buffer.getBuffer();
+     *
+     * @param area
+     * @param offsetTransactionId
+     * @param offsetTransactionElapsed
+     * @return
+     */
+    private Filter makeResponseTimeFilter(final SelectedScatterArea area, final TransactionId offsetTransactionId, int offsetTransactionElapsed) {
+        // filter by response time
+        ResponseTimeRange responseTimeRange = area.getResponseTimeRange();
+        byte[] responseFrom = Bytes.toBytes(responseTimeRange.getFrom());
+        byte[] responseTo = Bytes.toBytes(responseTimeRange.getTo());
+        FilterList filterList = new FilterList(Operator.MUST_PASS_ALL);
+        filterList.addFilter(new QualifierFilter(CompareOp.GREATER_OR_EQUAL, new BinaryPrefixComparator(responseFrom)));
+        filterList.addFilter(new QualifierFilter(CompareOp.LESS_OR_EQUAL, new BinaryPrefixComparator(responseTo)));
 
-			filterList.addFilter(new QualifierFilter(CompareOp.GREATER, new BinaryPrefixComparator(qualifierOffset)));
-		}
-		return filterList;
-	}
+        // add offset
+        if (offsetTransactionId != null) {
+            final Buffer buffer = new AutomaticBuffer(32);
+            buffer.put(offsetTransactionElapsed);
+            buffer.putPrefixedString(offsetTransactionId.getAgentId());
+            buffer.putSVar(offsetTransactionId.getAgentStartTime());
+            buffer.putVar(offsetTransactionId.getTransactionSequence());
+            byte[] qualifierOffset = buffer.getBuffer();
+
+            filterList.addFilter(new QualifierFilter(CompareOp.GREATER, new BinaryPrefixComparator(qualifierOffset)));
+        }
+        return filterList;
+    }
 }
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseHostApplicationMapDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseHostApplicationMapDao.java
index 8b5ceac18..5ea02ddb5 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseHostApplicationMapDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseHostApplicationMapDao.java
@@ -53,15 +53,15 @@ import org.springframework.stereotype.Repository;
 @Repository
 public class HbaseHostApplicationMapDao implements HostApplicationMapDao {
 
-	private Logger logger = LoggerFactory.getLogger(this.getClass());
-	private int scanCacheSize = 10;
+    private Logger logger = LoggerFactory.getLogger(this.getClass());
+    private int scanCacheSize = 10;
 
-	@Autowired
-	private HbaseOperations2 hbaseOperations2;
+    @Autowired
+    private HbaseOperations2 hbaseOperations2;
 
-	@Autowired
-	@Qualifier("hostApplicationMapper")
-	private RowMapper hostApplicationMapper;
+    @Autowired
+    @Qualifier("hostApplicationMapper")
+    private RowMapper hostApplicationMapper;
 
     @Autowired
     @Qualifier("hostApplicationMapperVer2")
@@ -121,24 +121,24 @@ public class HbaseHostApplicationMapDao implements HostApplicationMapDao {
         return scan;
     }
 
-	@Override
-	public Set findAcceptApplicationName(Application fromApplication, Range range) {
+    @Override
+    public Set findAcceptApplicationName(Application fromApplication, Range range) {
         if (fromApplication == null) {
             throw new NullPointerException("fromApplication must not be null");
         }
         final Scan scan = createScan(fromApplication, range);
-		final List> result = hbaseOperations2.find(HBaseTables.HOST_APPLICATION_MAP_VER2, scan, acceptApplicationRowKeyDistributor, hostApplicationMapperVer2);
-		if (CollectionUtils.isNotEmpty(result)) {
+        final List> result = hbaseOperations2.find(HBaseTables.HOST_APPLICATION_MAP_VER2, scan, acceptApplicationRowKeyDistributor, hostApplicationMapperVer2);
+        if (CollectionUtils.isNotEmpty(result)) {
             final Set resultSet = new HashSet();
             for (List resultList : result) {
                 resultSet.addAll(resultList);
             }
             logger.debug("findAcceptApplicationName result:{}", resultSet);
             return resultSet;
-		} else {
-			return Collections.emptySet();
-		}
-	}
+        } else {
+            return Collections.emptySet();
+        }
+    }
 
 
 
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseMapStatisticsCalleeDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseMapStatisticsCalleeDao.java
index e2daec95c..53a6ffbf1 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseMapStatisticsCalleeDao.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseMapStatisticsCalleeDao.java
@@ -45,21 +45,21 @@ import org.springframework.stereotype.Repository;
 @Repository
 public class HbaseMapStatisticsCalleeDao implements MapStatisticsCalleeDao {
 
-	private Logger logger = LoggerFactory.getLogger(this.getClass());
-	private int scanCacheSize = 40;
+    private Logger logger = LoggerFactory.getLogger(this.getClass());
+    private int scanCacheSize = 40;
 
-	@Autowired
-	private HbaseOperations2 hbaseOperations2;
+    @Autowired
+    private HbaseOperations2 hbaseOperations2;
 
-	@Autowired
-	@Qualifier("mapStatisticsCalleeMapper")
-	private RowMapper mapStatisticsCalleeMapper;
+    @Autowired
+    @Qualifier("mapStatisticsCalleeMapper")
+    private RowMapper mapStatisticsCalleeMapper;
 
     @Autowired
     private RangeFactory rangeFactory;
 
-	@Override
-	public LinkDataMap selectCallee(Application calleeApplication, Range range) {
+    @Override
+    public LinkDataMap selectCallee(Application calleeApplication, Range range) {
         if (calleeApplication == null) {
             throw new NullPointerException("calleeApplication must not be null");
         }
@@ -67,14 +67,14 @@ public class HbaseMapStatisticsCalleeDao implements MapStatisticsCalleeDao {
             throw new NullPointerException("range must not be null");
         }
         Scan scan = createScan(calleeApplication, range);
-		List foundListList = hbaseOperations2.find(HBaseTables.MAP_STATISTICS_CALLER, scan, mapStatisticsCalleeMapper);
+        List foundListList = hbaseOperations2.find(HBaseTables.MAP_STATISTICS_CALLER, scan, mapStatisticsCalleeMapper);
+
+        if (foundListList.isEmpty()) {
+            logger.debug("There's no caller data. {}, {}", calleeApplication, range);
+        }
 
-		if (foundListList.isEmpty()) {
-			logger.debug("There's no caller data. {}, {}", calleeApplication, range);
-		}
-		
         return merge(foundListList);
-	}
+    }
 
     private LinkDataMap merge(List foundListList) {
         final LinkDataMap result = new LinkDataMap();
@@ -88,51 +88,51 @@ public class HbaseMapStatisticsCalleeDao implements MapStatisticsCalleeDao {
 
 
     /**
-	 * statistics information used when a link between nodes is clicked at the server map
-	 * 
-	 * @return 
-	 * list [
-	 *     map {
-	 *         key = timestamp
-	 *         value = map {
-	 *             key = histogram slot
-	 *             value = count
-	 *         }
-	 *     }
-	 * ]
-	 * 
- */ - @Override - public List selectCalleeStatistics(Application callerApplication, Application calleeApplication, Range range) { - if (logger.isDebugEnabled()) { - logger.debug("selectCalleeStatistics. {}, {}, {}", callerApplication, calleeApplication, range); - } - Scan scan = createScan(calleeApplication, range); + * statistics information used when a link between nodes is clicked at the server map + * + * @return
+     * list [
+     *     map {
+     *         key = timestamp
+     *         value = map {
+     *             key = histogram slot
+     *             value = count
+     *         }
+     *     }
+     * ]
+     * 
+ */ + @Override + public List selectCalleeStatistics(Application callerApplication, Application calleeApplication, Range range) { + if (logger.isDebugEnabled()) { + logger.debug("selectCalleeStatistics. {}, {}, {}", callerApplication, calleeApplication, range); + } + Scan scan = createScan(calleeApplication, range); final LinkFilter filter = new DefaultLinkFilter(callerApplication, calleeApplication); RowMapper mapper = new MapStatisticsCalleeMapper(filter); - return hbaseOperations2.find(HBaseTables.MAP_STATISTICS_CALLER, scan, mapper); - } + return hbaseOperations2.find(HBaseTables.MAP_STATISTICS_CALLER, scan, mapper); + } - private Scan createScan(Application application, Range range) { + private Scan createScan(Application application, Range range) { range = rangeFactory.createStatisticsRange(range); - if (logger.isDebugEnabled()) { - logger.debug("scan time:{} ", range.prettyToString()); - } - - // start key is replaced by end key because timestamp has been reversed - byte[] startKey = ApplicationMapStatisticsUtils.makeRowKey(application.getName(), application.getServiceTypeCode(), range.getTo()); - byte[] endKey = ApplicationMapStatisticsUtils.makeRowKey(application.getName(), application.getServiceTypeCode(), range.getFrom()); + if (logger.isDebugEnabled()) { + logger.debug("scan time:{} ", range.prettyToString()); + } - Scan scan = new Scan(); - scan.setCaching(this.scanCacheSize); - scan.setStartRow(startKey); - scan.setStopRow(endKey); - scan.addFamily(HBaseTables.MAP_STATISTICS_CALLEE_CF_COUNTER); - scan.setId("ApplicationStatisticsScan"); + // start key is replaced by end key because timestamp has been reversed + byte[] startKey = ApplicationMapStatisticsUtils.makeRowKey(application.getName(), application.getServiceTypeCode(), range.getTo()); + byte[] endKey = ApplicationMapStatisticsUtils.makeRowKey(application.getName(), application.getServiceTypeCode(), range.getFrom()); - return scan; - } + Scan scan = new Scan(); + scan.setCaching(this.scanCacheSize); + scan.setStartRow(startKey); + scan.setStopRow(endKey); + scan.addFamily(HBaseTables.MAP_STATISTICS_CALLEE_CF_COUNTER); + scan.setId("ApplicationStatisticsScan"); + + return scan; + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseMapStatisticsCallerDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseMapStatisticsCallerDao.java index 18382b7c4..f843280f6 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseMapStatisticsCallerDao.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseMapStatisticsCallerDao.java @@ -45,30 +45,30 @@ import org.springframework.stereotype.Repository; @Repository public class HbaseMapStatisticsCallerDao implements MapStatisticsCallerDao { - private Logger logger = LoggerFactory.getLogger(this.getClass()); - private int scanCacheSize = 40; + private Logger logger = LoggerFactory.getLogger(this.getClass()); + private int scanCacheSize = 40; - @Autowired - private HbaseOperations2 hbaseOperations2; + @Autowired + private HbaseOperations2 hbaseOperations2; - @Autowired - @Qualifier("mapStatisticsCallerMapper") - private RowMapper mapStatisticsCallerMapper; + @Autowired + @Qualifier("mapStatisticsCallerMapper") + private RowMapper mapStatisticsCallerMapper; @Autowired private RangeFactory rangeFactory; - @Override - public LinkDataMap selectCaller(Application callerApplication, Range range) { - Scan scan = createScan(callerApplication, range); - final List foundList = hbaseOperations2.find(HBaseTables.MAP_STATISTICS_CALLEE, scan, mapStatisticsCallerMapper); + @Override + public LinkDataMap selectCaller(Application callerApplication, Range range) { + Scan scan = createScan(callerApplication, range); + final List foundList = hbaseOperations2.find(HBaseTables.MAP_STATISTICS_CALLEE, scan, mapStatisticsCallerMapper); - if (foundList.isEmpty()) { - logger.debug("There's no caller data. {}, {}", callerApplication, range); - } + if (foundList.isEmpty()) { + logger.debug("There's no caller data. {}, {}", callerApplication, range); + } return merge(foundList); - } + } private LinkDataMap merge(List foundList) { final LinkDataMap result = new LinkDataMap(); @@ -79,52 +79,52 @@ public class HbaseMapStatisticsCallerDao implements MapStatisticsCallerDao { } /** - * statistics information used when a link between nodes is clicked at the server map - * - * @return
-	 * list [
-	 *     map {
-	 *         key = timestamp
-	 *         value = map {
-	 *             key = histogram slot
-	 *             value = count
-	 *         }
-	 *     }
-	 * ]
-	 * 
- */ - @Override + * statistics information used when a link between nodes is clicked at the server map + * + * @return
+     * list [
+     *     map {
+     *         key = timestamp
+     *         value = map {
+     *             key = histogram slot
+     *             value = count
+     *         }
+     *     }
+     * ]
+     * 
+ */ + @Override @Deprecated - public List selectCallerStatistics(Application callerApplication, Application calleeApplication, Range range) { - if (logger.isDebugEnabled()) { - logger.debug("selectCallerStatistics. {}, {}, {}", callerApplication, calleeApplication, range); - } - Scan scan = createScan(callerApplication, range); + public List selectCallerStatistics(Application callerApplication, Application calleeApplication, Range range) { + if (logger.isDebugEnabled()) { + logger.debug("selectCallerStatistics. {}, {}, {}", callerApplication, calleeApplication, range); + } + Scan scan = createScan(callerApplication, range); final LinkFilter filter = new DefaultLinkFilter(callerApplication, calleeApplication); RowMapper mapper = new MapStatisticsCallerMapper(filter); - return hbaseOperations2.find(HBaseTables.MAP_STATISTICS_CALLEE, scan, mapper); - } + return hbaseOperations2.find(HBaseTables.MAP_STATISTICS_CALLEE, scan, mapper); + } - private Scan createScan(Application application, Range range) { + private Scan createScan(Application application, Range range) { range = rangeFactory.createStatisticsRange(range); - if (logger.isDebugEnabled()) { - logger.debug("scan Time:{}", range.prettyToString()); - } + if (logger.isDebugEnabled()) { + logger.debug("scan Time:{}", range.prettyToString()); + } - // start key is replaced by end key because timestamp has been reversed - byte[] startKey = ApplicationMapStatisticsUtils.makeRowKey(application.getName(), application.getServiceTypeCode(), range.getTo()); - byte[] endKey = ApplicationMapStatisticsUtils.makeRowKey(application.getName(), application.getServiceTypeCode(), range.getFrom()); + // start key is replaced by end key because timestamp has been reversed + byte[] startKey = ApplicationMapStatisticsUtils.makeRowKey(application.getName(), application.getServiceTypeCode(), range.getTo()); + byte[] endKey = ApplicationMapStatisticsUtils.makeRowKey(application.getName(), application.getServiceTypeCode(), range.getFrom()); - Scan scan = new Scan(); - scan.setCaching(this.scanCacheSize); - scan.setStartRow(startKey); - scan.setStopRow(endKey); - scan.addFamily(HBaseTables.MAP_STATISTICS_CALLEE_CF_COUNTER); + Scan scan = new Scan(); + scan.setCaching(this.scanCacheSize); + scan.setStartRow(startKey); + scan.setStopRow(endKey); + scan.addFamily(HBaseTables.MAP_STATISTICS_CALLEE_CF_COUNTER); scan.addFamily(HBaseTables.MAP_STATISTICS_CALLEE_CF_VER2_COUNTER); - scan.setId("ApplicationStatisticsScan"); + scan.setId("ApplicationStatisticsScan"); - return scan; - } + return scan; + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDao.java index 47554a0dc..73528aa8f 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDao.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseTraceDao.java @@ -39,89 +39,89 @@ import org.springframework.stereotype.Repository; @Repository public class HbaseTraceDao implements TraceDao { - @Autowired - private HbaseOperations2 template2; + @Autowired + private HbaseOperations2 template2; @Autowired @Qualifier("traceDistributor") private AbstractRowKeyDistributor rowKeyDistributor; - @Autowired - @Qualifier("spanMapper") - private RowMapper> spanMapper; + @Autowired + @Qualifier("spanMapper") + private RowMapper> spanMapper; - @Autowired - @Qualifier("spanAnnotationMapper") - private RowMapper> spanAnnotationMapper; + @Autowired + @Qualifier("spanAnnotationMapper") + private RowMapper> spanAnnotationMapper; - @Override - public List selectSpan(TransactionId transactionId) { + @Override + public List selectSpan(TransactionId transactionId) { if (transactionId == null) { throw new NullPointerException("transactionId must not be null"); } byte[] traceIdBytes = rowKeyDistributor.getDistributedKey(transactionId.getBytes()); - return template2.get(HBaseTables.TRACES, traceIdBytes, HBaseTables.TRACES_CF_SPAN, spanMapper); - } + return template2.get(HBaseTables.TRACES, traceIdBytes, HBaseTables.TRACES_CF_SPAN, spanMapper); + } - public List selectSpanAndAnnotation(TransactionId transactionId) { + public List selectSpanAndAnnotation(TransactionId transactionId) { if (transactionId == null) { throw new NullPointerException("transactionId must not be null"); } final byte[] traceIdBytes = rowKeyDistributor.getDistributedKey(transactionId.getBytes()); - Get get = new Get(traceIdBytes); - get.addFamily(HBaseTables.TRACES_CF_SPAN); - get.addFamily(HBaseTables.TRACES_CF_ANNOTATION); - get.addFamily(HBaseTables.TRACES_CF_TERMINALSPAN); - return template2.get(HBaseTables.TRACES, get, spanAnnotationMapper); - } + Get get = new Get(traceIdBytes); + get.addFamily(HBaseTables.TRACES_CF_SPAN); + get.addFamily(HBaseTables.TRACES_CF_ANNOTATION); + get.addFamily(HBaseTables.TRACES_CF_TERMINALSPAN); + return template2.get(HBaseTables.TRACES, get, spanAnnotationMapper); + } - @Override - public List> selectSpans(List transactionIdList) { + @Override + public List> selectSpans(List transactionIdList) { if (transactionIdList == null) { throw new NullPointerException("transactionIdList must not be null"); } final List getList = new ArrayList(transactionIdList.size()); - for (TransactionId traceId : transactionIdList) { - final byte[] traceIdBytes = rowKeyDistributor.getDistributedKey(traceId.getBytes()); - final Get get = new Get(traceIdBytes); - get.addFamily(HBaseTables.TRACES_CF_SPAN); - getList.add(get); - } - return template2.get(HBaseTables.TRACES, getList, spanMapper); - } + for (TransactionId traceId : transactionIdList) { + final byte[] traceIdBytes = rowKeyDistributor.getDistributedKey(traceId.getBytes()); + final Get get = new Get(traceIdBytes); + get.addFamily(HBaseTables.TRACES_CF_SPAN); + getList.add(get); + } + return template2.get(HBaseTables.TRACES, getList, spanMapper); + } - @Override - public List> selectAllSpans(Collection transactionIdList) { + @Override + public List> selectAllSpans(Collection transactionIdList) { if (transactionIdList == null) { throw new NullPointerException("transactionIdList must not be null"); } final List gets = new ArrayList(transactionIdList.size()); - for (TransactionId transactionId : transactionIdList) { + for (TransactionId transactionId : transactionIdList) { final byte[] transactionIdBytes = this.rowKeyDistributor.getDistributedKey(transactionId.getBytes()); final Get get = new Get(transactionIdBytes); - get.addFamily(HBaseTables.TRACES_CF_SPAN); - get.addFamily(HBaseTables.TRACES_CF_TERMINALSPAN); - gets.add(get); - } - return template2.get(HBaseTables.TRACES, gets, spanMapper); - } + get.addFamily(HBaseTables.TRACES_CF_SPAN); + get.addFamily(HBaseTables.TRACES_CF_TERMINALSPAN); + gets.add(get); + } + return template2.get(HBaseTables.TRACES, gets, spanMapper); + } - @Override - public List selectSpans(TransactionId transactionId) { + @Override + public List selectSpans(TransactionId transactionId) { if (transactionId == null) { throw new NullPointerException("transactionId must not be null"); } final byte[] transactionIdBytes = this.rowKeyDistributor.getDistributedKey(transactionId.getBytes()); Get get = new Get(transactionIdBytes); - get.addFamily(HBaseTables.TRACES_CF_SPAN); - get.addFamily(HBaseTables.TRACES_CF_TERMINALSPAN); - return template2.get(HBaseTables.TRACES, get, spanMapper); - } + get.addFamily(HBaseTables.TRACES_CF_SPAN); + get.addFamily(HBaseTables.TRACES_CF_TERMINALSPAN); + return template2.get(HBaseTables.TRACES, get, spanMapper); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java index fd697268d..d0b41d226 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java @@ -38,85 +38,85 @@ import org.springframework.stereotype.Component; @Component public class DefaultFilterBuilder implements FilterBuilder { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private ObjectMapper jsonObjectMapper; + @Autowired + private ObjectMapper jsonObjectMapper; - @Override - public Filter build(String filterText) { - if (StringUtils.isEmpty(filterText)) { - return Filter.NONE; - } + @Override + public Filter build(String filterText) { + if (StringUtils.isEmpty(filterText)) { + return Filter.NONE; + } - try { - filterText = URLDecoder.decode(filterText, "UTF-8"); - logger.debug("build filter from string. {}", filterText); - } catch (Exception e) { - throw new IllegalArgumentException(filterText); - } - return makeFilterFromJson(filterText); - } + try { + filterText = URLDecoder.decode(filterText, "UTF-8"); + logger.debug("build filter from string. {}", filterText); + } catch (Exception e) { + throw new IllegalArgumentException(filterText); + } + return makeFilterFromJson(filterText); + } - @Override - public Filter build(String filterText, String filterHint) { - if (StringUtils.isEmpty(filterText)) { - return Filter.NONE; - } + @Override + public Filter build(String filterText, String filterHint) { + if (StringUtils.isEmpty(filterText)) { + return Filter.NONE; + } - try { - filterText = URLDecoder.decode(filterText, "UTF-8"); - logger.debug("build filter from string. {}", filterText); - } catch (Exception e) { - throw new IllegalArgumentException("invalid filter text. " + filterText); - } + try { + filterText = URLDecoder.decode(filterText, "UTF-8"); + logger.debug("build filter from string. {}", filterText); + } catch (Exception e) { + throw new IllegalArgumentException("invalid filter text. " + filterText); + } - if (!StringUtils.isEmpty(filterHint)) { - try { - filterHint = URLDecoder.decode(filterHint, "UTF-8"); - logger.debug("build filter hint from string. {}", filterHint); - } catch (Exception e) { - throw new IllegalArgumentException("invalid filter hint. " + filterHint); - } - } else { - filterHint = FilterHint.EMPTY_JSON; - } + if (!StringUtils.isEmpty(filterHint)) { + try { + filterHint = URLDecoder.decode(filterHint, "UTF-8"); + logger.debug("build filter hint from string. {}", filterHint); + } catch (Exception e) { + throw new IllegalArgumentException("invalid filter hint. " + filterHint); + } + } else { + filterHint = FilterHint.EMPTY_JSON; + } - return makeFilterFromJson(filterText, filterHint); - } + return makeFilterFromJson(filterText, filterHint); + } - private Filter makeFilterFromJson(String jsonFilterText) { - return makeFilterFromJson(jsonFilterText, FilterHint.EMPTY_JSON); - } + private Filter makeFilterFromJson(String jsonFilterText) { + return makeFilterFromJson(jsonFilterText, FilterHint.EMPTY_JSON); + } - private Filter makeFilterFromJson(String jsonFilterText, String jsonFilterHint) { - if (StringUtils.isEmpty(jsonFilterText)) { - throw new IllegalArgumentException("json string is empty"); - } - FilterChain chain = new FilterChain(); - try { - List list = jsonObjectMapper.readValue(jsonFilterText, new TypeReference>() { - }); + private Filter makeFilterFromJson(String jsonFilterText, String jsonFilterHint) { + if (StringUtils.isEmpty(jsonFilterText)) { + throw new IllegalArgumentException("json string is empty"); + } + FilterChain chain = new FilterChain(); + try { + List list = jsonObjectMapper.readValue(jsonFilterText, new TypeReference>() { + }); - FilterHint hint = jsonObjectMapper.readValue(jsonFilterHint, new TypeReference() { - }); - - for (FilterDescriptor descriptor : list) { - if (!descriptor.isValid()) { - throw new IllegalArgumentException("invalid json " + jsonFilterText); - } + FilterHint hint = jsonObjectMapper.readValue(jsonFilterHint, new TypeReference() { + }); - logger.debug("FilterDescriptor={}", descriptor); + for (FilterDescriptor descriptor : list) { + if (!descriptor.isValid()) { + throw new IllegalArgumentException("invalid json " + jsonFilterText); + } - chain.addFilter(new FromToResponseFilter(descriptor, hint)); + logger.debug("FilterDescriptor={}", descriptor); - if (descriptor.isSetUrl()) { - chain.addFilter(new URLPatternFilter(descriptor)); - } - } - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); - } - return chain.get(); - } + chain.addFilter(new FromToResponseFilter(descriptor, hint)); + + if (descriptor.isSetUrl()) { + chain.addFilter(new URLPatternFilter(descriptor)); + } + } + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); + } + return chain.get(); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/Filter.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/Filter.java index 613232502..701050244 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/filter/Filter.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/Filter.java @@ -27,12 +27,12 @@ import com.navercorp.pinpoint.common.bo.SpanBo; */ public interface Filter { - public static final Filter NONE = new Filter() { - @Override - public boolean include(List transaction) { - return true; - } - }; + public static final Filter NONE = new Filter() { + @Override + public boolean include(List transaction) { + return true; + } + }; - boolean include(List transaction); + boolean include(List transaction); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterBuilder.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterBuilder.java index 1c6c6bf77..f65459cf5 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterBuilder.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterBuilder.java @@ -21,7 +21,7 @@ package com.navercorp.pinpoint.web.filter; * @author netspider */ public interface FilterBuilder { - Filter build(String filterText); + Filter build(String filterText); - Filter build(String filterText, String filterHint); + Filter build(String filterText, String filterHint); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterChain.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterChain.java index 25481301b..5de377163 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterChain.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterChain.java @@ -28,41 +28,41 @@ import com.navercorp.pinpoint.common.bo.SpanBo; */ public class FilterChain implements Filter { - private final List filterList; + private final List filterList; - public FilterChain() { - filterList = new ArrayList(); - } + public FilterChain() { + filterList = new ArrayList(); + } - public void addFilter(Filter filter) { - filterList.add(filter); - } + public void addFilter(Filter filter) { + filterList.add(filter); + } - @Override - public boolean include(List transaction) { - // FIXME how to improve performance without "for loop" - for (Filter f : filterList) { - if (!f.include(transaction)) { - return false; - } - } - return true; - } - - public Filter get() { - if (filterList.size() == 1) { - return filterList.get(0); - } else { - return this; - } - } + @Override + public boolean include(List transaction) { + // FIXME how to improve performance without "for loop" + for (Filter f : filterList) { + if (!f.include(transaction)) { + return false; + } + } + return true; + } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < filterList.size(); i++, sb.append("
")) { - sb.append(filterList.get(i).toString()); - } - return sb.toString(); - } + public Filter get() { + if (filterList.size() == 1) { + return filterList.get(0); + } else { + return this; + } + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < filterList.size(); i++, sb.append("
")) { + sb.append(filterList.get(i).toString()); + } + return sb.toString(); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterDescriptor.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterDescriptor.java index d83b4034f..9b95b20a1 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterDescriptor.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterDescriptor.java @@ -25,200 +25,200 @@ import org.apache.commons.lang.StringUtils; */ public class FilterDescriptor { - /** - * from application name - */ - private String fa = null; - - /** - * from service type - */ - private String fst = null; - - /** - * to application name - */ - private String ta = null; - - /** - * to service type - */ - private String tst = null; - - /** - * response time from - */ - private Long rf = null; - - /** - * response time to - */ - private String rt = null; - - /** - * include exception - */ - private Boolean ie = null; - - /** - * requested url - */ - private String url = null; - - /** - * from agent name - */ - private String fan = null; - - /** - * to agent name - */ - private String tan = null; - - public boolean isValid() { - return isValidFromToInfo() && isValidFromToResponseTime(); - } + /** + * from application name + */ + private String fa = null; - public boolean isValidFromToInfo() { - return !(StringUtils.isEmpty(fa) || StringUtils.isEmpty(fst) || StringUtils.isEmpty(ta) || StringUtils.isEmpty(tst)); - } + /** + * from service type + */ + private String fst = null; - public boolean isValidFromToResponseTime() { - return !((rf == null && !StringUtils.isEmpty(rt)) || (rf != null && StringUtils.isEmpty(rt))); - } + /** + * to application name + */ + private String ta = null; - public boolean isSetUrl() { - return !StringUtils.isEmpty(url); - } + /** + * to service type + */ + private String tst = null; - public String getFromApplicationName() { - return fa; - } + /** + * response time from + */ + private Long rf = null; - public String getFromServiceType() { - return fst; - } + /** + * response time to + */ + private String rt = null; - public String getToApplicationName() { - return ta; - } + /** + * include exception + */ + private Boolean ie = null; - public String getToServiceType() { - return tst; - } + /** + * requested url + */ + private String url = null; - public Long getResponseFrom() { - return rf; - } + /** + * from agent name + */ + private String fan = null; - public Long getResponseTo() { - if (rt == null) { - return null; - } else if ("max".equals(rt)) { - return Long.MAX_VALUE; - } else { - return Long.valueOf(rt); - } - } + /** + * to agent name + */ + private String tan = null; - public Boolean getIncludeException() { - return ie; - } + public boolean isValid() { + return isValidFromToInfo() && isValidFromToResponseTime(); + } - public String getUrlPattern() { - return url; - } + public boolean isValidFromToInfo() { + return !(StringUtils.isEmpty(fa) || StringUtils.isEmpty(fst) || StringUtils.isEmpty(ta) || StringUtils.isEmpty(tst)); + } - public String getFa() { - return fa; - } + public boolean isValidFromToResponseTime() { + return !((rf == null && !StringUtils.isEmpty(rt)) || (rf != null && StringUtils.isEmpty(rt))); + } - public void setFa(String fa) { - this.fa = fa; - } + public boolean isSetUrl() { + return !StringUtils.isEmpty(url); + } - public String getFst() { - return fst; - } + public String getFromApplicationName() { + return fa; + } - public void setFst(String fst) { - this.fst = fst; - } + public String getFromServiceType() { + return fst; + } - public String getTa() { - return ta; - } + public String getToApplicationName() { + return ta; + } - public void setTa(String ta) { - this.ta = ta; - } + public String getToServiceType() { + return tst; + } - public String getTst() { - return tst; - } + public Long getResponseFrom() { + return rf; + } - public void setTst(String tst) { - this.tst = tst; - } + public Long getResponseTo() { + if (rt == null) { + return null; + } else if ("max".equals(rt)) { + return Long.MAX_VALUE; + } else { + return Long.valueOf(rt); + } + } - public Long getRf() { - return rf; - } + public Boolean getIncludeException() { + return ie; + } - public void setRf(Long rf) { - this.rf = rf; - } + public String getUrlPattern() { + return url; + } - public String getRt() { - return rt; - } + public String getFa() { + return fa; + } - public void setRt(String rt) { - this.rt = rt; - } + public void setFa(String fa) { + this.fa = fa; + } - public Boolean getIe() { - return ie; - } + public String getFst() { + return fst; + } - public void setIe(Boolean ie) { - this.ie = ie; - } + public void setFst(String fst) { + this.fst = fst; + } - public String getUrl() { - return url; - } + public String getTa() { + return ta; + } - public void setUrl(String url) { - this.url = url; - } + public void setTa(String ta) { + this.ta = ta; + } - public String getFan() { - return fan; - } - - public String getFromAgentName() { - return fan; - } + public String getTst() { + return tst; + } - public void setFan(String fan) { - this.fan = fan; - } + public void setTst(String tst) { + this.tst = tst; + } - public String getTan() { - return tan; - } - - public String getToAgentName() { - return tan; - } + public Long getRf() { + return rf; + } - public void setTan(String tan) { - this.tan = tan; - } - - @Override - public String toString() { - return "FilterDescriptor [fa=" + fa + ", fst=" + fst + ", ta=" + ta + ", tst=" + tst + ", rf=" + rf + ", rt=" + rt + ", ie=" + ie + ", url=" + url + ", fan=" + fan + ", tan=" + tan + "]"; - } + public void setRf(Long rf) { + this.rf = rf; + } + + public String getRt() { + return rt; + } + + public void setRt(String rt) { + this.rt = rt; + } + + public Boolean getIe() { + return ie; + } + + public void setIe(Boolean ie) { + this.ie = ie; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getFan() { + return fan; + } + + public String getFromAgentName() { + return fan; + } + + public void setFan(String fan) { + this.fan = fan; + } + + public String getTan() { + return tan; + } + + public String getToAgentName() { + return tan; + } + + public void setTan(String tan) { + this.tan = tan; + } + + @Override + public String toString() { + return "FilterDescriptor [fa=" + fa + ", fst=" + fst + ", ta=" + ta + ", tst=" + tst + ", rf=" + rf + ", rt=" + rt + ", ie=" + ie + ", url=" + url + ", fan=" + fan + ", tan=" + tan + "]"; + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java index 3171475d1..1da96e2f2 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java @@ -28,35 +28,35 @@ import java.util.List; // FIXME don't know how to implement deserializer like this. public class FilterHint extends HashMap> { - private static final long serialVersionUID = -8765645836014210889L; + private static final long serialVersionUID = -8765645836014210889L; - public static final String EMPTY_JSON = "{}"; + public static final String EMPTY_JSON = "{}"; - public boolean containApplicationHint(String applicationName) { - List list = get(applicationName); + public boolean containApplicationHint(String applicationName) { + List list = get(applicationName); - if (list == null) { - return false; - } else { - return !list.isEmpty(); - } - } + if (list == null) { + return false; + } else { + return !list.isEmpty(); + } + } - public boolean containApplicationEndpoint(String applicationName, String endPoint, int serviceTypeCode) { - if (!containApplicationHint(applicationName)) { - return false; - } + public boolean containApplicationEndpoint(String applicationName, String endPoint, int serviceTypeCode) { + if (!containApplicationHint(applicationName)) { + return false; + } - List list = get(applicationName); + List list = get(applicationName); - for (int i = 0; i < list.size(); i += 2) { - if (endPoint.equals(list.get(i))) { - if (serviceTypeCode == (Integer) list.get(i + 1)) { - return true; - } - } - } + for (int i = 0; i < list.size(); i += 2) { + if (endPoint.equals(list.get(i))) { + if (serviceTypeCode == (Integer) list.get(i + 1)) { + return true; + } + } + } - return false; - } + return false; + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/FromToFilter.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/FromToFilter.java index 45bb25b05..74c9f0c4d 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/filter/FromToFilter.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/FromToFilter.java @@ -29,13 +29,13 @@ import com.navercorp.pinpoint.common.bo.SpanEventBo; */ public class FromToFilter implements Filter { - // FIXME couldn't remember why from, to serviceCode should be List. just ServiceType may be okay. right? - private final List fromServiceCode; + // FIXME couldn't remember why from, to serviceCode should be List. just ServiceType may be okay. right? + private final List fromServiceCode; private final String fromApplicationName; private final List toServiceCode; private final String toApplicationName; - public FromToFilter(String fromServiceType, String fromApplicationName, String toServiceType, String toApplicationName) { + public FromToFilter(String fromServiceType, String fromApplicationName, String toServiceType, String toApplicationName) { if (fromApplicationName == null) { throw new NullPointerException("fromApplicationName must not be null"); } @@ -49,74 +49,74 @@ public class FromToFilter implements Filter { } this.fromApplicationName = fromApplicationName; - this.toServiceCode = ServiceType.findDesc(toServiceType); + this.toServiceCode = ServiceType.findDesc(toServiceType); if (toServiceCode == null) { throw new IllegalArgumentException("toServiceCode not found. toServiceCode:" + toServiceType); } - this.toApplicationName = toApplicationName; - } + this.toApplicationName = toApplicationName; + } - @Override - public boolean include(List transaction) { - if (includeServiceType(fromServiceCode, ServiceType.USER)) { - for (SpanBo span : transaction) { - if (span.isRoot() && includeServiceType(toServiceCode, span.getServiceType()) && toApplicationName.equals(span.getApplicationId())) { - return true; - } - } - } else if (includeUnknown(toServiceCode)) { - for (SpanBo span : transaction) { + @Override + public boolean include(List transaction) { + if (includeServiceType(fromServiceCode, ServiceType.USER)) { + for (SpanBo span : transaction) { + if (span.isRoot() && includeServiceType(toServiceCode, span.getServiceType()) && toApplicationName.equals(span.getApplicationId())) { + return true; + } + } + } else if (includeUnknown(toServiceCode)) { + for (SpanBo span : transaction) { if (includeServiceType(fromServiceCode, span.getServiceType()) && fromApplicationName.equals(span.getApplicationId())) { - List eventBoList = span.getSpanEventBoList(); - if (eventBoList == null) { - continue; - } - for (SpanEventBo event : eventBoList) { - // check only whether client exists or not - if (event.getServiceType().isRpcClient() && toApplicationName.equals(event.getDestinationId())) { - return true; - } - } - } - } - } else if (includeWas(toServiceCode)) { - /** - * if destination is a "WAS", the span of src and dest may exists. need to check if be circular or not. - * find src first. span (from, to) may exist more than one. so (spanId == parentSpanID) should be checked. - */ - for (SpanBo srcSpan : transaction) { - if (includeServiceType(fromServiceCode, srcSpan.getServiceType()) && fromApplicationName.equals(srcSpan.getApplicationId())) { - // find dest of src. - for (SpanBo destSpan : transaction) { - if (destSpan.getParentSpanId() != srcSpan.getSpanId()) { - continue; - } + List eventBoList = span.getSpanEventBoList(); + if (eventBoList == null) { + continue; + } + for (SpanEventBo event : eventBoList) { + // check only whether client exists or not + if (event.getServiceType().isRpcClient() && toApplicationName.equals(event.getDestinationId())) { + return true; + } + } + } + } + } else if (includeWas(toServiceCode)) { + /** + * if destination is a "WAS", the span of src and dest may exists. need to check if be circular or not. + * find src first. span (from, to) may exist more than one. so (spanId == parentSpanID) should be checked. + */ + for (SpanBo srcSpan : transaction) { + if (includeServiceType(fromServiceCode, srcSpan.getServiceType()) && fromApplicationName.equals(srcSpan.getApplicationId())) { + // find dest of src. + for (SpanBo destSpan : transaction) { + if (destSpan.getParentSpanId() != srcSpan.getSpanId()) { + continue; + } - if (includeServiceType(toServiceCode, destSpan.getServiceType()) && toApplicationName.equals(destSpan.getApplicationId())) { - return true; - } - } + if (includeServiceType(toServiceCode, destSpan.getServiceType()) && toApplicationName.equals(destSpan.getApplicationId())) { + return true; + } + } - } - } - } else { - for (SpanBo span : transaction) { - if (includeServiceType(fromServiceCode, span.getServiceType()) && fromApplicationName.equals(span.getApplicationId())) { - List eventBoList = span.getSpanEventBoList(); - if (eventBoList == null) { - continue; - } - for (SpanEventBo event : eventBoList) { - if (includeServiceType(toServiceCode, event.getServiceType()) && toApplicationName.equals(event.getDestinationId())) { - return true; - } - } - } - } - } + } + } + } else { + for (SpanBo span : transaction) { + if (includeServiceType(fromServiceCode, span.getServiceType()) && fromApplicationName.equals(span.getApplicationId())) { + List eventBoList = span.getSpanEventBoList(); + if (eventBoList == null) { + continue; + } + for (SpanEventBo event : eventBoList) { + if (includeServiceType(toServiceCode, event.getServiceType()) && toApplicationName.equals(event.getDestinationId())) { + return true; + } + } + } + } + } - return false; - } + return false; + } private boolean includeUnknown(List serviceTypeList) { @@ -146,11 +146,11 @@ public class FromToFilter implements Filter { } @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(fromApplicationName).append(" (").append(fromServiceCode).append(")"); - sb.append(" --> "); - sb.append(toApplicationName).append(" (").append(toServiceCode).append(")"); - return sb.toString(); - } + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(fromApplicationName).append(" (").append(fromServiceCode).append(")"); + sb.append(" --> "); + sb.append(toApplicationName).append(" (").append(toServiceCode).append(")"); + return sb.toString(); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/FromToResponseFilter.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/FromToResponseFilter.java index bc491581e..a8fd905f9 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/filter/FromToResponseFilter.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/FromToResponseFilter.java @@ -29,228 +29,228 @@ import com.navercorp.pinpoint.common.bo.SpanEventBo; */ public class FromToResponseFilter implements Filter { - private final List fromServiceCode; - private final String fromApplicationName; - private final String fromAgentName; - - private final List toServiceCode; - private final String toApplicationName; - private final String toAgentName; - - private final Long fromResponseTime; - private final Long toResponseTime; - private final Boolean includeFailed; - - private final FilterHint hint; + private final List fromServiceCode; + private final String fromApplicationName; + private final String fromAgentName; - public FromToResponseFilter(FilterDescriptor filterDescriptor, FilterHint hint) { - if (filterDescriptor == null) { - throw new NullPointerException("filter descriptor must not be null"); - } + private final List toServiceCode; + private final String toApplicationName; + private final String toAgentName; - String fromServiceType = filterDescriptor.getFromServiceType(); - String fromApplicationName = filterDescriptor.getFromApplicationName(); - String fromAgentName = filterDescriptor.getFromAgentName(); - String toServiceType = filterDescriptor.getToServiceType(); - String toApplicationName = filterDescriptor.getToApplicationName(); - String toAgentName = filterDescriptor.getToAgentName(); - Long fromResponseTime = filterDescriptor.getResponseFrom(); - Long toResponseTime = filterDescriptor.getResponseTo(); - Boolean includeFailed = filterDescriptor.getIncludeException(); + private final Long fromResponseTime; + private final Long toResponseTime; + private final Boolean includeFailed; - if (fromApplicationName == null) { - throw new NullPointerException("fromApplicationName must not be null"); - } - if (toApplicationName == null) { - throw new NullPointerException("toApplicationName must not be null"); - } + private final FilterHint hint; - this.fromServiceCode = ServiceType.findDesc(fromServiceType); - if (fromServiceCode == null) { - throw new IllegalArgumentException("fromServiceCode not found. fromServiceType:" + fromServiceType); - } - this.fromApplicationName = fromApplicationName; - this.fromAgentName = fromAgentName; - - this.toServiceCode = ServiceType.findDesc(toServiceType); - if (toServiceCode == null) { - throw new IllegalArgumentException("toServiceCode not found. toServiceCode:" + toServiceType); - } - this.toApplicationName = toApplicationName; - this.toAgentName = toAgentName; + public FromToResponseFilter(FilterDescriptor filterDescriptor, FilterHint hint) { + if (filterDescriptor == null) { + throw new NullPointerException("filter descriptor must not be null"); + } - this.fromResponseTime = fromResponseTime; - this.toResponseTime = toResponseTime; - this.includeFailed = includeFailed; - - if (hint == null) { - throw new NullPointerException("hint must not be null"); - } - this.hint = hint; - } + String fromServiceType = filterDescriptor.getFromServiceType(); + String fromApplicationName = filterDescriptor.getFromApplicationName(); + String fromAgentName = filterDescriptor.getFromAgentName(); + String toServiceType = filterDescriptor.getToServiceType(); + String toApplicationName = filterDescriptor.getToApplicationName(); + String toAgentName = filterDescriptor.getToAgentName(); + Long fromResponseTime = filterDescriptor.getResponseFrom(); + Long toResponseTime = filterDescriptor.getResponseTo(); + Boolean includeFailed = filterDescriptor.getIncludeException(); - private boolean checkResponseCondition(long elapsed, boolean hasError) { - boolean result = true; - if (fromResponseTime != null && toResponseTime != null) { - result &= (elapsed >= fromResponseTime) && (elapsed <= toResponseTime); - } - if (includeFailed != null) { - if (includeFailed) { - result &= hasError; - } else { - result &= !hasError; - } - } - return result; - } - - private boolean checkPinPointAgentName(String fromAgentName, String toAgentName) { - if (this.fromAgentName == null && this.toAgentName == null) { - return true; - } - - boolean result = true; - - if (this.fromAgentName != null) { - result &= this.fromAgentName.equals(fromAgentName); - } - - if (this.toAgentName != null) { - result &= this.toAgentName.equals(toAgentName); - } - - return result; - } - - @Override - public boolean include(List transaction) { - if (includeServiceType(fromServiceCode, ServiceType.USER)) { - /** - * USER -> WAS - */ - for (SpanBo span : transaction) { - if (span.isRoot() && includeServiceType(toServiceCode, span.getServiceType()) && toApplicationName.equals(span.getApplicationId())) { - return checkResponseCondition(span.getElapsed(), span.getErrCode() > 0) - && checkPinPointAgentName(null, span.getAgentId()); - } - } - } else if (includeUnknown(toServiceCode)) { - /** - * WAS -> UNKNOWN - */ - for (SpanBo span : transaction) { - if (includeServiceType(fromServiceCode, span.getServiceType()) && fromApplicationName.equals(span.getApplicationId())) { - List eventBoList = span.getSpanEventBoList(); - if (eventBoList == null) { - continue; - } - - for (SpanEventBo event : eventBoList) { - // check only whether a client exists or not. - if (event.getServiceType().isRpcClient() && toApplicationName.equals(event.getDestinationId())) { - return checkResponseCondition(event.getEndElapsed(), event.hasException()); - } - } - } - } - } else if (includeWas(toServiceCode)) { - /** - * WAS -> WAS - * if destination is a "WAS", the span of src and dest may exists. need to check if be circular or not. - * find src first. span (from, to) may exist more than one. so (spanId == parentSpanID) should be checked. - */ - if (hint.containApplicationHint(toApplicationName)) { - for (SpanBo srcSpan : transaction) { - List eventBoList = srcSpan.getSpanEventBoList(); - if (eventBoList == null) { - continue; - } - for (SpanEventBo event : eventBoList) { - if (!event.getServiceType().isRpcClient()) { - continue; - } - - if (!hint.containApplicationEndpoint(toApplicationName, event.getDestinationId(), event.getServiceType().getCode())) { - continue; - } + if (fromApplicationName == null) { + throw new NullPointerException("fromApplicationName must not be null"); + } + if (toApplicationName == null) { + throw new NullPointerException("toApplicationName must not be null"); + } - return checkResponseCondition(event.getEndElapsed(), event.hasException()); - - // FIXME below code should be added for agent filter to work properly - // && checkPinPointAgentName(srcSpan.getAgentId(), destSpan.getAgentId()); - } - } - } else { - /** - * codes before hint has been added. - * if problems happen because of hint, don't use hint at front end (UI) or use below code in order to work properly. - */ - for (SpanBo srcSpan : transaction) { - if (includeServiceType(fromServiceCode, srcSpan.getServiceType()) && fromApplicationName.equals(srcSpan.getApplicationId())) { - // find dest of src. - for (SpanBo destSpan : transaction) { - if (destSpan.getParentSpanId() != srcSpan.getSpanId()) { - continue; - } + this.fromServiceCode = ServiceType.findDesc(fromServiceType); + if (fromServiceCode == null) { + throw new IllegalArgumentException("fromServiceCode not found. fromServiceType:" + fromServiceType); + } + this.fromApplicationName = fromApplicationName; + this.fromAgentName = fromAgentName; - if (includeServiceType(toServiceCode, destSpan.getServiceType()) && toApplicationName.equals(destSpan.getApplicationId())) { - return checkResponseCondition(destSpan.getElapsed(), destSpan.getErrCode() > 0) && checkPinPointAgentName(srcSpan.getAgentId(), destSpan.getAgentId()); - } - } - } - } - } - } else { - /** - * WAS -> BACKEND (non-WAS) - */ - for (SpanBo span : transaction) { - if (includeServiceType(fromServiceCode, span.getServiceType()) && fromApplicationName.equals(span.getApplicationId())) { - List eventBoList = span.getSpanEventBoList(); - if (eventBoList == null) { - continue; - } - for (SpanEventBo event : eventBoList) { - if (includeServiceType(toServiceCode, event.getServiceType()) && toApplicationName.equals(event.getDestinationId())) { - return checkResponseCondition(event.getEndElapsed(), event.hasException()) - && checkPinPointAgentName(span.getAgentId(), null); - } - } - } - } - } - return false; - } + this.toServiceCode = ServiceType.findDesc(toServiceType); + if (toServiceCode == null) { + throw new IllegalArgumentException("toServiceCode not found. toServiceCode:" + toServiceType); + } + this.toApplicationName = toApplicationName; + this.toAgentName = toAgentName; - private boolean includeUnknown(List serviceTypeList) { - for (ServiceType serviceType : serviceTypeList) { - if (serviceType.isUnknown()) { - return true; - } - } - return false; - } + this.fromResponseTime = fromResponseTime; + this.toResponseTime = toResponseTime; + this.includeFailed = includeFailed; - private boolean includeWas(List serviceTypeList) { - for (ServiceType serviceType : serviceTypeList) { - if (serviceType.isWas()) { - return true; - } - } - return false; - } + if (hint == null) { + throw new NullPointerException("hint must not be null"); + } + this.hint = hint; + } - private boolean includeServiceType(List serviceTypeList, ServiceType targetServiceType) { - for (ServiceType serviceType : serviceTypeList) { - if (serviceType == targetServiceType) { - return true; - } - } - return false; - } + private boolean checkResponseCondition(long elapsed, boolean hasError) { + boolean result = true; + if (fromResponseTime != null && toResponseTime != null) { + result &= (elapsed >= fromResponseTime) && (elapsed <= toResponseTime); + } + if (includeFailed != null) { + if (includeFailed) { + result &= hasError; + } else { + result &= !hasError; + } + } + return result; + } - @Override - public String toString() { - return "FromToResponseFilter [fromServiceCode=" + fromServiceCode + ", fromApplicationName=" + fromApplicationName + ", fromAgentName=" + fromAgentName + ", toServiceCode=" + toServiceCode + ", toApplicationName=" + toApplicationName + ", toAgentName=" + toAgentName + ", fromResponseTime=" + fromResponseTime + ", toResponseTime=" + toResponseTime + ", includeFailed=" + includeFailed + "]"; - } + private boolean checkPinPointAgentName(String fromAgentName, String toAgentName) { + if (this.fromAgentName == null && this.toAgentName == null) { + return true; + } + + boolean result = true; + + if (this.fromAgentName != null) { + result &= this.fromAgentName.equals(fromAgentName); + } + + if (this.toAgentName != null) { + result &= this.toAgentName.equals(toAgentName); + } + + return result; + } + + @Override + public boolean include(List transaction) { + if (includeServiceType(fromServiceCode, ServiceType.USER)) { + /** + * USER -> WAS + */ + for (SpanBo span : transaction) { + if (span.isRoot() && includeServiceType(toServiceCode, span.getServiceType()) && toApplicationName.equals(span.getApplicationId())) { + return checkResponseCondition(span.getElapsed(), span.getErrCode() > 0) + && checkPinPointAgentName(null, span.getAgentId()); + } + } + } else if (includeUnknown(toServiceCode)) { + /** + * WAS -> UNKNOWN + */ + for (SpanBo span : transaction) { + if (includeServiceType(fromServiceCode, span.getServiceType()) && fromApplicationName.equals(span.getApplicationId())) { + List eventBoList = span.getSpanEventBoList(); + if (eventBoList == null) { + continue; + } + + for (SpanEventBo event : eventBoList) { + // check only whether a client exists or not. + if (event.getServiceType().isRpcClient() && toApplicationName.equals(event.getDestinationId())) { + return checkResponseCondition(event.getEndElapsed(), event.hasException()); + } + } + } + } + } else if (includeWas(toServiceCode)) { + /** + * WAS -> WAS + * if destination is a "WAS", the span of src and dest may exists. need to check if be circular or not. + * find src first. span (from, to) may exist more than one. so (spanId == parentSpanID) should be checked. + */ + if (hint.containApplicationHint(toApplicationName)) { + for (SpanBo srcSpan : transaction) { + List eventBoList = srcSpan.getSpanEventBoList(); + if (eventBoList == null) { + continue; + } + for (SpanEventBo event : eventBoList) { + if (!event.getServiceType().isRpcClient()) { + continue; + } + + if (!hint.containApplicationEndpoint(toApplicationName, event.getDestinationId(), event.getServiceType().getCode())) { + continue; + } + + return checkResponseCondition(event.getEndElapsed(), event.hasException()); + + // FIXME below code should be added for agent filter to work properly + // && checkPinPointAgentName(srcSpan.getAgentId(), destSpan.getAgentId()); + } + } + } else { + /** + * codes before hint has been added. + * if problems happen because of hint, don't use hint at front end (UI) or use below code in order to work properly. + */ + for (SpanBo srcSpan : transaction) { + if (includeServiceType(fromServiceCode, srcSpan.getServiceType()) && fromApplicationName.equals(srcSpan.getApplicationId())) { + // find dest of src. + for (SpanBo destSpan : transaction) { + if (destSpan.getParentSpanId() != srcSpan.getSpanId()) { + continue; + } + + if (includeServiceType(toServiceCode, destSpan.getServiceType()) && toApplicationName.equals(destSpan.getApplicationId())) { + return checkResponseCondition(destSpan.getElapsed(), destSpan.getErrCode() > 0) && checkPinPointAgentName(srcSpan.getAgentId(), destSpan.getAgentId()); + } + } + } + } + } + } else { + /** + * WAS -> BACKEND (non-WAS) + */ + for (SpanBo span : transaction) { + if (includeServiceType(fromServiceCode, span.getServiceType()) && fromApplicationName.equals(span.getApplicationId())) { + List eventBoList = span.getSpanEventBoList(); + if (eventBoList == null) { + continue; + } + for (SpanEventBo event : eventBoList) { + if (includeServiceType(toServiceCode, event.getServiceType()) && toApplicationName.equals(event.getDestinationId())) { + return checkResponseCondition(event.getEndElapsed(), event.hasException()) + && checkPinPointAgentName(span.getAgentId(), null); + } + } + } + } + } + return false; + } + + private boolean includeUnknown(List serviceTypeList) { + for (ServiceType serviceType : serviceTypeList) { + if (serviceType.isUnknown()) { + return true; + } + } + return false; + } + + private boolean includeWas(List serviceTypeList) { + for (ServiceType serviceType : serviceTypeList) { + if (serviceType.isWas()) { + return true; + } + } + return false; + } + + private boolean includeServiceType(List serviceTypeList, ServiceType targetServiceType) { + for (ServiceType serviceType : serviceTypeList) { + if (serviceType == targetServiceType) { + return true; + } + } + return false; + } + + @Override + public String toString() { + return "FromToResponseFilter [fromServiceCode=" + fromServiceCode + ", fromApplicationName=" + fromApplicationName + ", fromAgentName=" + fromAgentName + ", toServiceCode=" + toServiceCode + ", toApplicationName=" + toApplicationName + ", toAgentName=" + toAgentName + ", fromResponseTime=" + fromResponseTime + ", toResponseTime=" + toResponseTime + ", includeFailed=" + includeFailed + "]"; + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/URLPatternFilter.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/URLPatternFilter.java index 191ee995d..84f9e4a52 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/filter/URLPatternFilter.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/URLPatternFilter.java @@ -32,39 +32,39 @@ import com.navercorp.pinpoint.common.bo.SpanBo; */ public class URLPatternFilter implements Filter { - private final String urlPattern; - private final Filter fromToFilter; - private final AntPathMatcher matcher = new AntPathMatcher(); + private final String urlPattern; + private final Filter fromToFilter; + private final AntPathMatcher matcher = new AntPathMatcher(); - public URLPatternFilter(FilterDescriptor filterDescriptor) { - this(filterDescriptor.getFromServiceType(), filterDescriptor.getFromApplicationName(), filterDescriptor.getToServiceType(), filterDescriptor.getToApplicationName(), filterDescriptor.getUrlPattern()); - } - - public URLPatternFilter(String fromServiceType, String fromApplicationName, String toServiceType, String toApplicationName, String urlPattern) { - this.fromToFilter = new FromToFilter(fromServiceType, fromApplicationName, toServiceType, toApplicationName); - this.urlPattern = new String(Base64.decodeBase64(urlPattern), Charset.forName("UTF-8")); - } + public URLPatternFilter(FilterDescriptor filterDescriptor) { + this(filterDescriptor.getFromServiceType(), filterDescriptor.getFromApplicationName(), filterDescriptor.getToServiceType(), filterDescriptor.getToApplicationName(), filterDescriptor.getUrlPattern()); + } - @Override - public boolean include(List transaction) { - if (fromToFilter.include(transaction)) { - for (SpanBo span : transaction) { - if (span.isRoot() && match(span.getRpc())) { - return true; - } - } - } - return false; - } + public URLPatternFilter(String fromServiceType, String fromApplicationName, String toServiceType, String toApplicationName, String urlPattern) { + this.fromToFilter = new FromToFilter(fromServiceType, fromApplicationName, toServiceType, toApplicationName); + this.urlPattern = new String(Base64.decodeBase64(urlPattern), Charset.forName("UTF-8")); + } - private boolean match(String url) { - return matcher.match(urlPattern, url); - } + @Override + public boolean include(List transaction) { + if (fromToFilter.include(transaction)) { + for (SpanBo span : transaction) { + if (span.isRoot() && match(span.getRpc())) { + return true; + } + } + } + return false; + } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("urlfilter=").append(urlPattern); - return sb.toString(); - } + private boolean match(String url) { + return matcher.match(urlPattern, url); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("urlfilter=").append(urlPattern); + return sb.toString(); + } } \ No newline at end of file diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/AgentIdMapper.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/AgentIdMapper.java index aa5a1b882..db799f37a 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/AgentIdMapper.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/AgentIdMapper.java @@ -32,19 +32,19 @@ import java.util.List; @Component public class AgentIdMapper implements RowMapper> { - @Override - public List mapRow(Result result, int rowNum) throws Exception { + @Override + public List mapRow(Result result, int rowNum) throws Exception { if (result.isEmpty()) { return Collections.emptyList(); } - final KeyValue[] raw = result.raw(); - final List agentIdList = new ArrayList(raw.length); + final KeyValue[] raw = result.raw(); + final List agentIdList = new ArrayList(raw.length); - for (KeyValue kv : raw) { + for (KeyValue kv : raw) { final String agentId = Bytes.toString(kv.getQualifier()); agentIdList.add(agentId); - } + } - return agentIdList; - } + return agentIdList; + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/ApplicationNameMapper.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/ApplicationNameMapper.java index a6857b2d1..186e061e0 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/ApplicationNameMapper.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/ApplicationNameMapper.java @@ -28,13 +28,13 @@ import com.navercorp.pinpoint.web.vo.Application; */ @Component public class ApplicationNameMapper implements RowMapper { - @Override - public Application mapRow(Result result, int rowNum) throws Exception { + @Override + public Application mapRow(Result result, int rowNum) throws Exception { if (result.isEmpty()) { return null; } - String applicationName = Bytes.toString(result.getRow()); - short serviceType = Bytes.toShort(result.value()); - return new Application(applicationName, serviceType); - } + String applicationName = Bytes.toString(result.getRow()); + short serviceType = Bytes.toShort(result.value()); + return new Application(applicationName, serviceType); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/HostApplicationMapper.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/HostApplicationMapper.java index 6adcdd575..eaaf27f5a 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/HostApplicationMapper.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/HostApplicationMapper.java @@ -36,22 +36,22 @@ import com.navercorp.pinpoint.web.vo.Application; @Component public class HostApplicationMapper implements RowMapper { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Override - public Application mapRow(Result result, int rowNum) throws Exception { + @Override + public Application mapRow(Result result, int rowNum) throws Exception { if (result.isEmpty()) { return null; } - byte[] value = result.value(); + byte[] value = result.value(); - if (value.length != HBaseTables.APPLICATION_NAME_MAX_LEN + 2) { - logger.warn("Invalid value. {}", Arrays.toString(value)); - } + if (value.length != HBaseTables.APPLICATION_NAME_MAX_LEN + 2) { + logger.warn("Invalid value. {}", Arrays.toString(value)); + } - String applicationName = Bytes.toString(value, 0, HBaseTables.APPLICATION_NAME_MAX_LEN - 1).trim(); - short serviceType = Bytes.toShort(value, HBaseTables.APPLICATION_NAME_MAX_LEN); + String applicationName = Bytes.toString(value, 0, HBaseTables.APPLICATION_NAME_MAX_LEN - 1).trim(); + short serviceType = Bytes.toShort(value, HBaseTables.APPLICATION_NAME_MAX_LEN); - return new Application(applicationName, serviceType); - } + return new Application(applicationName, serviceType); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/HostApplicationMapperVer2.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/HostApplicationMapperVer2.java index 8aa2bb586..b1cc8350c 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/HostApplicationMapperVer2.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/HostApplicationMapperVer2.java @@ -39,10 +39,10 @@ import java.util.List; @Component public class HostApplicationMapperVer2 implements RowMapper> { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Override - public List mapRow(Result result, int rowNum) throws Exception { + @Override + public List mapRow(Result result, int rowNum) throws Exception { if (result.isEmpty()) { return Collections.emptyList(); } @@ -53,8 +53,8 @@ public class HostApplicationMapperVer2 implements RowMapper { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final LinkFilter filter; @@ -55,7 +55,7 @@ public class MapStatisticsCalleeMapper implements RowMapper { } @Override - public LinkDataMap mapRow(Result result, int rowNum) throws Exception { + public LinkDataMap mapRow(Result result, int rowNum) throws Exception { if (result.isEmpty()) { return new LinkDataMap(); } @@ -67,7 +67,7 @@ public class MapStatisticsCalleeMapper implements RowMapper { final LinkDataMap linkDataMap = new LinkDataMap(); - for (KeyValue kv : result.raw()) { + for (KeyValue kv : result.raw()) { final byte[] qualifier = kv.getQualifier(); final Application callerApplication = readCallerApplication(qualifier); @@ -92,10 +92,10 @@ public class MapStatisticsCalleeMapper implements RowMapper { if (logger.isDebugEnabled()) { logger.debug(" Fetched Callee. statistics:{}", linkDataMap); } - } + } return linkDataMap; - } + } private Application readCallerApplication(byte[] qualifier) { String callerApplicationName = ApplicationMapStatisticsUtils.getDestApplicationNameFromColumnName(qualifier); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/MapStatisticsCallerMapper.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/MapStatisticsCallerMapper.java index b745e13cd..6190b5ad7 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/MapStatisticsCallerMapper.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/MapStatisticsCallerMapper.java @@ -45,7 +45,7 @@ import org.springframework.stereotype.Component; @Component public class MapStatisticsCallerMapper implements RowMapper { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final LinkFilter filter; @@ -61,7 +61,7 @@ public class MapStatisticsCallerMapper implements RowMapper { } @Override - public LinkDataMap mapRow(Result result, int rowNum) throws Exception { + public LinkDataMap mapRow(Result result, int rowNum) throws Exception { if (result.isEmpty()) { return new LinkDataMap(); } @@ -71,7 +71,7 @@ public class MapStatisticsCallerMapper implements RowMapper { final Application caller = readCallerApplication(row); final long timestamp = TimeUtils.recoveryTimeMillis(row.readLong()); - // key is destApplicationName. + // key is destApplicationName. final LinkDataMap linkDataMap = new LinkDataMap(); for (KeyValue kv : result.raw()) { final byte[] family = kv.getFamily(); @@ -129,10 +129,10 @@ public class MapStatisticsCallerMapper implements RowMapper { throw new IllegalArgumentException("unknown ColumnFamily :" + Arrays.toString(family)); } - } + } return linkDataMap; - } + } private long getValueToLong(KeyValue kv) { return Bytes.toLong(kv.getBuffer(), kv.getValueOffset()); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/TraceIndexScatterMapper.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/TraceIndexScatterMapper.java index 32a07e7ae..cb7adefde 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/TraceIndexScatterMapper.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/TraceIndexScatterMapper.java @@ -40,21 +40,21 @@ import org.springframework.stereotype.Component; @Component public class TraceIndexScatterMapper implements RowMapper> { - @Override - public List mapRow(Result result, int rowNum) throws Exception { + @Override + public List mapRow(Result result, int rowNum) throws Exception { if (result.isEmpty()) { return Collections.emptyList(); } - KeyValue[] raw = result.raw(); - List list = new ArrayList(raw.length); - for (KeyValue kv : raw) { + KeyValue[] raw = result.raw(); + List list = new ArrayList(raw.length); + for (KeyValue kv : raw) { final Dot dot = createDot(kv); list.add(dot); - } + } - return list; - } + return list; + } private Dot createDot(KeyValue kv) { final byte[] buffer = kv.getBuffer(); @@ -70,10 +70,10 @@ public class TraceIndexScatterMapper implements RowMapper> { final int qualifierOffset = kv.getQualifierOffset(); - // TransactionId transactionId = new TransactionId(buffer, qualifierOffset); + // TransactionId transactionId = new TransactionId(buffer, qualifierOffset); // for temporary, used TransactionIdMapper - TransactionId transactionId = TransactionIdMapper.parseVarTransactionId(buffer, qualifierOffset); + TransactionId transactionId = TransactionIdMapper.parseVarTransactionId(buffer, qualifierOffset); return new Dot(transactionId, acceptedTime, elapsed, exceptionCode, agentId); } @@ -85,8 +85,8 @@ public class TraceIndexScatterMapper implements RowMapper> { } final Buffer buffer = new OffsetFixedBuffer(bytes, offset); - buffer.readInt(); - + buffer.readInt(); + String agentId = buffer.readPrefixedString(); long agentStartTime = buffer.readSVarLong(); long transactionSequence = buffer.readVarLong(); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/TraceIndexScatterMapper2.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/TraceIndexScatterMapper2.java index f48b1c89b..b94cfb60b 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/TraceIndexScatterMapper2.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/TraceIndexScatterMapper2.java @@ -37,57 +37,57 @@ import com.navercorp.pinpoint.web.vo.scatter.Dot; */ public class TraceIndexScatterMapper2 implements RowMapper> { - private final int responseOffsetFrom; - private final int responseOffsetTo; + private final int responseOffsetFrom; + private final int responseOffsetTo; - public TraceIndexScatterMapper2(int responseOffsetFrom, int responseOffsetTo) { - this.responseOffsetFrom = responseOffsetFrom; - this.responseOffsetTo = responseOffsetTo; - } + public TraceIndexScatterMapper2(int responseOffsetFrom, int responseOffsetTo) { + this.responseOffsetFrom = responseOffsetFrom; + this.responseOffsetTo = responseOffsetTo; + } - @Override - public List mapRow(Result result, int rowNum) throws Exception { - if (result.isEmpty()) { - return Collections.emptyList(); - } + @Override + public List mapRow(Result result, int rowNum) throws Exception { + if (result.isEmpty()) { + return Collections.emptyList(); + } - KeyValue[] raw = result.raw(); - List list = new ArrayList(raw.length); - for (KeyValue kv : raw) { - final Dot dot = createDot(kv); - if (dot != null) { - list.add(dot); - } - } + KeyValue[] raw = result.raw(); + List list = new ArrayList(raw.length); + for (KeyValue kv : raw) { + final Dot dot = createDot(kv); + if (dot != null) { + list.add(dot); + } + } - return list; - } + return list; + } - private Dot createDot(KeyValue kv) { - final byte[] buffer = kv.getBuffer(); + private Dot createDot(KeyValue kv) { + final byte[] buffer = kv.getBuffer(); - final int valueOffset = kv.getValueOffset(); - final Buffer valueBuffer = new OffsetFixedBuffer(buffer, valueOffset); - int elapsed = valueBuffer.readVarInt(); + final int valueOffset = kv.getValueOffset(); + final Buffer valueBuffer = new OffsetFixedBuffer(buffer, valueOffset); + int elapsed = valueBuffer.readVarInt(); - if (elapsed < responseOffsetFrom || elapsed > responseOffsetTo) { - return null; - } + if (elapsed < responseOffsetFrom || elapsed > responseOffsetTo) { + return null; + } - int exceptionCode = valueBuffer.readSVarInt(); - String agentId = valueBuffer.readPrefixedString(); + int exceptionCode = valueBuffer.readSVarInt(); + String agentId = valueBuffer.readPrefixedString(); - long reverseAcceptedTime = BytesUtils.bytesToLong(buffer, kv.getRowOffset() + HBaseTables.APPLICATION_NAME_MAX_LEN + HBaseTables.APPLICATION_TRACE_INDEX_ROW_DISTRIBUTE_SIZE); - long acceptedTime = TimeUtils.recoveryTimeMillis(reverseAcceptedTime); + long reverseAcceptedTime = BytesUtils.bytesToLong(buffer, kv.getRowOffset() + HBaseTables.APPLICATION_NAME_MAX_LEN + HBaseTables.APPLICATION_TRACE_INDEX_ROW_DISTRIBUTE_SIZE); + long acceptedTime = TimeUtils.recoveryTimeMillis(reverseAcceptedTime); - final int qualifierOffset = kv.getQualifierOffset(); + final int qualifierOffset = kv.getQualifierOffset(); - // TransactionId transactionId = new TransactionId(buffer, - // qualifierOffset); + // TransactionId transactionId = new TransactionId(buffer, + // qualifierOffset); - // for temporary, used TransactionIdMapper - TransactionId transactionId = TransactionIdMapper.parseVarTransactionId(buffer, qualifierOffset); + // for temporary, used TransactionIdMapper + TransactionId transactionId = TransactionIdMapper.parseVarTransactionId(buffer, qualifierOffset); - return new Dot(transactionId, acceptedTime, elapsed, exceptionCode, agentId); - } + return new Dot(transactionId, acceptedTime, elapsed, exceptionCode, agentId); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/TransactionIdMapper.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/TransactionIdMapper.java index a5e4f8ebf..16b8ba16d 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/TransactionIdMapper.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/TransactionIdMapper.java @@ -38,39 +38,39 @@ import org.springframework.stereotype.Component; @Component public class TransactionIdMapper implements RowMapper> { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - // @Autowired - // private AbstractRowKeyDistributor rowKeyDistributor; + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + // @Autowired + // private AbstractRowKeyDistributor rowKeyDistributor; + + @Override + public List mapRow(Result result, int rowNum) throws Exception { + if (result.isEmpty()) { + return Collections.emptyList(); + } + KeyValue[] raw = result.raw(); + List traceIdList = new ArrayList(raw.length); + for (KeyValue kv : raw) { + byte[] buffer = kv.getBuffer(); + int qualifierOffset = kv.getQualifierOffset(); + // increment by value of key + TransactionId traceId = parseVarTransactionId(buffer, qualifierOffset); + traceIdList.add(traceId); + + logger.debug("found traceId {}", traceId); + } + return traceIdList; + } - @Override - public List mapRow(Result result, int rowNum) throws Exception { - if (result.isEmpty()) { - return Collections.emptyList(); - } - KeyValue[] raw = result.raw(); - List traceIdList = new ArrayList(raw.length); - for (KeyValue kv : raw) { - byte[] buffer = kv.getBuffer(); - int qualifierOffset = kv.getQualifierOffset(); - // increment by value of key - TransactionId traceId = parseVarTransactionId(buffer, qualifierOffset); - traceIdList.add(traceId); - - logger.debug("found traceId {}", traceId); - } - return traceIdList; - } - public static TransactionId parseVarTransactionId(byte[] bytes, int offset) { if (bytes == null) { throw new NullPointerException("bytes must not be null"); } final Buffer buffer = new OffsetFixedBuffer(bytes, offset); - // skip elapsed time (not used) hbase column prefix - only used for filtering. + // skip elapsed time (not used) hbase column prefix - only used for filtering. // Not sure if we can reduce the data size any further. - // buffer.readInt(); + // buffer.readInt(); String agentId = buffer.readPrefixedString(); long agentStartTime = buffer.readSVarLong(); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/server/PinpointSocketManager.java b/web/src/main/java/com/navercorp/pinpoint/web/server/PinpointSocketManager.java index 0964cf2ac..c3b100b3b 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/server/PinpointSocketManager.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/server/PinpointSocketManager.java @@ -48,145 +48,145 @@ import com.navercorp.pinpoint.web.config.WebConfig; */ public class PinpointSocketManager { - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - private final Charset charset = Charset.forName("UTF-8"); + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + private final Charset charset = Charset.forName("UTF-8"); - // local ip - // @Value("#{pinpointWebProps['web.tcpListenI']}") - private String representationLocalIp; - private List localIpList; + // local ip + // @Value("#{pinpointWebProps['web.tcpListenI']}") + private String representationLocalIp; + private List localIpList; - private WebConfig config; + private WebConfig config; - private final PinpointServerSocket pinpointServerSocket; + private final PinpointServerSocket pinpointServerSocket; - private ClusterManager clusterManager; + private ClusterManager clusterManager; - public PinpointSocketManager(WebConfig config) { - this.config = config; - this.pinpointServerSocket = new PinpointServerSocket(); - } + public PinpointSocketManager(WebConfig config) { + this.config = config; + this.pinpointServerSocket = new PinpointServerSocket(); + } - @PostConstruct - public void start() throws KeeperException, IOException, InterruptedException { - logger.info("{} enable {}.", this.getClass().getSimpleName(), config.isClusterEnable()); - if (config.isClusterEnable()) { - this.representationLocalIp = getRepresentationLocalV4Ip(); - this.localIpList = NetUtils.getLocalV4IpList(); + @PostConstruct + public void start() throws KeeperException, IOException, InterruptedException { + logger.info("{} enable {}.", this.getClass().getSimpleName(), config.isClusterEnable()); + if (config.isClusterEnable()) { + this.representationLocalIp = getRepresentationLocalV4Ip(); + this.localIpList = NetUtils.getLocalV4IpList(); - logger.info("Representation_Ip = {}, Ip_List = {}", representationLocalIp, localIpList); - - // TODO might be better to make it configurable whether to keep the process alive or to kill - if (representationLocalIp.equals(NetUtils.LOOPBACK_ADDRESS_V4) || localIpList.size() == 0) { - throw new SocketException("Can't find Local Ip."); - } - - String nodeName = representationLocalIp + ":" + config.getClusterTcpPort(); - if (!NetUtils.validationIpPortV4FormatAddress(nodeName)) { - throw new SocketException("Unexpected LocalAddress. LocalAddress format must be ip:port (" + nodeName + ")."); - } + logger.info("Representation_Ip = {}, Ip_List = {}", representationLocalIp, localIpList); - this.pinpointServerSocket.setMessageListener(new PinpointSocketManagerHandler()); - this.pinpointServerSocket.bind(representationLocalIp, config.getClusterTcpPort()); + // TODO might be better to make it configurable whether to keep the process alive or to kill + if (representationLocalIp.equals(NetUtils.LOOPBACK_ADDRESS_V4) || localIpList.size() == 0) { + throw new SocketException("Can't find Local Ip."); + } - this.clusterManager = new ZookeeperClusterManager(config.getClusterZookeeperAddress(), config.getClusterZookeeperSessionTimeout(), config.getClusterZookeeperRetryInterval()); + String nodeName = representationLocalIp + ":" + config.getClusterTcpPort(); + if (!NetUtils.validationIpPortV4FormatAddress(nodeName)) { + throw new SocketException("Unexpected LocalAddress. LocalAddress format must be ip:port (" + nodeName + ")."); + } - // TODO need modification - storing ip list using \r\n as delimiter since json list is not supported natively - this.clusterManager.registerWebCluster(nodeName, convertIpListToBytes(localIpList, "\r\n")); - } - } + this.pinpointServerSocket.setMessageListener(new PinpointSocketManagerHandler()); + this.pinpointServerSocket.bind(representationLocalIp, config.getClusterTcpPort()); - @PreDestroy - public void stop() { - if (config.isClusterEnable()) { - if (clusterManager != null) { - clusterManager.close(); - } - - if (pinpointServerSocket != null) { - pinpointServerSocket.close(); - } - } - } + this.clusterManager = new ZookeeperClusterManager(config.getClusterZookeeperAddress(), config.getClusterZookeeperSessionTimeout(), config.getClusterZookeeperRetryInterval()); - public List getCollectorChannelContext() { - return pinpointServerSocket.getDuplexCommunicationChannelContext(); - } - - public ChannelContext getCollectorChannelContext(String applicationName, String agentId, long startTimeStamp) { - List agentNameList = clusterManager.getRegisteredAgentList(applicationName, agentId, startTimeStamp); - - // having duplicate AgentName registered is an exceptional case - if (agentNameList.size() == 0) { - logger.warn("{}/{} couldn't find agent.", applicationName, agentId); - return null; - } else if (agentNameList.size() > 1) { - logger.warn("{}/{} found duplicate agent {}.", applicationName, agentId, agentNameList); - return null; - } - - String agentName = agentNameList.get(0); - - List channelContextList = getCollectorChannelContext(); - - for (ChannelContext channelContext : channelContextList) { - String id = (String) channelContext.getChannelProperties().get("id"); - if (agentName.startsWith(id)) { - return channelContext; - } - } - - return null; - } - - private String getRepresentationLocalV4Ip() { - String ip = NetUtils.getLocalV4Ip(); - - if (!ip.equals(NetUtils.LOOPBACK_ADDRESS_V4)) { - return ip; - } - - // local ip addresses with all LOOPBACK addresses removed - List ipList = NetUtils.getLocalV4IpList(); - if (ipList.size() > 0) { - return ipList.get(0); - } - - return NetUtils.LOOPBACK_ADDRESS_V4; - } + // TODO need modification - storing ip list using \r\n as delimiter since json list is not supported natively + this.clusterManager.registerWebCluster(nodeName, convertIpListToBytes(localIpList, "\r\n")); + } + } - private byte[] convertIpListToBytes(List ipList, String delimeter) { - StringBuilder stringBuilder = new StringBuilder(); - - Iterator ipIterator = ipList.iterator(); - while (ipIterator.hasNext()) { - String eachIp = ipIterator.next(); - stringBuilder.append(eachIp); - - if (ipIterator.hasNext()) { - stringBuilder.append(delimeter); - } - } - - return stringBuilder.toString().getBytes(charset); - } - - private class PinpointSocketManagerHandler implements ServerMessageListener { - @Override - public void handleSend(SendPacket sendPacket, SocketChannel channel) { - logger.warn("Unsupport send received {} {}", sendPacket, channel); - } + @PreDestroy + public void stop() { + if (config.isClusterEnable()) { + if (clusterManager != null) { + clusterManager.close(); + } - @Override - public void handleRequest(RequestPacket requestPacket, SocketChannel channel) { - logger.warn("Unsupport request received {} {}", requestPacket, channel); - } + if (pinpointServerSocket != null) { + pinpointServerSocket.close(); + } + } + } - @Override - public HandshakeResponseCode handleHandshake(Map properties) { - logger.warn("do handShake {}", properties); - return HandshakeResponseType.Success.DUPLEX_COMMUNICATION; - } - } + public List getCollectorChannelContext() { + return pinpointServerSocket.getDuplexCommunicationChannelContext(); + } + + public ChannelContext getCollectorChannelContext(String applicationName, String agentId, long startTimeStamp) { + List agentNameList = clusterManager.getRegisteredAgentList(applicationName, agentId, startTimeStamp); + + // having duplicate AgentName registered is an exceptional case + if (agentNameList.size() == 0) { + logger.warn("{}/{} couldn't find agent.", applicationName, agentId); + return null; + } else if (agentNameList.size() > 1) { + logger.warn("{}/{} found duplicate agent {}.", applicationName, agentId, agentNameList); + return null; + } + + String agentName = agentNameList.get(0); + + List channelContextList = getCollectorChannelContext(); + + for (ChannelContext channelContext : channelContextList) { + String id = (String) channelContext.getChannelProperties().get("id"); + if (agentName.startsWith(id)) { + return channelContext; + } + } + + return null; + } + + private String getRepresentationLocalV4Ip() { + String ip = NetUtils.getLocalV4Ip(); + + if (!ip.equals(NetUtils.LOOPBACK_ADDRESS_V4)) { + return ip; + } + + // local ip addresses with all LOOPBACK addresses removed + List ipList = NetUtils.getLocalV4IpList(); + if (ipList.size() > 0) { + return ipList.get(0); + } + + return NetUtils.LOOPBACK_ADDRESS_V4; + } + + private byte[] convertIpListToBytes(List ipList, String delimeter) { + StringBuilder stringBuilder = new StringBuilder(); + + Iterator ipIterator = ipList.iterator(); + while (ipIterator.hasNext()) { + String eachIp = ipIterator.next(); + stringBuilder.append(eachIp); + + if (ipIterator.hasNext()) { + stringBuilder.append(delimeter); + } + } + + return stringBuilder.toString().getBytes(charset); + } + + private class PinpointSocketManagerHandler implements ServerMessageListener { + @Override + public void handleSend(SendPacket sendPacket, SocketChannel channel) { + logger.warn("Unsupport send received {} {}", sendPacket, channel); + } + + @Override + public void handleRequest(RequestPacket requestPacket, SocketChannel channel) { + logger.warn("Unsupport request received {} {}", requestPacket, channel); + } + + @Override + public HandshakeResponseCode handleHandshake(Map properties) { + logger.warn("do handShake {}", properties); + return HandshakeResponseType.Success.DUPLEX_COMMUNICATION; + } + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java index 789c23c98..031b2fd82 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java @@ -22,7 +22,7 @@ package com.navercorp.pinpoint.web.service; * */ public interface AdminService { - void removeApplicationName(String applicationName); - - void removeAgentId(String applicationName, String agentId); + void removeApplicationName(String applicationName); + + void removeAgentId(String applicationName, String agentId); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java index bec084522..f92384653 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java @@ -29,17 +29,17 @@ import com.navercorp.pinpoint.web.dao.ApplicationIndexDao; @Service public class AdminServiceImpl implements AdminService { - @Autowired - ApplicationIndexDao applicationIndexDao; + @Autowired + ApplicationIndexDao applicationIndexDao; - @Override - public void removeApplicationName(String applicationName) { - applicationIndexDao.deleteApplicationName(applicationName); - } + @Override + public void removeApplicationName(String applicationName) { + applicationIndexDao.deleteApplicationName(applicationName); + } @Override public void removeAgentId(String applicationName, String agentId) { applicationIndexDao.deleteAgentId(applicationName, agentId); } - + } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java index 38a8d0c65..a60bec812 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java @@ -27,7 +27,7 @@ import com.navercorp.pinpoint.web.vo.Range; * @author netspider */ public interface AgentInfoService { - SortedMap> getApplicationAgentList(String applicationName, Range range); + SortedMap> getApplicationAgentList(String applicationName, Range range); Set selectAgent(String applicationId, Range range); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java index 84c0c75cf..6d167822e 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java @@ -36,66 +36,66 @@ import org.springframework.stereotype.Service; */ @Service public class AgentInfoServiceImpl implements AgentInfoService { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private ApplicationIndexDao applicationIndexDao; + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private AgentInfoDao agentInfoDao; - - /** - * FIXME from/to present in the interface but these values are not currently used. They should be used when agent list snapshot is implemented - */ - @Override - public SortedMap> getApplicationAgentList(String applicationName, Range range) { + @Autowired + private ApplicationIndexDao applicationIndexDao; + + @Autowired + private AgentInfoDao agentInfoDao; + + /** + * FIXME from/to present in the interface but these values are not currently used. They should be used when agent list snapshot is implemented + */ + @Override + public SortedMap> getApplicationAgentList(String applicationName, Range range) { if (applicationName == null) { throw new NullPointerException("applicationName must not be null"); } final List agentIdList = applicationIndexDao.selectAgentIds(applicationName); if (logger.isDebugEnabled()) { - logger.debug("agentIdList={}", agentIdList); + logger.debug("agentIdList={}", agentIdList); } - - if (CollectionUtils.isEmpty(agentIdList)) { - logger.debug("agentIdList is empty. applicationName={}, {}", applicationName, range); - return new TreeMap>(); - } - - // key = hostname - // value= list fo agentinfo - SortedMap> result = new TreeMap>(); - for (String agentId : agentIdList) { - List agentInfoList = agentInfoDao.getAgentInfo(agentId, range); + if (CollectionUtils.isEmpty(agentIdList)) { + logger.debug("agentIdList is empty. applicationName={}, {}", applicationName, range); + return new TreeMap>(); + } - if (agentInfoList.isEmpty()) { - logger.debug("agentinfolist is empty. agentid={}, {}", agentId, range); - continue; - } + // key = hostname + // value= list fo agentinfo + SortedMap> result = new TreeMap>(); - // FIXME just using the first value for now. Might need to check and pick which one to use. - AgentInfoBo agentInfo = agentInfoList.get(0); - String hostname = agentInfo.getHostName(); + for (String agentId : agentIdList) { + List agentInfoList = agentInfoDao.getAgentInfo(agentId, range); - if (result.containsKey(hostname)) { - result.get(hostname).add(agentInfo); - } else { - List list = new ArrayList(); - list.add(agentInfo); - result.put(hostname, list); - } - } + if (agentInfoList.isEmpty()) { + logger.debug("agentinfolist is empty. agentid={}, {}", agentId, range); + continue; + } - for (List agentInfoBoList : result.values()) { - Collections.sort(agentInfoBoList, AgentInfoBo.AGENT_NAME_ASC_COMPARATOR); - } + // FIXME just using the first value for now. Might need to check and pick which one to use. + AgentInfoBo agentInfo = agentInfoList.get(0); + String hostname = agentInfo.getHostName(); - logger.info("getApplicationAgentList={}", result); - - return result; - } + if (result.containsKey(hostname)) { + result.get(hostname).add(agentInfo); + } else { + List list = new ArrayList(); + list.add(agentInfo); + result.put(hostname, list); + } + } + + for (List agentInfoBoList : result.values()) { + Collections.sort(agentInfoBoList, AgentInfoBo.AGENT_NAME_ASC_COMPARATOR); + } + + logger.info("getApplicationAgentList={}", result); + + return result; + } public Set selectAgent(String applicationId, Range range) { if (applicationId == null) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/CommonServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/CommonServiceImpl.java index 6b6bb9fcb..7d36a09cd 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/CommonServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/CommonServiceImpl.java @@ -30,11 +30,11 @@ import com.navercorp.pinpoint.web.vo.Application; @Service public class CommonServiceImpl implements CommonService { - @Autowired - private ApplicationIndexDao applicationIndexDao; + @Autowired + private ApplicationIndexDao applicationIndexDao; - @Override - public List selectAllApplicationNames() { - return applicationIndexDao.selectAllApplicationNames(); - } + @Override + public List selectAllApplicationNames() { + return applicationIndexDao.selectAllApplicationNames(); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/FilteredMapServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/FilteredMapServiceImpl.java index 5743d10f8..789d2f181 100755 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/FilteredMapServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/FilteredMapServiceImpl.java @@ -90,17 +90,17 @@ public class FilteredMapServiceImpl implements FilteredMapService { @Override public LimitedScanResult> selectTraceIdsFromApplicationTraceIndex(String applicationName, SelectedScatterArea area, int limit) { - if (applicationName == null) { - throw new NullPointerException("applicationName must not be null"); - } - if (area == null) { - throw new NullPointerException("area must not be null"); - } - if (logger.isTraceEnabled()) { - logger.trace("scan(selectTraceIdsFromApplicationTraceIndex) {}, {}", applicationName, area); - } - - return this.applicationTraceIndexDao.scanTraceIndex(applicationName, area, limit); + if (applicationName == null) { + throw new NullPointerException("applicationName must not be null"); + } + if (area == null) { + throw new NullPointerException("area must not be null"); + } + if (logger.isTraceEnabled()) { + logger.trace("scan(selectTraceIdsFromApplicationTraceIndex) {}, {}", applicationName, area); + } + + return this.applicationTraceIndexDao.scanTraceIndex(applicationName, area, limit); } @Override diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/ScatterChartServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/ScatterChartServiceImpl.java index 4a4078aeb..a426a76c2 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/ScatterChartServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/ScatterChartServiceImpl.java @@ -45,13 +45,13 @@ public class ScatterChartServiceImpl implements ScatterChartService { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired - private ApplicationTraceIndexDao applicationTraceIndexDao; + private ApplicationTraceIndexDao applicationTraceIndexDao; - @Autowired - private TraceDao traceDao; + @Autowired + private TraceDao traceDao; - @Override - public List selectScatterData(String applicationName, Range range, int limit) { + @Override + public List selectScatterData(String applicationName, Range range, int limit) { if (applicationName == null) { throw new NullPointerException("applicationName must not be null"); } @@ -59,21 +59,21 @@ public class ScatterChartServiceImpl implements ScatterChartService { throw new NullPointerException("range must not be null"); } return applicationTraceIndexDao.scanTraceScatter(applicationName, range, limit); - } - - @Override - public List selectScatterData(String applicationName, SelectedScatterArea area, TransactionId offsetTransactionId, int offsetTransactionElapsed, int limit) { - if (applicationName == null) { - throw new NullPointerException("applicationName must not be null"); - } - if (area == null) { - throw new NullPointerException("area must not be null"); - } - return applicationTraceIndexDao.scanTraceScatter(applicationName, area, offsetTransactionId, offsetTransactionElapsed, limit); - } + } - @Override - public List selectScatterData(Collection transactionIdList, String applicationName, Filter filter) { + @Override + public List selectScatterData(String applicationName, SelectedScatterArea area, TransactionId offsetTransactionId, int offsetTransactionElapsed, int limit) { + if (applicationName == null) { + throw new NullPointerException("applicationName must not be null"); + } + if (area == null) { + throw new NullPointerException("area must not be null"); + } + return applicationTraceIndexDao.scanTraceScatter(applicationName, area, offsetTransactionId, offsetTransactionElapsed, limit); + } + + @Override + public List selectScatterData(Collection transactionIdList, String applicationName, Filter filter) { if (transactionIdList == null) { throw new NullPointerException("transactionIdList must not be null"); } @@ -86,30 +86,30 @@ public class ScatterChartServiceImpl implements ScatterChartService { final List> traceList = traceDao.selectAllSpans(transactionIdList); - final List result = new ArrayList(); + final List result = new ArrayList(); - for (List trace : traceList) { - if (!filter.include(trace)) { - continue; - } + for (List trace : traceList) { + if (!filter.include(trace)) { + continue; + } - for (SpanBo span : trace) { - if (applicationName.equals(span.getApplicationId())) { + for (SpanBo span : trace) { + if (applicationName.equals(span.getApplicationId())) { final TransactionId transactionId = new TransactionId(span.getTraceAgentId(), span.getTraceAgentStartTime(), span.getTraceTransactionSequence()); final Dot dot = new Dot(transactionId, span.getCollectorAcceptTime(), span.getElapsed(), span.getErrCode(), span.getAgentId()); result.add(dot); - } - } - } + } + } + } - return result; - } + return result; + } - /** - * Queries for details on dots selected from the scatter chart. - */ - @Override - public List selectTransactionMetadata(final TransactionMetadataQuery query) { + /** + * Queries for details on dots selected from the scatter chart. + */ + @Override + public List selectTransactionMetadata(final TransactionMetadataQuery query) { if (query == null) { throw new NullPointerException("query must not be null"); } @@ -117,7 +117,7 @@ public class ScatterChartServiceImpl implements ScatterChartService { final List> selectedSpans = traceDao.selectSpans(transactionIdList); - final List result = new ArrayList(query.size()); + final List result = new ArrayList(query.size()); int index = 0; for (List spans : selectedSpans) { if (spans.size() == 0) { @@ -141,8 +141,8 @@ public class ScatterChartServiceImpl implements ScatterChartService { } } index++; - } + } - return result; - } + return result; + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/SpanServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/SpanServiceImpl.java index f3c3389d5..f75f1747c 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/SpanServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/SpanServiceImpl.java @@ -44,76 +44,76 @@ import org.springframework.stereotype.Service; @Service public class SpanServiceImpl implements SpanService { - private Logger logger = LoggerFactory.getLogger(this.getClass()); + private Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private TraceDao traceDao; + @Autowired + private TraceDao traceDao; - @Autowired - private SqlMetaDataDao sqlMetaDataDao; + @Autowired + private SqlMetaDataDao sqlMetaDataDao; - @Autowired - private ApiMetaDataDao apiMetaDataDao; + @Autowired + private ApiMetaDataDao apiMetaDataDao; @Autowired private StringMetaDataDao stringMetaDataDao; - private final SqlParser sqlParser = new SqlParser(); - private final OutputParameterParser outputParameterParser = new OutputParameterParser(); + private final SqlParser sqlParser = new SqlParser(); + private final OutputParameterParser outputParameterParser = new OutputParameterParser(); - @Override - public SpanResult selectSpan(TransactionId transactionId, long selectedSpanHint) { + @Override + public SpanResult selectSpan(TransactionId transactionId, long selectedSpanHint) { if (transactionId == null) { throw new NullPointerException("transactionId must not be null"); } List spans = traceDao.selectSpanAndAnnotation(transactionId); - if (spans == null || spans.isEmpty()) { - return new SpanResult(SpanAligner2.FAIL_MATCH, Collections.emptyList()); - } + if (spans == null || spans.isEmpty()) { + return new SpanResult(SpanAligner2.FAIL_MATCH, Collections.emptyList()); + } SpanResult result = order(spans, selectedSpanHint); List order = result.getSpanAlignList(); -// transitionApiId(order); - transitionDynamicApiId(order); - transitionSqlId(order); +// transitionApiId(order); + transitionDynamicApiId(order); + transitionSqlId(order); transitionCachedString(order); transitionException(order); // TODO need to at least show the row data when root span is not found. - return result; - } + return result; + } private void transitionAnnotation(List spans, AnnotationReplacementCallback annotationReplacementCallback) { for (SpanAlign spanAlign : spans) { - List annotationBoList; - if (spanAlign.isSpan()) { - annotationBoList = spanAlign.getSpanBo().getAnnotationBoList(); + List annotationBoList; + if (spanAlign.isSpan()) { + annotationBoList = spanAlign.getSpanBo().getAnnotationBoList(); if (annotationBoList == null) { annotationBoList = new ArrayList(); spanAlign.getSpanBo().setAnnotationBoList(annotationBoList); } - annotationReplacementCallback.replacement(spanAlign, annotationBoList); - } else { - annotationBoList = spanAlign.getSpanEventBo().getAnnotationBoList(); + annotationReplacementCallback.replacement(spanAlign, annotationBoList); + } else { + annotationBoList = spanAlign.getSpanEventBo().getAnnotationBoList(); if (annotationBoList == null) { annotationBoList = new ArrayList(); spanAlign.getSpanBo().setAnnotationBoList(annotationBoList); } - annotationReplacementCallback.replacement(spanAlign, annotationBoList); - } - } - } + annotationReplacementCallback.replacement(spanAlign, annotationBoList); + } + } + } - private void transitionSqlId(final List spans) { - this.transitionAnnotation(spans, new AnnotationReplacementCallback() { - @Override - public void replacement(SpanAlign spanAlign, List annotationBoList) { - AnnotationBo sqlIdAnnotation = findAnnotation(annotationBoList, AnnotationKey.SQL_ID.getCode()); - if (sqlIdAnnotation == null) { - return; - } + private void transitionSqlId(final List spans) { + this.transitionAnnotation(spans, new AnnotationReplacementCallback() { + @Override + public void replacement(SpanAlign spanAlign, List annotationBoList) { + AnnotationBo sqlIdAnnotation = findAnnotation(annotationBoList, AnnotationKey.SQL_ID.getCode()); + if (sqlIdAnnotation == null) { + return; + } final AgentKey agentKey = getAgentKey(spanAlign); @@ -121,60 +121,60 @@ public class SpanServiceImpl implements SpanService { final IntStringStringValue sqlValue = (IntStringStringValue) sqlIdAnnotation.getValue(); final int hashCode = sqlValue.getIntValue(); final String sqlParam = sqlValue.getStringValue1(); - final List sqlMetaDataList = sqlMetaDataDao.getSqlMetaData(agentKey.getAgentId(), agentKey.getAgentStartTime(), hashCode); - final int size = sqlMetaDataList.size(); - if (size == 0) { - AnnotationBo api = new AnnotationBo(); - api.setKey(AnnotationKey.SQL.getCode()); - api.setValue("SQL-ID not found hashCode:" + hashCode); - annotationBoList.add(api); - } else if (size == 1) { - final SqlMetaDataBo sqlMetaDataBo = sqlMetaDataList.get(0); - if (StringUtils.isEmpty(sqlParam)) { - AnnotationBo sqlMeta = new AnnotationBo(); - sqlMeta.setKey(AnnotationKey.SQL_METADATA.getCode()); - sqlMeta.setValue(sqlMetaDataBo.getSql()); - annotationBoList.add(sqlMeta); + final List sqlMetaDataList = sqlMetaDataDao.getSqlMetaData(agentKey.getAgentId(), agentKey.getAgentStartTime(), hashCode); + final int size = sqlMetaDataList.size(); + if (size == 0) { + AnnotationBo api = new AnnotationBo(); + api.setKey(AnnotationKey.SQL.getCode()); + api.setValue("SQL-ID not found hashCode:" + hashCode); + annotationBoList.add(api); + } else if (size == 1) { + final SqlMetaDataBo sqlMetaDataBo = sqlMetaDataList.get(0); + if (StringUtils.isEmpty(sqlParam)) { + AnnotationBo sqlMeta = new AnnotationBo(); + sqlMeta.setKey(AnnotationKey.SQL_METADATA.getCode()); + sqlMeta.setValue(sqlMetaDataBo.getSql()); + annotationBoList.add(sqlMeta); -// AnnotationBo checkFail = checkIdentifier(spanAlign, sqlMetaDataBo); -// if (checkFail != null) { -// // fail -// annotationBoList.add(checkFail); -// return; -// } +// AnnotationBo checkFail = checkIdentifier(spanAlign, sqlMetaDataBo); +// if (checkFail != null) { +// // fail +// annotationBoList.add(checkFail); +// return; +// } - AnnotationBo sql = new AnnotationBo(); - sql.setKey(AnnotationKey.SQL.getCode()); - sql.setValue(sqlMetaDataBo.getSql()); - annotationBoList.add(sql); - } else { - logger.debug("sqlMetaDataBo:{}", sqlMetaDataBo); - final String outputParams = sqlParam; - List parsedOutputParams = outputParameterParser.parseOutputParameter(outputParams); - logger.debug("outputPrams:{}, parsedOutputPrams:{}", outputParams, parsedOutputParams); - String originalSql = sqlParser.combineOutputParams(sqlMetaDataBo.getSql(), parsedOutputParams); - logger.debug("outputPrams{}, originalSql:{}", outputParams, originalSql); + AnnotationBo sql = new AnnotationBo(); + sql.setKey(AnnotationKey.SQL.getCode()); + sql.setValue(sqlMetaDataBo.getSql()); + annotationBoList.add(sql); + } else { + logger.debug("sqlMetaDataBo:{}", sqlMetaDataBo); + final String outputParams = sqlParam; + List parsedOutputParams = outputParameterParser.parseOutputParameter(outputParams); + logger.debug("outputPrams:{}, parsedOutputPrams:{}", outputParams, parsedOutputParams); + String originalSql = sqlParser.combineOutputParams(sqlMetaDataBo.getSql(), parsedOutputParams); + logger.debug("outputPrams{}, originalSql:{}", outputParams, originalSql); - AnnotationBo sqlMeta = new AnnotationBo(); - sqlMeta.setKey(AnnotationKey.SQL_METADATA.getCode()); - sqlMeta.setValue(sqlMetaDataBo.getSql()); - annotationBoList.add(sqlMeta); + AnnotationBo sqlMeta = new AnnotationBo(); + sqlMeta.setKey(AnnotationKey.SQL_METADATA.getCode()); + sqlMeta.setValue(sqlMetaDataBo.getSql()); + annotationBoList.add(sqlMeta); - AnnotationBo sql = new AnnotationBo(); - sql.setKey(AnnotationKey.SQL.getCode()); - sql.setValue(originalSql); - annotationBoList.add(sql); + AnnotationBo sql = new AnnotationBo(); + sql.setKey(AnnotationKey.SQL.getCode()); + sql.setValue(originalSql); + annotationBoList.add(sql); - } - } else { - // TODO need improvement - AnnotationBo api = new AnnotationBo(); - api.setKey(AnnotationKey.SQL.getCode()); - api.setValue(collisionSqlHashCodeMessage(hashCode, sqlMetaDataList)); - annotationBoList.add(api); - } - // add if bindValue exists + } + } else { + // TODO need improvement + AnnotationBo api = new AnnotationBo(); + api.setKey(AnnotationKey.SQL.getCode()); + api.setValue(collisionSqlHashCodeMessage(hashCode, sqlMetaDataList)); + annotationBoList.add(api); + } + // add if bindValue exists final String bindValue = sqlValue.getStringValue2(); if (StringUtils.isNotEmpty(bindValue)) { AnnotationBo bindValueAnnotation = new AnnotationBo(); @@ -183,75 +183,75 @@ public class SpanServiceImpl implements SpanService { annotationBoList.add(bindValueAnnotation); } - } + } - }); - } + }); + } - private AnnotationBo findAnnotation(List annotationBoList, int key) { - for (AnnotationBo annotationBo : annotationBoList) { - if (key == annotationBo.getKey()) { - return annotationBo; - } - } - return null; - } + private AnnotationBo findAnnotation(List annotationBoList, int key) { + for (AnnotationBo annotationBo : annotationBoList) { + if (key == annotationBo.getKey()) { + return annotationBo; + } + } + return null; + } - private String collisionSqlHashCodeMessage(int hashCode, List sqlMetaDataList) { - // TODO need a separate test case to test for hashCode collision (probability way too low for easy replication) - StringBuilder sb = new StringBuilder(64); - sb.append("Collision Sql hashCode:"); - sb.append(hashCode); - sb.append('\n'); - for (int i = 0; i < sqlMetaDataList.size(); i++) { - if (i != 0) { - sb.append("or\n"); - } - SqlMetaDataBo sqlMetaDataBo = sqlMetaDataList.get(i); - sb.append(sqlMetaDataBo.getSql()); - } - return sb.toString(); - } + private String collisionSqlHashCodeMessage(int hashCode, List sqlMetaDataList) { + // TODO need a separate test case to test for hashCode collision (probability way too low for easy replication) + StringBuilder sb = new StringBuilder(64); + sb.append("Collision Sql hashCode:"); + sb.append(hashCode); + sb.append('\n'); + for (int i = 0; i < sqlMetaDataList.size(); i++) { + if (i != 0) { + sb.append("or\n"); + } + SqlMetaDataBo sqlMetaDataBo = sqlMetaDataList.get(i); + sb.append(sqlMetaDataBo.getSql()); + } + return sb.toString(); + } - private void transitionDynamicApiId(List spans) { - this.transitionAnnotation(spans, new AnnotationReplacementCallback() { - @Override - public void replacement(SpanAlign spanAlign, List annotationBoList) { + private void transitionDynamicApiId(List spans) { + this.transitionAnnotation(spans, new AnnotationReplacementCallback() { + @Override + public void replacement(SpanAlign spanAlign, List annotationBoList) { final AgentKey key = getAgentKey(spanAlign); final int apiId = getApiId(spanAlign); // may be able to get a more accurate data using agentIdentifier. - List apiMetaDataList = apiMetaDataDao.getApiMetaData(key.getAgentId(), key.getAgentStartTime(), apiId); - int size = apiMetaDataList.size(); - if (size == 0) { - AnnotationBo api = new AnnotationBo(); - api.setKey(AnnotationKey.ERROR_API_METADATA_NOT_FOUND.getCode()); - api.setValue("API-DynamicID not found. api:" + apiId); - annotationBoList.add(api); - } else if (size == 1) { - ApiMetaDataBo apiMetaDataBo = apiMetaDataList.get(0); - AnnotationBo apiMetaData = new AnnotationBo(); - apiMetaData.setKey(AnnotationKey.API_METADATA.getCode()); - apiMetaData.setValue(apiMetaDataBo); - annotationBoList.add(apiMetaData); + List apiMetaDataList = apiMetaDataDao.getApiMetaData(key.getAgentId(), key.getAgentStartTime(), apiId); + int size = apiMetaDataList.size(); + if (size == 0) { + AnnotationBo api = new AnnotationBo(); + api.setKey(AnnotationKey.ERROR_API_METADATA_NOT_FOUND.getCode()); + api.setValue("API-DynamicID not found. api:" + apiId); + annotationBoList.add(api); + } else if (size == 1) { + ApiMetaDataBo apiMetaDataBo = apiMetaDataList.get(0); + AnnotationBo apiMetaData = new AnnotationBo(); + apiMetaData.setKey(AnnotationKey.API_METADATA.getCode()); + apiMetaData.setValue(apiMetaDataBo); + annotationBoList.add(apiMetaData); - AnnotationBo apiAnnotation = new AnnotationBo(); - apiAnnotation.setKey(AnnotationKey.API.getCode()); - String apiInfo = getApiInfo(apiMetaDataBo); - apiAnnotation.setValue(apiInfo); - annotationBoList.add(apiAnnotation); - } else { - AnnotationBo apiAnnotation = new AnnotationBo(); - apiAnnotation.setKey(AnnotationKey.ERROR_API_METADATA_DID_COLLSION.getCode()); - String collisonMessage = collisionApiDidMessage(apiId, apiMetaDataList); - apiAnnotation.setValue(collisonMessage); - annotationBoList.add(apiAnnotation); - } + AnnotationBo apiAnnotation = new AnnotationBo(); + apiAnnotation.setKey(AnnotationKey.API.getCode()); + String apiInfo = getApiInfo(apiMetaDataBo); + apiAnnotation.setValue(apiInfo); + annotationBoList.add(apiAnnotation); + } else { + AnnotationBo apiAnnotation = new AnnotationBo(); + apiAnnotation.setKey(AnnotationKey.ERROR_API_METADATA_DID_COLLSION.getCode()); + String collisonMessage = collisionApiDidMessage(apiId, apiMetaDataList); + apiAnnotation.setValue(collisonMessage); + annotationBoList.add(apiAnnotation); + } - } + } - }); - } + }); + } private void transitionCachedString(List spans) { this.transitionAnnotation(spans, new AnnotationReplacementCallback() { @@ -356,42 +356,42 @@ public class SpanServiceImpl implements SpanService { } } - private String collisionApiDidMessage(int apidId, List apiMetaDataList) { + private String collisionApiDidMessage(int apidId, List apiMetaDataList) { // TODO need a separate test case to test for hashCode collision (probability way too low for easy replication) - StringBuilder sb = new StringBuilder(64); - sb.append("Collision Api DynamicId:"); - sb.append(apidId); - sb.append('\n'); - for (int i = 0; i < apiMetaDataList.size(); i++) { - if (i != 0) { - sb.append("or\n"); - } - ApiMetaDataBo apiMetaDataBo = apiMetaDataList.get(i); - sb.append(getApiInfo(apiMetaDataBo)); - } - return sb.toString(); - } + StringBuilder sb = new StringBuilder(64); + sb.append("Collision Api DynamicId:"); + sb.append(apidId); + sb.append('\n'); + for (int i = 0; i < apiMetaDataList.size(); i++) { + if (i != 0) { + sb.append("or\n"); + } + ApiMetaDataBo apiMetaDataBo = apiMetaDataList.get(i); + sb.append(getApiInfo(apiMetaDataBo)); + } + return sb.toString(); + } - private String getApiInfo(ApiMetaDataBo apiMetaDataBo) { - if (apiMetaDataBo.getLineNumber() != -1) { - return apiMetaDataBo.getApiInfo() + ":" + apiMetaDataBo.getLineNumber(); - } else { - return apiMetaDataBo.getApiInfo(); - } - } + private String getApiInfo(ApiMetaDataBo apiMetaDataBo) { + if (apiMetaDataBo.getLineNumber() != -1) { + return apiMetaDataBo.getApiInfo() + ":" + apiMetaDataBo.getLineNumber(); + } else { + return apiMetaDataBo.getApiInfo(); + } + } - public static interface AnnotationReplacementCallback { - void replacement(SpanAlign spanAlign, List annotationBoList); - } + public static interface AnnotationReplacementCallback { + void replacement(SpanAlign spanAlign, List annotationBoList); + } - private SpanResult order(List spans, long selectedSpanHint) { - SpanAligner2 spanAligner = new SpanAligner2(spans, selectedSpanHint); + private SpanResult order(List spans, long selectedSpanHint) { + SpanAligner2 spanAligner = new SpanAligner2(spans, selectedSpanHint); List sort = spanAligner.sort(); logger.trace("SpanAlignList:{}", sort); return new SpanResult(spanAligner.getMatchType(), sort); - } + } private static final class AgentKey { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/TransactionInfoService.java b/web/src/main/java/com/navercorp/pinpoint/web/service/TransactionInfoService.java index 6fe80e727..6f1d8c470 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/TransactionInfoService.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/TransactionInfoService.java @@ -29,7 +29,7 @@ import com.navercorp.pinpoint.web.vo.callstacks.RecordSet; * */ public interface TransactionInfoService { - RecordSet createRecordSet(List spanAligns, long focusTimestamp); + RecordSet createRecordSet(List spanAligns, long focusTimestamp); - BusinessTransactions selectBusinessTransactions(List traceIds, String applicationName, Range range, Filter filter); + BusinessTransactions selectBusinessTransactions(List traceIds, String applicationName, Range range, Filter filter); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/TransactionInfoServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/TransactionInfoServiceImpl.java index 314359be9..65ab26ff9 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/TransactionInfoServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/TransactionInfoServiceImpl.java @@ -51,11 +51,11 @@ public class TransactionInfoServiceImpl implements TransactionInfoService { private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private TraceDao traceDao; + @Autowired + private TraceDao traceDao; - @Override - public BusinessTransactions selectBusinessTransactions(List transactionIdList, String applicationName, Range range, Filter filter) { + @Override + public BusinessTransactions selectBusinessTransactions(List transactionIdList, String applicationName, Range range, Filter filter) { if (transactionIdList == null) { throw new NullPointerException("transactionIdList must not be null"); } @@ -73,28 +73,28 @@ public class TransactionInfoServiceImpl implements TransactionInfoService { List> traceList; - if (filter == Filter.NONE) { - traceList = this.traceDao.selectSpans(transactionIdList); - } else { - traceList = this.traceDao.selectAllSpans(transactionIdList); - } + if (filter == Filter.NONE) { + traceList = this.traceDao.selectSpans(transactionIdList); + } else { + traceList = this.traceDao.selectAllSpans(transactionIdList); + } - BusinessTransactions businessTransactions = new BusinessTransactions(); - for (List trace : traceList) { - if (!filter.include(trace)) { - continue; - } + BusinessTransactions businessTransactions = new BusinessTransactions(); + for (List trace : traceList) { + if (!filter.include(trace)) { + continue; + } - for (SpanBo spanBo : trace) { - // show application's incoming requests - if (applicationName.equals(spanBo.getApplicationId())) { - businessTransactions.add(spanBo); - } - } - } + for (SpanBo spanBo : trace) { + // show application's incoming requests + if (applicationName.equals(spanBo.getApplicationId())) { + businessTransactions.add(spanBo); + } + } + } - return businessTransactions; - } + return businessTransactions; + } @Override public RecordSet createRecordSet(List spanAlignList, long focusTimestamp) { @@ -287,40 +287,40 @@ public class TransactionInfoServiceImpl implements TransactionInfoService { if (method != null) { ApiDescription apiDescription = apiDescriptionParser.parse(method); Record record = new Record(spanAlign.getDepth(), - spanBoSequence, - parentSequence, - true, - apiDescription.getSimpleMethodDescription(), - argument, - begin, - elapsed, - getGap(stack), - spanBo.getAgentId(), - spanBo.getApplicationId(), - spanBo.getServiceType(), - null, - spanAlign.isHasChild(), - false); + spanBoSequence, + parentSequence, + true, + apiDescription.getSimpleMethodDescription(), + argument, + begin, + elapsed, + getGap(stack), + spanBo.getAgentId(), + spanBo.getApplicationId(), + spanBo.getServiceType(), + null, + spanAlign.isHasChild(), + false); record.setSimpleClassName(apiDescription.getSimpleClassName()); record.setFullApiDescription(method); recordList.add(record); } else { AnnotationKey apiMetaDataError = AnnotationUtils.getApiMetaDataError(spanBo.getAnnotationBoList()); Record record = new Record(spanAlign.getDepth(), - spanBoSequence, - parentSequence, - true, - apiMetaDataError.getValue(), - argument, - begin, - elapsed, - getGap(stack), - spanBo.getAgentId(), - spanBo.getApplicationId(), - spanBo.getServiceType(), - null, - spanAlign.isHasChild(), - false); + spanBoSequence, + parentSequence, + true, + apiMetaDataError.getValue(), + argument, + begin, + elapsed, + getGap(stack), + spanBo.getAgentId(), + spanBo.getApplicationId(), + spanBo.getServiceType(), + null, + spanAlign.isHasChild(), + false); record.setSimpleClassName(""); record.setFullApiDescription(""); recordList.add(record); @@ -360,21 +360,21 @@ public class TransactionInfoServiceImpl implements TransactionInfoService { // use spanBo's applicationId instead of spanEventBo's destinationId to display the name of the calling application on the call stack. Record record = new Record(spanAlign.getDepth(), - spanBoEventSequence, - parentSequence, - true, - apiDescription.getSimpleMethodDescription(), - argument, - begin, - elapsed, - getGap(stack), - spanEventBo.getAgentId(), - spanBo.getApplicationId(), + spanBoEventSequence, + parentSequence, + true, + apiDescription.getSimpleMethodDescription(), + argument, + begin, + elapsed, + getGap(stack), + spanEventBo.getAgentId(), + spanBo.getApplicationId(), spanEventBo.getServiceType(), - /* spanEventBo.getDestinationId(), spanEventBo.getServiceType(),*/ - destinationId, - spanAlign.isHasChild(), - false); + /* spanEventBo.getDestinationId(), spanEventBo.getServiceType(),*/ + destinationId, + spanAlign.isHasChild(), + false); record.setSimpleClassName(apiDescription.getSimpleClassName()); record.setFullApiDescription(method); @@ -388,21 +388,21 @@ public class TransactionInfoServiceImpl implements TransactionInfoService { // use spanBo's applicationId instead of spanEventBo's destinationId to display the name of the calling application on the call stack. Record record = new Record(spanAlign.getDepth(), - spanBoEventSequence, - parentSequence, - true, - apiMetaDataError.getValue(), - argument, - begin, - elapsed, - getGap(stack), - spanEventBo.getAgentId(), - spanBo.getApplicationId(), + spanBoEventSequence, + parentSequence, + true, + apiMetaDataError.getValue(), + argument, + begin, + elapsed, + getGap(stack), + spanEventBo.getAgentId(), + spanBo.getApplicationId(), spanEventBo.getServiceType(), - /*spanEventBo.getDestinationId(), spanEventBo.getServiceType(),*/ - destinationId, - spanAlign.isHasChild(), - false); + /*spanEventBo.getDestinationId(), spanEventBo.getServiceType(),*/ + destinationId, + spanAlign.isHasChild(), + false); record.setSimpleClassName(""); record.setFullApiDescription(method); @@ -427,40 +427,40 @@ public class TransactionInfoServiceImpl implements TransactionInfoService { if (spanBo.hasException()) { String simpleExceptionClass = getSimpleExceptionName(spanBo.getExceptionClass()); return new Record(spanAlign.getDepth() + 1, - getNextId(), - parentSequence, - false, - simpleExceptionClass, - spanBo.getExceptionMessage(), - 0L, - 0L, - 0, - null, - null, - null, - null, - false, - false); + getNextId(), + parentSequence, + false, + simpleExceptionClass, + spanBo.getExceptionMessage(), + 0L, + 0L, + 0, + null, + null, + null, + null, + false, + false); } } else { final SpanEventBo spanEventBo = spanAlign.getSpanEventBo(); if (spanEventBo.hasException()) { String simpleExceptionClass = getSimpleExceptionName(spanEventBo.getExceptionClass()); return new Record(spanAlign.getDepth() + 1, - getNextId(), - parentSequence, - false, - simpleExceptionClass, - spanEventBo.getExceptionMessage(), - 0L, - 0L, - 0, - null, - null, - null, - null, - false, - true); + getNextId(), + parentSequence, + false, + simpleExceptionClass, + spanEventBo.getExceptionMessage(), + 0L, + 0L, + 0, + null, + null, + null, + null, + false, + true); } } return null; diff --git a/web/src/main/java/com/navercorp/pinpoint/web/servletfilter/NoCacheFilter.java b/web/src/main/java/com/navercorp/pinpoint/web/servletfilter/NoCacheFilter.java index 448c3aa03..2daabe0e2 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/servletfilter/NoCacheFilter.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/servletfilter/NoCacheFilter.java @@ -32,21 +32,21 @@ import javax.servlet.http.HttpServletResponse; * */ public class NoCacheFilter implements Filter { - private FilterConfig filterConfig = null; + private FilterConfig filterConfig = null; - public void init(FilterConfig filterConfig) { - this.filterConfig = filterConfig; - } + public void init(FilterConfig filterConfig) { + this.filterConfig = filterConfig; + } - public void destroy() { - this.filterConfig = null; - } + public void destroy() { + this.filterConfig = null; + } - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - HttpServletResponse httpResponse = (HttpServletResponse) response; - httpResponse.setHeader("Cache-Control", "no-cache"); - httpResponse.setDateHeader("Expires", 0); - httpResponse.setHeader("Pragma", "No-cache"); - chain.doFilter(request, response); - } + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletResponse httpResponse = (HttpServletResponse) response; + httpResponse.setHeader("Cache-Control", "no-cache"); + httpResponse.setDateHeader("Expires", 0); + httpResponse.setHeader("Pragma", "No-cache"); + chain.doFilter(request, response); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/AgentStatus.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/AgentStatus.java index 8a7e577b4..8dbd4a788 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/AgentStatus.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/AgentStatus.java @@ -25,25 +25,25 @@ import com.navercorp.pinpoint.common.bo.AgentInfoBo; */ public class AgentStatus { - private final boolean exists; - private final long checkTime; - private final AgentInfoBo agentInfo; + private final boolean exists; + private final long checkTime; + private final AgentInfoBo agentInfo; - public AgentStatus(AgentInfoBo agentInfoBo) { - this.exists = agentInfoBo != null; - this.agentInfo = agentInfoBo; - this.checkTime = System.currentTimeMillis(); - } + public AgentStatus(AgentInfoBo agentInfoBo) { + this.exists = agentInfoBo != null; + this.agentInfo = agentInfoBo; + this.checkTime = System.currentTimeMillis(); + } - public boolean isExists() { - return exists; - } + public boolean isExists() { + return exists; + } - public AgentInfoBo getAgentInfo() { - return agentInfo; - } + public AgentInfoBo getAgentInfo() { + return agentInfo; + } - public long getCheckTime() { - return checkTime; - } + public long getCheckTime() { + return checkTime; + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/Application.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/Application.java index c94ba0874..56cb5f593 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/Application.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/Application.java @@ -25,7 +25,7 @@ import com.navercorp.pinpoint.common.ServiceType; * */ public final class Application { - private final String name; + private final String name; private final ServiceType serviceType; // store separately to track undefined cases more easily private final short code; @@ -42,22 +42,22 @@ public final class Application { this.code = serviceType.getCode(); } - public Application(String name, short serviceType) { + public Application(String name, short serviceType) { if (name == null) { throw new NullPointerException("name must not be null"); } this.name = name; - this.serviceType = ServiceType.findServiceType(serviceType); + this.serviceType = ServiceType.findServiceType(serviceType); this.code = serviceType; - } + } public String getName() { - return name; - } + return name; + } - public ServiceType getServiceType() { - return serviceType; - } + public ServiceType getServiceType() { + return serviceType; + } public short getServiceTypeCode() { return serviceType.getCode(); @@ -101,7 +101,7 @@ public final class Application { } @Override - public String toString() { - return name + "(" + serviceType + ":" + code + ")"; - } + public String toString() { + return name + "(" + serviceType + ":" + code + ")"; + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/BusinessTransaction.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/BusinessTransaction.java index c46fc12f7..be211ad02 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/BusinessTransaction.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/BusinessTransaction.java @@ -26,87 +26,87 @@ import com.navercorp.pinpoint.common.util.TransactionIdUtils; * @author emeroad */ public class BusinessTransaction { - private final List traces = new ArrayList(); - private final String rpc; + private final List traces = new ArrayList(); + private final String rpc; - private int calls = 0; - private int error = 0; - private long totalTime = 0; - private long maxTime = 0; - private long minTime = 0; + private int calls = 0; + private int error = 0; + private long totalTime = 0; + private long maxTime = 0; + private long minTime = 0; - public BusinessTransaction(SpanBo span) { + public BusinessTransaction(SpanBo span) { if (span == null) { throw new NullPointerException("span must not be null"); } this.rpc = span.getRpc(); - long elapsed = span.getElapsed(); - totalTime = maxTime = minTime = elapsed; + long elapsed = span.getElapsed(); + totalTime = maxTime = minTime = elapsed; String traceIdString = TransactionIdUtils.formatString(span.getTraceAgentId(), span.getTraceAgentStartTime(), span.getTraceTransactionSequence()); Trace trace = new Trace(traceIdString, elapsed, span.getCollectorAcceptTime(), span.getErrCode()); this.traces.add(trace); - calls++; - if(span.getErrCode() > 0) { - error++; - } - } + calls++; + if(span.getErrCode() > 0) { + error++; + } + } - public void add(SpanBo span) { + public void add(SpanBo span) { if (span == null) { throw new NullPointerException("span must not be null"); } long elapsed = span.getElapsed(); - totalTime += elapsed; - if (maxTime < elapsed) { - maxTime = elapsed; + totalTime += elapsed; + if (maxTime < elapsed) { + maxTime = elapsed; } - if (minTime > elapsed) { - minTime = elapsed; + if (minTime > elapsed) { + minTime = elapsed; } String traceIdString = TransactionIdUtils.formatString(span.getTraceAgentId(), span.getTraceAgentStartTime(), span.getTraceTransactionSequence()); Trace trace = new Trace(traceIdString, elapsed, span.getCollectorAcceptTime(), span.getErrCode()); - this.traces.add(trace); + this.traces.add(trace); - if(span.getErrCode() > 0) { - error++; - } - - //if (span.getParentSpanId() == -1) { - calls++; - //} - } + if(span.getErrCode() > 0) { + error++; + } - public String getRpc() { - return rpc; - } + //if (span.getParentSpanId() == -1) { + calls++; + //} + } - public List getTraces() { - return traces; - } + public String getRpc() { + return rpc; + } - public int getCalls() { - return calls; - } + public List getTraces() { + return traces; + } - public long getTotalTime() { - return totalTime; - } + public int getCalls() { + return calls; + } - public long getMaxTime() { - return maxTime; - } + public long getTotalTime() { + return totalTime; + } - public long getMinTime() { - return minTime; - } - - public int getError() { - return error; - } + public long getMaxTime() { + return maxTime; + } + + public long getMinTime() { + return minTime; + } + + public int getError() { + return error; + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/BusinessTransactions.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/BusinessTransactions.java index 05661d172..84d1cb8de 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/BusinessTransactions.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/BusinessTransactions.java @@ -28,33 +28,33 @@ import com.navercorp.pinpoint.common.bo.SpanBo; */ public class BusinessTransactions { - private final Map transactions = new HashMap(); + private final Map transactions = new HashMap(); - private int totalCallCount; - - public void add(SpanBo span) { + private int totalCallCount; + + public void add(SpanBo span) { if (span == null) { throw new NullPointerException("span must not be null"); } totalCallCount++; - - String rpc = span.getRpc(); - if (transactions.containsKey(rpc)) { - transactions.get(rpc).add(span); - } else { - transactions.put(rpc, new BusinessTransaction(span)); - } - } - public Collection getBusinessTransaction() { + String rpc = span.getRpc(); + if (transactions.containsKey(rpc)) { + transactions.get(rpc).add(span); + } else { + transactions.put(rpc, new BusinessTransaction(span)); + } + } + + public Collection getBusinessTransaction() { return transactions.values(); - } - - public int getTotalCallCount() { - return totalCallCount; - } - - public int getURLCount() { - return transactions.size(); - } + } + + public int getTotalCallCount() { + return totalCallCount; + } + + public int getURLCount() { + return transactions.size(); + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/LimitedScanResult.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/LimitedScanResult.java index d41767168..76e0aa9a8 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/LimitedScanResult.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/LimitedScanResult.java @@ -27,21 +27,21 @@ public class LimitedScanResult { private long limitedTime; private V data; - public V getScanData() { - return data; - } + public V getScanData() { + return data; + } - public void setScanData(V scanData) { - this.data = scanData; - } + public void setScanData(V scanData) { + this.data = scanData; + } - public long getLimitedTime() { - return limitedTime; - } + public long getLimitedTime() { + return limitedTime; + } - public void setLimitedTime(long limitedTime) { - this.limitedTime = limitedTime; - } + public void setLimitedTime(long limitedTime) { + this.limitedTime = limitedTime; + } @Override public String toString() { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/LoadFactor.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/LoadFactor.java index 95fedd6d4..7743431a4 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/LoadFactor.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/LoadFactor.java @@ -32,73 +32,73 @@ import org.slf4j.LoggerFactory; @Deprecated public class LoadFactor { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public static final Integer SLOT_VERY_SLOW = Integer.MAX_VALUE - 1; - public static final Integer SLOT_ERROR = (int)Integer.MAX_VALUE; + public static final Integer SLOT_VERY_SLOW = Integer.MAX_VALUE - 1; + public static final Integer SLOT_ERROR = (int)Integer.MAX_VALUE; -// /** -// *
-//	 * key = responseTimeslot
-//	 * value = count
-//	 * 
-// */ -// private final SortedMap histogramSummary = new TreeMap();; +// /** +// *
+//     * key = responseTimeslot
+//     * value = count
+//     * 
+// */ +// private final SortedMap histogramSummary = new TreeMap();; - /** - *
-	 * index = responseTimeslot index,
-	 * value = key=timestamp, value=value
-	 * 
- */ - private final List> timeseriesValueList = new ArrayList>(); - private final Map timeseriesSlotIndex = new TreeMap(); + /** + *
+     * index = responseTimeslot index,
+     * value = key=timestamp, value=value
+     * 
+ */ + private final List> timeseriesValueList = new ArrayList>(); + private final Map timeseriesSlotIndex = new TreeMap(); private final Range range; - private long successCount = 0; - private long failedCount = 0; + private long successCount = 0; + private long failedCount = 0; private final TimeWindow timeWindow; - public LoadFactor(Range range) { + public LoadFactor(Range range) { if (range == null) { throw new NullPointerException("range must not be null"); } this.range = range; this.timeWindow = new TimeWindow(range); - } + } - /** - * initialize timeseries with default value. - * - * @return - */ - private Map makeEmptyTimeseriesValueMap() { - Map map = new TreeMap(); + /** + * initialize timeseries with default value. + * + * @return + */ + private Map makeEmptyTimeseriesValueMap() { + Map map = new TreeMap(); for (Long time : timeWindow) { map.put(time, 0L); } - return map; - } + return map; + } - /** - * Empty slots in the view is shown as 0 if the histogram slot is set. - * If not, value cannot be shown as the key is unknown. - * - * @param schema - */ - public void setDefaultHistogramSlotList(HistogramSchema schema) { - if (successCount > 0 || failedCount > 0) { - throw new IllegalStateException("Can't set slot list while containing the data."); - } + /** + * Empty slots in the view is shown as 0 if the histogram slot is set. + * If not, value cannot be shown as the key is unknown. + * + * @param schema + */ + public void setDefaultHistogramSlotList(HistogramSchema schema) { + if (successCount > 0 || failedCount > 0) { + throw new IllegalStateException("Can't set slot list while containing the data."); + } -// histogramSummary.clear(); - timeseriesSlotIndex.clear(); - timeseriesValueList.clear(); +// histogramSummary.clear(); + timeseriesSlotIndex.clear(); + timeseriesValueList.clear(); -// histogramSummary.put(SLOT_VERY_SLOW, 0L); -// histogramSummary.put(SLOT_ERROR, 0L); +// histogramSummary.put(SLOT_VERY_SLOW, 0L); +// histogramSummary.put(SLOT_ERROR, 0L); timeseriesSlotIndex.put((int)schema.getFastSlot().getSlotTime(), timeseriesSlotIndex.size()); timeseriesValueList.add(makeEmptyTimeseriesValueMap()); @@ -109,49 +109,49 @@ public class LoadFactor { timeseriesSlotIndex.put((int)schema.getSlowSlot().getSlotTime(), timeseriesSlotIndex.size()); timeseriesValueList.add(makeEmptyTimeseriesValueMap()); - timeseriesSlotIndex.put(SLOT_VERY_SLOW, timeseriesSlotIndex.size()); - timeseriesSlotIndex.put(SLOT_ERROR, timeseriesSlotIndex.size()); + timeseriesSlotIndex.put(SLOT_VERY_SLOW, timeseriesSlotIndex.size()); + timeseriesSlotIndex.put(SLOT_ERROR, timeseriesSlotIndex.size()); - timeseriesValueList.add(makeEmptyTimeseriesValueMap()); - timeseriesValueList.add(makeEmptyTimeseriesValueMap()); - } + timeseriesValueList.add(makeEmptyTimeseriesValueMap()); + timeseriesValueList.add(makeEmptyTimeseriesValueMap()); + } - public void addSample(long timestamp, int responseTimeslot, long callCount, boolean isFailed) { + public void addSample(long timestamp, int responseTimeslot, long callCount, boolean isFailed) { if (logger.isDebugEnabled()) { - logger.debug("Add sample. timeslot={}, responseTimeslot={}, callCount={}, failed={}", timestamp, responseTimeslot, callCount, isFailed); + logger.debug("Add sample. timeslot={}, responseTimeslot={}, callCount={}, failed={}", timestamp, responseTimeslot, callCount, isFailed); } - timestamp = timeWindow.refineTimestamp(timestamp); + timestamp = timeWindow.refineTimestamp(timestamp); - if (isFailed) { - failedCount += callCount; - } else { - successCount += callCount; - } + if (isFailed) { + failedCount += callCount; + } else { + successCount += callCount; + } - if (responseTimeslot == -1) { - responseTimeslot = SLOT_ERROR; - } else if (responseTimeslot == 0) { - responseTimeslot = SLOT_VERY_SLOW; - } + if (responseTimeslot == -1) { + responseTimeslot = SLOT_ERROR; + } else if (responseTimeslot == 0) { + responseTimeslot = SLOT_VERY_SLOW; + } - // add summary -// long value = histogramSummary.containsKey(responseTimeslot) ? histogramSummary.get(responseTimeslot) + callCount : callCount; -// histogramSummary.put(responseTimeslot, value); + // add summary +// long value = histogramSummary.containsKey(responseTimeslot) ? histogramSummary.get(responseTimeslot) + callCount : callCount; +// histogramSummary.put(responseTimeslot, value); - /** - *
-		 * timeseriesValueList : 
-		 * list[respoinse_slot_no + 0] = value 
-		 * list[respoinse_slot_no + 1] = value 
-		 * list[respoinse_slot_no + N] = value
-		 * 
- */ - for (int i = 0; i < timeseriesValueList.size(); i++) { - Map map = timeseriesValueList.get(i); + /** + *
+         * timeseriesValueList :
+         * list[respoinse_slot_no + 0] = value
+         * list[respoinse_slot_no + 1] = value
+         * list[respoinse_slot_no + N] = value
+         * 
+ */ + for (int i = 0; i < timeseriesValueList.size(); i++) { + Map map = timeseriesValueList.get(i); - // the same time should exist in different slots. - // FIXME change responseTimeSlot's data type to short + // the same time should exist in different slots. + // FIXME change responseTimeSlot's data type to short Integer slotNumber = timeseriesSlotIndex.get(responseTimeslot); if (i == slotNumber) { long v = map.containsKey(timestamp) ? map.get(timestamp) + callCount : callCount; @@ -162,39 +162,39 @@ public class LoadFactor { } } } - } + } -// public Map getHistogramSummary() { -// return histogramSummary; -// } +// public Map getHistogramSummary() { +// return histogramSummary; +// } - public long getSuccessCount() { - return successCount; - } + public long getSuccessCount() { + return successCount; + } - public long getFailedCount() { - return failedCount; - } + public long getFailedCount() { + return failedCount; + } - public Map getTimeseriesSlotIndex() { - return timeseriesSlotIndex; - } + public Map getTimeseriesSlotIndex() { + return timeseriesSlotIndex; + } - public List> getTimeseriesValue() { - return timeseriesValueList; - } + public List> getTimeseriesValue() { + return timeseriesValueList; + } - public int getVerySlow() { - return SLOT_VERY_SLOW; - } + public int getVerySlow() { + return SLOT_VERY_SLOW; + } - public int getError() { - return SLOT_ERROR; - } + public int getError() { + return SLOT_ERROR; + } - @Override - public String toString() { - return "LoadFactor [timeseriesValue=" + timeseriesValueList + ", timeseriesSlotIndex=" + timeseriesSlotIndex + ", range=" + range + ", successCount=" + successCount + ", failedCount=" + failedCount + "]"; - } + @Override + public String toString() { + return "LoadFactor [timeseriesValue=" + timeseriesValueList + ", timeseriesSlotIndex=" + timeseriesSlotIndex + ", range=" + range + ", successCount=" + successCount + ", failedCount=" + failedCount + "]"; + } } \ No newline at end of file diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/Range.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/Range.java index 2a48d2ef9..97d407727 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/Range.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/Range.java @@ -38,7 +38,7 @@ public final class Range { this.from = from; this.to = to; if (check) { - validate(); + validate(); } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/ResponseTimeRange.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/ResponseTimeRange.java index df2639473..d6f9cee4b 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/ResponseTimeRange.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/ResponseTimeRange.java @@ -23,72 +23,72 @@ package com.navercorp.pinpoint.web.vo; * */ public final class ResponseTimeRange { - private final int from; - private final int to; + private final int from; + private final int to; - public ResponseTimeRange(int from, int to) { - this.from = from; - this.to = to; - validate(); - } + public ResponseTimeRange(int from, int to) { + this.from = from; + this.to = to; + validate(); + } - public ResponseTimeRange(int from, int to, boolean check) { - this.from = from; - this.to = to; - if (check) { - validate(); - } - } + public ResponseTimeRange(int from, int to, boolean check) { + this.from = from; + this.to = to; + if (check) { + validate(); + } + } - public static ResponseTimeRange createUncheckedRange(int from, int to) { - return new ResponseTimeRange(from, to, false); - } + public static ResponseTimeRange createUncheckedRange(int from, int to) { + return new ResponseTimeRange(from, to, false); + } - public int getFrom() { - return from; - } + public int getFrom() { + return from; + } - public int getTo() { - return to; - } + public int getTo() { + return to; + } - public int getRange() { - return to - from; - } + public int getRange() { + return to - from; + } - public void validate() { - if (this.to < this.from) { - throw new IllegalArgumentException("invalid range:" + this); - } - } + public void validate() { + if (this.to < this.from) { + throw new IllegalArgumentException("invalid range:" + this); + } + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + from; - result = prime * result + to; - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + from; + result = prime * result + to; + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ResponseTimeRange other = (ResponseTimeRange) obj; - if (from != other.from) - return false; - if (to != other.to) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ResponseTimeRange other = (ResponseTimeRange) obj; + if (from != other.from) + return false; + if (to != other.to) + return false; + return true; + } - @Override - public String toString() { - return "ResponseTimeRange [from=" + from + ", to=" + to + "]"; - } + @Override + public String toString() { + return "ResponseTimeRange [from=" + from + ", to=" + to + "]"; + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/SelectedScatterArea.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/SelectedScatterArea.java index 4a2979d3a..652913c0e 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/SelectedScatterArea.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/SelectedScatterArea.java @@ -24,71 +24,71 @@ package com.navercorp.pinpoint.web.vo; */ public final class SelectedScatterArea { - private final Range timeRange; - private final ResponseTimeRange responseTimeRange; + private final Range timeRange; + private final ResponseTimeRange responseTimeRange; - public SelectedScatterArea(long timeFrom, long timeTo, int responseTimeFrom, int responseTimeTo) { - this.timeRange = new Range(timeFrom, timeTo); - this.responseTimeRange = new ResponseTimeRange(responseTimeFrom, responseTimeTo); - } + public SelectedScatterArea(long timeFrom, long timeTo, int responseTimeFrom, int responseTimeTo) { + this.timeRange = new Range(timeFrom, timeTo); + this.responseTimeRange = new ResponseTimeRange(responseTimeFrom, responseTimeTo); + } - public SelectedScatterArea(long timeFrom, long timeTo, int responseTimeFrom, int responseTimeTo, boolean check) { - this(timeFrom, timeTo, responseTimeFrom, responseTimeTo); - if (check) { - isValid(); - } - } + public SelectedScatterArea(long timeFrom, long timeTo, int responseTimeFrom, int responseTimeTo, boolean check) { + this(timeFrom, timeTo, responseTimeFrom, responseTimeTo); + if (check) { + isValid(); + } + } - public static SelectedScatterArea createUncheckedArea(long timeFrom, long timeTo, int responseTimeFrom, int responseTimeTo) { - return new SelectedScatterArea(timeFrom, timeTo, responseTimeFrom, responseTimeTo); - } + public static SelectedScatterArea createUncheckedArea(long timeFrom, long timeTo, int responseTimeFrom, int responseTimeTo) { + return new SelectedScatterArea(timeFrom, timeTo, responseTimeFrom, responseTimeTo); + } - private void isValid() { - timeRange.validate(); - responseTimeRange.validate(); - } + private void isValid() { + timeRange.validate(); + responseTimeRange.validate(); + } - public Range getTimeRange() { - return timeRange; - } + public Range getTimeRange() { + return timeRange; + } - public ResponseTimeRange getResponseTimeRange() { - return responseTimeRange; - } + public ResponseTimeRange getResponseTimeRange() { + return responseTimeRange; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((responseTimeRange == null) ? 0 : responseTimeRange.hashCode()); - result = prime * result + ((timeRange == null) ? 0 : timeRange.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((responseTimeRange == null) ? 0 : responseTimeRange.hashCode()); + result = prime * result + ((timeRange == null) ? 0 : timeRange.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; - SelectedScatterArea other = (SelectedScatterArea) obj; - if (responseTimeRange == null) { - if (other.responseTimeRange != null) - return false; - } else if (!responseTimeRange.equals(other.responseTimeRange)) - return false; - if (timeRange == null) { - if (other.timeRange != null) - return false; - } else if (!timeRange.equals(other.timeRange)) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + SelectedScatterArea other = (SelectedScatterArea) obj; + if (responseTimeRange == null) { + if (other.responseTimeRange != null) + return false; + } else if (!responseTimeRange.equals(other.responseTimeRange)) + return false; + if (timeRange == null) { + if (other.timeRange != null) + return false; + } else if (!timeRange.equals(other.timeRange)) + return false; + return true; + } - @Override - public String toString() { - return "SelectedScatterArea [timeRange=" + timeRange + ", responseTimeRange=" + responseTimeRange + "]"; - } + @Override + public String toString() { + return "SelectedScatterArea [timeRange=" + timeRange + ", responseTimeRange=" + responseTimeRange + "]"; + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/Trace.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/Trace.java index 1fc3a6c00..15a4de5b5 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/Trace.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/Trace.java @@ -21,35 +21,35 @@ package com.navercorp.pinpoint.web.vo; */ public class Trace { - private final String transactionId; - private final long executionTime; - private final long startTime; + private final String transactionId; + private final long executionTime; + private final long startTime; - private final int exceptionCode; + private final int exceptionCode; - public Trace(String transactionId, long executionTime, long startTime, int exceptionCode) { + public Trace(String transactionId, long executionTime, long startTime, int exceptionCode) { if (transactionId == null) { throw new NullPointerException("transactionId must not be null"); } this.transactionId = transactionId; - this.executionTime = executionTime; - this.startTime = startTime; - this.exceptionCode = exceptionCode; - } + this.executionTime = executionTime; + this.startTime = startTime; + this.exceptionCode = exceptionCode; + } - public String getTransactionId() { - return transactionId; - } + public String getTransactionId() { + return transactionId; + } - public long getExecutionTime() { - return executionTime; - } + public long getExecutionTime() { + return executionTime; + } - public long getStartTime() { - return startTime; - } + public long getStartTime() { + return startTime; + } - public int getExceptionCode() { - return exceptionCode; - } + public int getExceptionCode() { + return exceptionCode; + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/TransactionId.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/TransactionId.java index 514413105..b20f2a5bb 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/TransactionId.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/TransactionId.java @@ -127,25 +127,25 @@ public class TransactionId implements Comparable { } // FIXME remove - @Override - public int compareTo(TransactionId transactionId) { - int r1 = this.agentId.compareTo(transactionId.agentId); - if (r1 == 0) { - if (this.agentStartTime > transactionId.agentStartTime) { - return 1; - } else if (this.agentStartTime < transactionId.agentStartTime) { - return -1; - } else { - if (this.transactionSequence > transactionId.transactionSequence) { - return 1; - } else if (this.transactionSequence < transactionId.transactionSequence) { - return -1; - } else { - return 0; - } - } - } else { - return r1; - } - } + @Override + public int compareTo(TransactionId transactionId) { + int r1 = this.agentId.compareTo(transactionId.agentId); + if (r1 == 0) { + if (this.agentStartTime > transactionId.agentStartTime) { + return 1; + } else if (this.agentStartTime < transactionId.agentStartTime) { + return -1; + } else { + if (this.transactionSequence > transactionId.transactionSequence) { + return 1; + } else if (this.transactionSequence < transactionId.transactionSequence) { + return -1; + } else { + return 0; + } + } + } else { + return r1; + } + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/callstacks/Record.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/callstacks/Record.java index ac4a7a471..636c37eb4 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/callstacks/Record.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/callstacks/Record.java @@ -25,62 +25,62 @@ import com.navercorp.pinpoint.common.ServiceType; * @author emeroad */ public class Record { - private final int tab; - private final int id; - private final int parentId; - private final boolean method; + private final int tab; + private final int id; + private final int parentId; + private final boolean method; - private final String title; + private final String title; private String simpleClassName = ""; private String fullApiDescription = ""; - private final String arguments; - private final long begin; - private final long elapsed; + private final String arguments; + private final long begin; + private final long elapsed; private final long gap; - private final String agent; - private final String applicationName; + private final String agent; + private final String applicationName; private final ServiceType serviceType; private final String destinationId; - private final boolean excludeFromTimeline; + private final boolean excludeFromTimeline; private boolean focused; private boolean hasChild; private boolean hasException; - public Record(int tab, int id, int parentId, boolean method, String title, String arguments, long begin, long elapsed, long gap, String agent, String applicationName, ServiceType serviceType, String destinationId, boolean hasChild, boolean hasException) { - this.tab = tab; - this.id = id; - this.parentId = parentId; - this.method = method; + public Record(int tab, int id, int parentId, boolean method, String title, String arguments, long begin, long elapsed, long gap, String agent, String applicationName, ServiceType serviceType, String destinationId, boolean hasChild, boolean hasException) { + this.tab = tab; + this.id = id; + this.parentId = parentId; + this.method = method; - this.title = title; - this.arguments = arguments; - this.begin = begin; - this.elapsed = elapsed; + this.title = title; + this.arguments = arguments; + this.begin = begin; + this.elapsed = elapsed; this.gap = gap; - this.agent = agent; + this.agent = agent; - this.applicationName = applicationName; + this.applicationName = applicationName; this.serviceType = serviceType; this.destinationId = destinationId; - this.excludeFromTimeline = serviceType == null || serviceType.isInternalMethod(); - this.hasChild = hasChild; - this.hasException = hasException; - } + this.excludeFromTimeline = serviceType == null || serviceType.isInternalMethod(); + this.hasChild = hasChild; + this.hasException = hasException; + } - public int getId() { - return id; - } + public int getId() { + return id; + } - public int getParentId() { - return parentId; - } + public int getParentId() { + return parentId; + } - public int getTab() { - return tab; - } + public int getTab() { + return tab; + } public String getTabspace() { if(tab == 0) { return ""; @@ -92,37 +92,37 @@ public class Record { return sb.toString(); } - public boolean isMethod() { - return method; - } + public boolean isMethod() { + return method; + } - public String getTitle() { + public String getTitle() { return title; - } + } - public String getArguments() { + public String getArguments() { return arguments; - } + } - public long getBegin() { - return begin; - } + public long getBegin() { + return begin; + } - public long getElapsed() { - return elapsed; - } + public long getElapsed() { + return elapsed; + } public long getGap() { return gap; } public String getAgent() { - return agent; - } + return agent; + } - public String getApplicationName() { - return applicationName; - } + public String getApplicationName() { + return applicationName; + } public String getApiType() { if (destinationId == null) { @@ -141,8 +141,8 @@ public class Record { } public boolean isExcludeFromTimeline() { - return excludeFromTimeline; - } + return excludeFromTimeline; + } public String getSimpleClassName() { return simpleClassName; @@ -169,11 +169,11 @@ public class Record { } public boolean getHasChild() { - return hasChild; + return hasChild; } public boolean getHasException() { - return hasException; + return hasException; } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/callstacks/RecordSet.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/callstacks/RecordSet.java index d3655866e..a94b16918 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/callstacks/RecordSet.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/callstacks/RecordSet.java @@ -25,17 +25,17 @@ import java.util.List; public class RecordSet { private long startTime = -1; - private long endTime = -1; + private long endTime = -1; - private List recordList; - private String applicationName; - private long beginTimestamp; + private List recordList; + private String applicationName; + private long beginTimestamp; private String agentId; private String applicationId; - public RecordSet() { - } + public RecordSet() { + } public void setRecordList(List recordList) { this.recordList = recordList; @@ -46,28 +46,28 @@ public class RecordSet { } public long getStartTime() { - return startTime; - } + return startTime; + } - public void setStartTime(long startTime) { - this.startTime = startTime; - } + public void setStartTime(long startTime) { + this.startTime = startTime; + } - public long getEndTime() { - return endTime; - } + public long getEndTime() { + return endTime; + } - public void setEndTime(long endTime) { - this.endTime = endTime; - } + public void setEndTime(long endTime) { + this.endTime = endTime; + } - public boolean isStartTimeSet() { - return startTime != -1; - } + public boolean isStartTimeSet() { + return startTime != -1; + } - public boolean isEndTimeSet() { - return endTime != -1; - } + public boolean isEndTimeSet() { + return endTime != -1; + } public void setApplicationName(String applicationName) { this.applicationName = applicationName; @@ -78,12 +78,12 @@ public class RecordSet { } public String getApplicationName() { - return applicationName; - } + return applicationName; + } - public long getBeginTimestamp() { - return beginTimestamp; - } + public long getBeginTimestamp() { + return beginTimestamp; + } public String getAgentId() { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/linechart/DownSampler.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/linechart/DownSampler.java index 578fa6818..d66ca1b85 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/linechart/DownSampler.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/linechart/DownSampler.java @@ -25,8 +25,8 @@ import java.util.Collection; */ public interface DownSampler { - long sampleLong(Collection values); - - double sampleDouble(Collection values); - + long sampleLong(Collection values); + + double sampleDouble(Collection values); + } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/linechart/DownSamplers.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/linechart/DownSamplers.java index 0f102a1ef..0fd4ce603 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/linechart/DownSamplers.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/linechart/DownSamplers.java @@ -33,14 +33,14 @@ import org.apache.commons.collections.CollectionUtils; */ public class DownSamplers { - public static final DownSampler MIN = new Min(); - public static final DownSampler MAX = new Max(); - public static final DownSampler AVG = new Avg(); + public static final DownSampler MIN = new Min(); + public static final DownSampler MAX = new Max(); + public static final DownSampler AVG = new Avg(); - private DownSamplers() { - } - - static class Min implements DownSampler { + private DownSamplers() { + } + + static class Min implements DownSampler { @Override public long sampleLong(Collection values) { @@ -58,9 +58,9 @@ public class DownSamplers { return Collections.min(values); } - } + } - static class Max implements DownSampler { + static class Max implements DownSampler { @Override public long sampleLong(Collection values) { @@ -77,9 +77,9 @@ public class DownSamplers { } return Collections.max(values); } - } + } - static class Avg implements DownSampler { + static class Avg implements DownSampler { @Override public long sampleLong(Collection values) { @@ -104,6 +104,6 @@ public class DownSamplers { } return total / values.size(); } - } + } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/scatter/Dot.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/scatter/Dot.java index da6ad3f1d..7fca20d08 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/scatter/Dot.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/scatter/Dot.java @@ -40,7 +40,7 @@ public class Dot { * @param elapsedTime * @param exceptionCode 0 : success, 1 : error */ - public Dot(TransactionId transactionId, long acceptedTime, int elapsedTime, int exceptionCode, String agentId) { + public Dot(TransactionId transactionId, long acceptedTime, int elapsedTime, int exceptionCode, String agentId) { if (transactionId == null) { throw new NullPointerException("transactionId must not be null"); } @@ -54,13 +54,13 @@ public class Dot { this.agentId = agentId; } - public String getTransactionId() { - return transactionId.getFormatString(); - } + public String getTransactionId() { + return transactionId.getFormatString(); + } - public int getExceptionCode() { - return exceptionCode; - } + public int getExceptionCode() { + return exceptionCode; + } /** * Simple stateCode used in the UI. May need to be fleshed out with state transitions in the future. @@ -76,13 +76,13 @@ public class Dot { } } - public int getElapsedTime() { - return elapsedTime; - } + public int getElapsedTime() { + return elapsedTime; + } - public long getAcceptedTime() { - return acceptedTime; - } + public long getAcceptedTime() { + return acceptedTime; + } public String getAgentId() { return agentId; diff --git a/web/src/test/java/com/navercorp/pinpoint/web/alarm/MainCategoryTest.java b/web/src/test/java/com/navercorp/pinpoint/web/alarm/MainCategoryTest.java index dd310d340..2ff8dd39b 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/alarm/MainCategoryTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/alarm/MainCategoryTest.java @@ -22,13 +22,13 @@ import org.junit.Test; public class MainCategoryTest { -// @Test -// public void getValueTest() { -// MainCategory category = MainCategory.getValue(1); -// Assert.assertEquals(MainCategory.REQUEST_SENDED, category); -// -// category = MainCategory.getValue(2); -// Assert.assertEquals(MainCategory.REQUEST_RECEIVED, category); -// } - +// @Test +// public void getValueTest() { +// MainCategory category = MainCategory.getValue(1); +// Assert.assertEquals(MainCategory.REQUEST_SENDED, category); +// +// category = MainCategory.getValue(2); +// Assert.assertEquals(MainCategory.REQUEST_RECEIVED, category); +// } + } diff --git a/web/src/test/java/com/navercorp/pinpoint/web/cluster/ClusterTest.java b/web/src/test/java/com/navercorp/pinpoint/web/cluster/ClusterTest.java index 28e0c2701..be9dde738 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/cluster/ClusterTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/cluster/ClusterTest.java @@ -44,175 +44,175 @@ import com.navercorp.pinpoint.web.server.PinpointSocketManager; public class ClusterTest { - // some tests may fail when executed in local environment - // when failures happen, you have to copy pinpoint-web.properties of resource-test to resource-local. Tests will succeed. - - private static final int DEFAULT_ACCEPTOR_PORT = 9996; - private static final int DEFAULT_ZOOKEEPER_PORT = 22213; + // some tests may fail when executed in local environment + // when failures happen, you have to copy pinpoint-web.properties of resource-test to resource-local. Tests will succeed. - private static final String DEFAULT_IP = NetUtils.getLocalV4Ip(); + private static final int DEFAULT_ACCEPTOR_PORT = 9996; + private static final int DEFAULT_ZOOKEEPER_PORT = 22213; - private static final String CLUSTER_NODE_PATH = "/pinpoint-cluster/web/" + DEFAULT_IP + ":" + DEFAULT_ACCEPTOR_PORT; + private static final String DEFAULT_IP = NetUtils.getLocalV4Ip(); - private static TestingServer ts = null; + private static final String CLUSTER_NODE_PATH = "/pinpoint-cluster/web/" + DEFAULT_IP + ":" + DEFAULT_ACCEPTOR_PORT; - static PinpointSocketManager socketManager; - - @BeforeClass - public static void setUp() throws Exception { - WebConfig config = mock(WebConfig.class); - - when(config.isClusterEnable()).thenReturn(true); - when(config.getClusterTcpPort()).thenReturn(DEFAULT_ACCEPTOR_PORT); - when(config.getClusterZookeeperAddress()).thenReturn("127.0.0.1:22213"); - when(config.getClusterZookeeperRetryInterval()).thenReturn(60000); - when(config.getClusterZookeeperSessionTimeout()).thenReturn(3000); + private static TestingServer ts = null; - socketManager = new PinpointSocketManager(config); - socketManager.start(); - - ts = createZookeeperServer(DEFAULT_ZOOKEEPER_PORT); - } + static PinpointSocketManager socketManager; - @AfterClass - public static void tearDown() throws Exception { - closeZookeeperServer(ts); - socketManager.stop(); - } + @BeforeClass + public static void setUp() throws Exception { + WebConfig config = mock(WebConfig.class); - @Before - public void before() throws IOException { - ts.stop(); - } + when(config.isClusterEnable()).thenReturn(true); + when(config.getClusterTcpPort()).thenReturn(DEFAULT_ACCEPTOR_PORT); + when(config.getClusterZookeeperAddress()).thenReturn("127.0.0.1:22213"); + when(config.getClusterZookeeperRetryInterval()).thenReturn(60000); + when(config.getClusterZookeeperSessionTimeout()).thenReturn(3000); - @Test - public void clusterTest1() throws Exception { - ts.restart(); - Thread.sleep(5000); + socketManager = new PinpointSocketManager(config); + socketManager.start(); - ZooKeeper zookeeper = new ZooKeeper("127.0.0.1:22213", 5000, null); - getNodeAndCompareContents(zookeeper); - - if (zookeeper != null) { - zookeeper.close(); - } - } + ts = createZookeeperServer(DEFAULT_ZOOKEEPER_PORT); + } - @Test - public void clusterTest2() throws Exception { - ts.restart(); - Thread.sleep(5000); + @AfterClass + public static void tearDown() throws Exception { + closeZookeeperServer(ts); + socketManager.stop(); + } - ZooKeeper zookeeper = new ZooKeeper("127.0.0.1:22213", 5000, null); - getNodeAndCompareContents(zookeeper); + @Before + public void before() throws IOException { + ts.stop(); + } - ts.stop(); + @Test + public void clusterTest1() throws Exception { + ts.restart(); + Thread.sleep(5000); - Thread.sleep(5000); - try { - zookeeper.getData(CLUSTER_NODE_PATH, null, null); - Assert.fail(); - } catch (KeeperException e) { - Assert.assertEquals(KeeperException.Code.CONNECTIONLOSS, e.code()); - // TODO Auto-generated catch block - e.printStackTrace(); - } + ZooKeeper zookeeper = new ZooKeeper("127.0.0.1:22213", 5000, null); + getNodeAndCompareContents(zookeeper); - ts.restart(); + if (zookeeper != null) { + zookeeper.close(); + } + } - getNodeAndCompareContents(zookeeper); + @Test + public void clusterTest2() throws Exception { + ts.restart(); + Thread.sleep(5000); - if (zookeeper != null) { - zookeeper.close(); - } - } + ZooKeeper zookeeper = new ZooKeeper("127.0.0.1:22213", 5000, null); + getNodeAndCompareContents(zookeeper); - @Test - public void clusterTest3() throws Exception { - ts.restart(); + ts.stop(); - PinpointSocketFactory factory = null; - PinpointSocket socket = null; - - ZooKeeper zookeeper = null; - try { - Thread.sleep(5000); + Thread.sleep(5000); + try { + zookeeper.getData(CLUSTER_NODE_PATH, null, null); + Assert.fail(); + } catch (KeeperException e) { + Assert.assertEquals(KeeperException.Code.CONNECTIONLOSS, e.code()); + // TODO Auto-generated catch block + e.printStackTrace(); + } - zookeeper = new ZooKeeper("127.0.0.1:22213", 5000, null); - getNodeAndCompareContents(zookeeper); + ts.restart(); - Assert.assertEquals(0, socketManager.getCollectorChannelContext().size()); + getNodeAndCompareContents(zookeeper); - factory = new PinpointSocketFactory(); - factory.setMessageListener(new SimpleListener()); - - socket = factory.connect(DEFAULT_IP, DEFAULT_ACCEPTOR_PORT); + if (zookeeper != null) { + zookeeper.close(); + } + } - Thread.sleep(1000); + @Test + public void clusterTest3() throws Exception { + ts.restart(); - Assert.assertEquals(1, socketManager.getCollectorChannelContext().size()); + PinpointSocketFactory factory = null; + PinpointSocket socket = null; - } finally { - closePinpointSocket(factory, socket); + ZooKeeper zookeeper = null; + try { + Thread.sleep(5000); - if (zookeeper != null) { - zookeeper.close(); - } - } - } + zookeeper = new ZooKeeper("127.0.0.1:22213", 5000, null); + getNodeAndCompareContents(zookeeper); - private static TestingServer createZookeeperServer(int port) throws Exception { - TestingServer mockZookeeperServer = new TestingServer(port); - mockZookeeperServer.start(); + Assert.assertEquals(0, socketManager.getCollectorChannelContext().size()); - return mockZookeeperServer; - } + factory = new PinpointSocketFactory(); + factory.setMessageListener(new SimpleListener()); - private static void closeZookeeperServer(TestingServer mockZookeeperServer) throws Exception { - try { - if (mockZookeeperServer != null) { - mockZookeeperServer.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } + socket = factory.connect(DEFAULT_IP, DEFAULT_ACCEPTOR_PORT); - private void getNodeAndCompareContents(ZooKeeper zookeeper) throws KeeperException, InterruptedException { - byte[] conetents = zookeeper.getData(CLUSTER_NODE_PATH, null, null); + Thread.sleep(1000); - String[] registeredIplist = new String(conetents).split("\r\n"); + Assert.assertEquals(1, socketManager.getCollectorChannelContext().size()); - List ipList = NetUtils.getLocalV4IpList(); + } finally { + closePinpointSocket(factory, socket); - Assert.assertEquals(registeredIplist.length, ipList.size()); + if (zookeeper != null) { + zookeeper.close(); + } + } + } - for (String ip : registeredIplist) { - Assert.assertTrue(ipList.contains(ip)); - } - } + private static TestingServer createZookeeperServer(int port) throws Exception { + TestingServer mockZookeeperServer = new TestingServer(port); + mockZookeeperServer.start(); - private void closePinpointSocket(PinpointSocketFactory factory, PinpointSocket socket) { - if (socket != null) { - socket.close(); - } + return mockZookeeperServer; + } - if (factory != null) { - factory.release(); - } - } + private static void closeZookeeperServer(TestingServer mockZookeeperServer) throws Exception { + try { + if (mockZookeeperServer != null) { + mockZookeeperServer.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } - class SimpleListener implements MessageListener { - @Override - public void handleSend(SendPacket sendPacket, Channel channel) { + private void getNodeAndCompareContents(ZooKeeper zookeeper) throws KeeperException, InterruptedException { + byte[] conetents = zookeeper.getData(CLUSTER_NODE_PATH, null, null); - } + String[] registeredIplist = new String(conetents).split("\r\n"); - @Override - public void handleRequest(RequestPacket requestPacket, Channel channel) { - // TODO Auto-generated method stub + List ipList = NetUtils.getLocalV4IpList(); - } - } + Assert.assertEquals(registeredIplist.length, ipList.size()); + + for (String ip : registeredIplist) { + Assert.assertTrue(ipList.contains(ip)); + } + } + + private void closePinpointSocket(PinpointSocketFactory factory, PinpointSocket socket) { + if (socket != null) { + socket.close(); + } + + if (factory != null) { + factory.release(); + } + } + + class SimpleListener implements MessageListener { + @Override + public void handleSend(SendPacket sendPacket, Channel channel) { + + } + + @Override + public void handleRequest(RequestPacket requestPacket, Channel channel) { + // TODO Auto-generated method stub + + } + } } diff --git a/web/src/test/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClusterTest.java b/web/src/test/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClusterTest.java index c50c9f635..cf3395caa 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClusterTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/cluster/zookeeper/ZookeeperClusterTest.java @@ -45,200 +45,200 @@ import com.navercorp.pinpoint.web.cluster.zookeeper.ZookeeperClusterManager; public class ZookeeperClusterTest { - private static final int DEFAULT_ACCEPTOR_PORT = 9995; - private static final int DEFAULT_ZOOKEEPER_PORT = 22213; + private static final int DEFAULT_ACCEPTOR_PORT = 9995; + private static final int DEFAULT_ZOOKEEPER_PORT = 22213; - private static final String DEFAULT_IP = NetUtils.getLocalV4Ip(); + private static final String DEFAULT_IP = NetUtils.getLocalV4Ip(); - private static final String COLLECTOR_NODE_PATH = "/pinpoint-cluster/collector"; - private static final String COLLECTOR_TEST_NODE_PATH = "/pinpoint-cluster/collector/test"; - - private static final String CLUSTER_NODE_PATH = "/pinpoint-cluster/web/" + DEFAULT_IP + ":" + DEFAULT_ACCEPTOR_PORT; + private static final String COLLECTOR_NODE_PATH = "/pinpoint-cluster/collector"; + private static final String COLLECTOR_TEST_NODE_PATH = "/pinpoint-cluster/collector/test"; - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - private static TestingServer ts = null; + private static final String CLUSTER_NODE_PATH = "/pinpoint-cluster/web/" + DEFAULT_IP + ":" + DEFAULT_ACCEPTOR_PORT; - @BeforeClass - public static void setUp() throws Exception { - ts = createZookeeperServer(DEFAULT_ZOOKEEPER_PORT); - } + private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @AfterClass - public static void tearDown() throws Exception { - closeZookeeperServer(ts); - } + private static TestingServer ts = null; - @Before - public void before() throws IOException { - ts.stop(); - } + @BeforeClass + public static void setUp() throws Exception { + ts = createZookeeperServer(DEFAULT_ZOOKEEPER_PORT); + } - // test for zookeeper agents to be registered correctly at the cluster as expected - @Test - public void clusterTest1() throws Exception { - ts.restart(); + @AfterClass + public static void tearDown() throws Exception { + closeZookeeperServer(ts); + } - ZooKeeper zookeeper = null; - ZookeeperClusterManager manager = null; - try { - zookeeper = new ZooKeeper(DEFAULT_IP + ":" + DEFAULT_ZOOKEEPER_PORT, 5000, null); - createPath(zookeeper, COLLECTOR_TEST_NODE_PATH, true); - zookeeper.setData(COLLECTOR_TEST_NODE_PATH, "a:b:1".getBytes(), -1); - - manager = new ZookeeperClusterManager(DEFAULT_IP + ":" + DEFAULT_ZOOKEEPER_PORT, 5000, 60000); - Thread.sleep(3000); + @Before + public void before() throws IOException { + ts.stop(); + } - List agentList = manager.getRegisteredAgentList("a", "b", 1L); - Assert.assertEquals(1, agentList.size()); - Assert.assertEquals("test", agentList.get(0)); + // test for zookeeper agents to be registered correctly at the cluster as expected + @Test + public void clusterTest1() throws Exception { + ts.restart(); - agentList = manager.getRegisteredAgentList("b", "c", 1L); - Assert.assertEquals(0, agentList.size()); - - zookeeper.setData(COLLECTOR_TEST_NODE_PATH, "".getBytes(), -1); - Thread.sleep(3000); + ZooKeeper zookeeper = null; + ZookeeperClusterManager manager = null; + try { + zookeeper = new ZooKeeper(DEFAULT_IP + ":" + DEFAULT_ZOOKEEPER_PORT, 5000, null); + createPath(zookeeper, COLLECTOR_TEST_NODE_PATH, true); + zookeeper.setData(COLLECTOR_TEST_NODE_PATH, "a:b:1".getBytes(), -1); - agentList = manager.getRegisteredAgentList("a", "b", 1L); - Assert.assertEquals(0, agentList.size()); - } finally { - if (zookeeper != null) { - zookeeper.close(); - } - - if (manager != null) { - manager.close(); - } - } - } - - @Test - public void clusterTest2() throws Exception { - ts.restart(); + manager = new ZookeeperClusterManager(DEFAULT_IP + ":" + DEFAULT_ZOOKEEPER_PORT, 5000, 60000); + Thread.sleep(3000); - ZooKeeper zookeeper = null; - ZookeeperClusterManager manager = null; - try { - zookeeper = new ZooKeeper(DEFAULT_IP + ":" + DEFAULT_ZOOKEEPER_PORT, 5000, null); - createPath(zookeeper, COLLECTOR_TEST_NODE_PATH, true); - zookeeper.setData(COLLECTOR_TEST_NODE_PATH, "a:b:1".getBytes(), -1); - - manager = new ZookeeperClusterManager(DEFAULT_IP + ":" + DEFAULT_ZOOKEEPER_PORT, 5000, 60000); - Thread.sleep(3000); + List agentList = manager.getRegisteredAgentList("a", "b", 1L); + Assert.assertEquals(1, agentList.size()); + Assert.assertEquals("test", agentList.get(0)); - List agentList = manager.getRegisteredAgentList("a", "b", 1L); - Assert.assertEquals(1, agentList.size()); - Assert.assertEquals("test", agentList.get(0)); + agentList = manager.getRegisteredAgentList("b", "c", 1L); + Assert.assertEquals(0, agentList.size()); - zookeeper.setData(COLLECTOR_TEST_NODE_PATH, "a:b:1\r\nc:d:2".getBytes(), -1); - Thread.sleep(3000); + zookeeper.setData(COLLECTOR_TEST_NODE_PATH, "".getBytes(), -1); + Thread.sleep(3000); + + agentList = manager.getRegisteredAgentList("a", "b", 1L); + Assert.assertEquals(0, agentList.size()); + } finally { + if (zookeeper != null) { + zookeeper.close(); + } + + if (manager != null) { + manager.close(); + } + } + } + + @Test + public void clusterTest2() throws Exception { + ts.restart(); + + ZooKeeper zookeeper = null; + ZookeeperClusterManager manager = null; + try { + zookeeper = new ZooKeeper(DEFAULT_IP + ":" + DEFAULT_ZOOKEEPER_PORT, 5000, null); + createPath(zookeeper, COLLECTOR_TEST_NODE_PATH, true); + zookeeper.setData(COLLECTOR_TEST_NODE_PATH, "a:b:1".getBytes(), -1); + + manager = new ZookeeperClusterManager(DEFAULT_IP + ":" + DEFAULT_ZOOKEEPER_PORT, 5000, 60000); + Thread.sleep(3000); + + List agentList = manager.getRegisteredAgentList("a", "b", 1L); + Assert.assertEquals(1, agentList.size()); + Assert.assertEquals("test", agentList.get(0)); + + zookeeper.setData(COLLECTOR_TEST_NODE_PATH, "a:b:1\r\nc:d:2".getBytes(), -1); + Thread.sleep(3000); - agentList = manager.getRegisteredAgentList("a", "b", 1L); - Assert.assertEquals(1, agentList.size()); - Assert.assertEquals("test", agentList.get(0)); + agentList = manager.getRegisteredAgentList("a", "b", 1L); + Assert.assertEquals(1, agentList.size()); + Assert.assertEquals("test", agentList.get(0)); - agentList = manager.getRegisteredAgentList("c", "d", 2L); - Assert.assertEquals(1, agentList.size()); - Assert.assertEquals("test", agentList.get(0)); + agentList = manager.getRegisteredAgentList("c", "d", 2L); + Assert.assertEquals(1, agentList.size()); + Assert.assertEquals("test", agentList.get(0)); - zookeeper.delete(COLLECTOR_TEST_NODE_PATH, -1); - Thread.sleep(3000); - - agentList = manager.getRegisteredAgentList("a", "b", 1L); - Assert.assertEquals(0, agentList.size()); - - agentList = manager.getRegisteredAgentList("c", "d", 2L); - Assert.assertEquals(0, agentList.size()); - } finally { - if (zookeeper != null) { - zookeeper.close(); - } - - if (manager != null) { - manager.close(); - } - } - } + zookeeper.delete(COLLECTOR_TEST_NODE_PATH, -1); + Thread.sleep(3000); - private static TestingServer createZookeeperServer(int port) throws Exception { - TestingServer mockZookeeperServer = new TestingServer(port); - mockZookeeperServer.start(); + agentList = manager.getRegisteredAgentList("a", "b", 1L); + Assert.assertEquals(0, agentList.size()); - return mockZookeeperServer; - } + agentList = manager.getRegisteredAgentList("c", "d", 2L); + Assert.assertEquals(0, agentList.size()); + } finally { + if (zookeeper != null) { + zookeeper.close(); + } - private static void closeZookeeperServer(TestingServer mockZookeeperServer) throws Exception { - try { - if (mockZookeeperServer != null) { - mockZookeeperServer.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } + if (manager != null) { + manager.close(); + } + } + } - private void getNodeAndCompareContents(ZooKeeper zookeeper) throws KeeperException, InterruptedException { - byte[] conetents = zookeeper.getData(CLUSTER_NODE_PATH, null, null); + private static TestingServer createZookeeperServer(int port) throws Exception { + TestingServer mockZookeeperServer = new TestingServer(port); + mockZookeeperServer.start(); - String[] registeredIplist = new String(conetents).split("\r\n"); + return mockZookeeperServer; + } - List ipList = NetUtils.getLocalV4IpList(); + private static void closeZookeeperServer(TestingServer mockZookeeperServer) throws Exception { + try { + if (mockZookeeperServer != null) { + mockZookeeperServer.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } - Assert.assertEquals(registeredIplist.length, ipList.size()); + private void getNodeAndCompareContents(ZooKeeper zookeeper) throws KeeperException, InterruptedException { + byte[] conetents = zookeeper.getData(CLUSTER_NODE_PATH, null, null); - for (String ip : registeredIplist) { - Assert.assertTrue(ipList.contains(ip)); - } - } + String[] registeredIplist = new String(conetents).split("\r\n"); - private void closePinpointSocket(PinpointSocketFactory factory, PinpointSocket socket) { - if (socket != null) { - socket.close(); - } + List ipList = NetUtils.getLocalV4IpList(); - if (factory != null) { - factory.release(); - } - } + Assert.assertEquals(registeredIplist.length, ipList.size()); - class SimpleListener implements MessageListener { - @Override - public void handleSend(SendPacket sendPacket, Channel channel) { + for (String ip : registeredIplist) { + Assert.assertTrue(ipList.contains(ip)); + } + } - } + private void closePinpointSocket(PinpointSocketFactory factory, PinpointSocket socket) { + if (socket != null) { + socket.close(); + } - @Override - public void handleRequest(RequestPacket requestPacket, Channel channel) { - // TODO Auto-generated method stub + if (factory != null) { + factory.release(); + } + } - } - } + class SimpleListener implements MessageListener { + @Override + public void handleSend(SendPacket sendPacket, Channel channel) { - public void createPath(ZooKeeper zookeeper, String path, boolean createEndNode) throws PinpointZookeeperException, InterruptedException, KeeperException { + } - int pos = 1; - do { - pos = path.indexOf('/', pos + 1); + @Override + public void handleRequest(RequestPacket requestPacket, Channel channel) { + // TODO Auto-generated method stub - if (pos == -1) { - pos = path.length(); - } + } + } - if (pos == path.length()) { - if (!createEndNode) { - return; - } - } + public void createPath(ZooKeeper zookeeper, String path, boolean createEndNode) throws PinpointZookeeperException, InterruptedException, KeeperException { - String subPath = path.substring(0, pos); - if (zookeeper.exists(subPath, false) != null) { - continue; - } + int pos = 1; + do { + pos = path.indexOf('/', pos + 1); - String result = zookeeper.create(subPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); - logger.info("Create path {} success.", result); - } while (pos < path.length()); - } + if (pos == -1) { + pos = path.length(); + } + + if (pos == path.length()) { + if (!createEndNode) { + return; + } + } + + String subPath = path.substring(0, pos); + if (zookeeper.exists(subPath, false) != null) { + continue; + } + + String result = zookeeper.create(subPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + logger.info("Create path {} success.", result); + } while (pos < path.length()); + } } diff --git a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/filter/PrefixFilterTest.java b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/filter/PrefixFilterTest.java index 17f166a65..184e7a9c2 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/filter/PrefixFilterTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/filter/PrefixFilterTest.java @@ -29,32 +29,32 @@ public class PrefixFilterTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Test - public void prefixInt() { + @Test + public void prefixInt() { - byte[] before = new byte[4]; + byte[] before = new byte[4]; - for (int i = 1000; i < 1100; i++) { - byte[] buffer = new byte[4]; - BytesUtils.writeVar32(i, buffer, 0); + for (int i = 1000; i < 1100; i++) { + byte[] buffer = new byte[4]; + BytesUtils.writeVar32(i, buffer, 0); - logger.debug(compare(before, buffer) + ", " + compare(buffer, before) + ", " + compare(buffer, buffer)); + logger.debug(compare(before, buffer) + ", " + compare(buffer, before) + ", " + compare(buffer, buffer)); - before = Arrays.copyOf(buffer, 4); + before = Arrays.copyOf(buffer, 4); logger.debug(Arrays.toString(buffer)); - } - } + } + } - public int compare(byte[] left, byte[] right) { - for (int i = 0, j = 0; i < left.length && j < right.length; i++, j++) { - int a = (left[i] & 0xff); - int b = (right[j] & 0xff); - if (a != b) { - return a - b; - } - } - return left.length - right.length; - } + public int compare(byte[] left, byte[] right) { + for (int i = 0, j = 0; i < left.length && j < right.length; i++, j++) { + int a = (left[i] & 0xff); + int b = (right[j] & 0xff); + if (a != b) { + return a - b; + } + } + return left.length - right.length; + } } diff --git a/web/src/test/java/com/navercorp/pinpoint/web/filter/FilterDescriptorTest.java b/web/src/test/java/com/navercorp/pinpoint/web/filter/FilterDescriptorTest.java index 1fb812f04..944d23d93 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/filter/FilterDescriptorTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/filter/FilterDescriptorTest.java @@ -32,51 +32,51 @@ import com.navercorp.pinpoint.web.filter.FilterDescriptor; * */ public class FilterDescriptorTest { - private final ObjectMapper om = new ObjectMapper(); + private final ObjectMapper om = new ObjectMapper(); - @Test - public void convert() { - StringBuilder json = new StringBuilder(); - json.append("[{"); - json.append("\"fa\" : \"FROM_APPLICATION\""); - json.append(", \"fst\" : \"FROM_APPLICATION_TYPE\""); - json.append(", \"ta\" : \"TO_APPLICATION\""); - json.append(", \"tst\" : \"TO_APPLICATION_TYPE\""); - json.append(", \"rf\" : 0"); - json.append(", \"rt\" : 1000"); - json.append(", \"ie\" : 1"); - json.append(", \"url\" : \"/**\""); - json.append("}]"); + @Test + public void convert() { + StringBuilder json = new StringBuilder(); + json.append("[{"); + json.append("\"fa\" : \"FROM_APPLICATION\""); + json.append(", \"fst\" : \"FROM_APPLICATION_TYPE\""); + json.append(", \"ta\" : \"TO_APPLICATION\""); + json.append(", \"tst\" : \"TO_APPLICATION_TYPE\""); + json.append(", \"rf\" : 0"); + json.append(", \"rt\" : 1000"); + json.append(", \"ie\" : 1"); + json.append(", \"url\" : \"/**\""); + json.append("}]"); - try { - List list = om.readValue(json.toString(), new TypeReference>() { - }); + try { + List list = om.readValue(json.toString(), new TypeReference>() { + }); - Assert.assertEquals(1, list.size()); + Assert.assertEquals(1, list.size()); - FilterDescriptor descriptor = list.get(0); + FilterDescriptor descriptor = list.get(0); - Assert.assertEquals("FROM_APPLICATION", descriptor.getFromApplicationName()); - Assert.assertEquals("FROM_APPLICATION_TYPE", descriptor.getFromServiceType()); - Assert.assertEquals("TO_APPLICATION", descriptor.getToApplicationName()); - Assert.assertEquals("TO_APPLICATION_TYPE", descriptor.getToServiceType()); - Assert.assertEquals(new Long(0L), descriptor.getResponseFrom()); - Assert.assertEquals(new Long(1000L), descriptor.getResponseTo()); - Assert.assertEquals(new Boolean(true), descriptor.getIe()); - Assert.assertEquals("/**", descriptor.getUrlPattern()); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(e.getMessage()); - } - } + Assert.assertEquals("FROM_APPLICATION", descriptor.getFromApplicationName()); + Assert.assertEquals("FROM_APPLICATION_TYPE", descriptor.getFromServiceType()); + Assert.assertEquals("TO_APPLICATION", descriptor.getToApplicationName()); + Assert.assertEquals("TO_APPLICATION_TYPE", descriptor.getToServiceType()); + Assert.assertEquals(new Long(0L), descriptor.getResponseFrom()); + Assert.assertEquals(new Long(1000L), descriptor.getResponseTo()); + Assert.assertEquals(new Boolean(true), descriptor.getIe()); + Assert.assertEquals("/**", descriptor.getUrlPattern()); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(e.getMessage()); + } + } - @Test - public void invalidJson() { - try { - om.readValue("INVALID", new TypeReference>() { - }); - Assert.fail(); - } catch (Exception e) { - } - } + @Test + public void invalidJson() { + try { + om.readValue("INVALID", new TypeReference>() { + }); + Assert.fail(); + } catch (Exception e) { + } + } } diff --git a/web/src/test/java/com/navercorp/pinpoint/web/filter/FilterHintTest.java b/web/src/test/java/com/navercorp/pinpoint/web/filter/FilterHintTest.java index 06f5defe3..6785cd3db 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/filter/FilterHintTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/filter/FilterHintTest.java @@ -30,49 +30,49 @@ import com.navercorp.pinpoint.web.filter.FilterHint; * */ public class FilterHintTest { - private final ObjectMapper om = new ObjectMapper(); + private final ObjectMapper om = new ObjectMapper(); - @Test - public void convert() { - StringBuilder json = new StringBuilder(); - json.append("{ \"TO_APPLICATION\" : [\"IP1\", 1,\"IP2\", 2], \"TO_APPLICATION2\" : [\"IP3\", 3,\"IP4\", 4] }"); + @Test + public void convert() { + StringBuilder json = new StringBuilder(); + json.append("{ \"TO_APPLICATION\" : [\"IP1\", 1,\"IP2\", 2], \"TO_APPLICATION2\" : [\"IP3\", 3,\"IP4\", 4] }"); - try { - FilterHint hint = om.readValue(json.toString(), new TypeReference() { - }); + try { + FilterHint hint = om.readValue(json.toString(), new TypeReference() { + }); - Assert.assertNotNull(hint); - Assert.assertEquals(2, hint.size()); + Assert.assertNotNull(hint); + Assert.assertEquals(2, hint.size()); - Assert.assertTrue(hint.containApplicationHint("TO_APPLICATION")); - Assert.assertTrue(hint.containApplicationHint("TO_APPLICATION2")); - Assert.assertFalse(hint.containApplicationHint("TO_APPLICATION3")); + Assert.assertTrue(hint.containApplicationHint("TO_APPLICATION")); + Assert.assertTrue(hint.containApplicationHint("TO_APPLICATION2")); + Assert.assertFalse(hint.containApplicationHint("TO_APPLICATION3")); - Assert.assertTrue(hint.containApplicationEndpoint("TO_APPLICATION", "IP1", 1)); - Assert.assertTrue(hint.containApplicationEndpoint("TO_APPLICATION", "IP2", 2)); + Assert.assertTrue(hint.containApplicationEndpoint("TO_APPLICATION", "IP1", 1)); + Assert.assertTrue(hint.containApplicationEndpoint("TO_APPLICATION", "IP2", 2)); - Assert.assertTrue(hint.containApplicationEndpoint("TO_APPLICATION2", "IP3", 3)); - Assert.assertTrue(hint.containApplicationEndpoint("TO_APPLICATION2", "IP4", 4)); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(e.getMessage()); - } - } - - @Test - public void empty() { - StringBuilder json = new StringBuilder(); - json.append("{}"); - - try { - FilterHint hint = om.readValue(json.toString(), new TypeReference() { - }); - - Assert.assertNotNull(hint); - Assert.assertTrue(hint.isEmpty()); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(e.getMessage()); - } - } + Assert.assertTrue(hint.containApplicationEndpoint("TO_APPLICATION2", "IP3", 3)); + Assert.assertTrue(hint.containApplicationEndpoint("TO_APPLICATION2", "IP4", 4)); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(e.getMessage()); + } + } + + @Test + public void empty() { + StringBuilder json = new StringBuilder(); + json.append("{}"); + + try { + FilterHint hint = om.readValue(json.toString(), new TypeReference() { + }); + + Assert.assertNotNull(hint); + Assert.assertTrue(hint.isEmpty()); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(e.getMessage()); + } + } } diff --git a/web/src/test/java/com/navercorp/pinpoint/web/path/PathTest.java b/web/src/test/java/com/navercorp/pinpoint/web/path/PathTest.java index d7baa47dd..67e8419c9 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/path/PathTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/path/PathTest.java @@ -32,53 +32,53 @@ public class PathTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); int index; - SimpleDateFormat format = new SimpleDateFormat("ss.SSS"); + SimpleDateFormat format = new SimpleDateFormat("ss.SSS"); - @Test - public void testPath() { - // root -> next1 -> next2 - // > - -> next3 + @Test + public void testPath() { + // root -> next1 -> next2 + // > - -> next3 - // Span root = root(); - // printSpan("root", root); - // - // Span next1 = createNextSpan(root); - // printSpan("next1", next1); - // - // Span next2 = createNextSpan(next1); - // printSpan("next2", next2); - // - // Span next3 = createNextSpan(next1); - // printSpan("next3", next3); + // Span root = root(); + // printSpan("root", root); + // + // Span next1 = createNextSpan(root); + // printSpan("next1", next1); + // + // Span next2 = createNextSpan(next1); + // printSpan("next2", next2); + // + // Span next3 = createNextSpan(next1); + // printSpan("next3", next3); - } + } - public void printSpan(String msg, TSpan span) { - // System.out.println(msg + " id:" + span.getSpanID() + " pid:" + - // span.getParentSpanId() + " time:" + format.format(new - // Date(span.getTimestamp()))); - logger.debug(msg + " id:" + span.getSpanId() + " pid:" + span.getParentSpanId() + " time:" + span.getStartTime()); - } - // private Span root() { - // TraceID traceID = TraceID.newTraceId(); - // UUID uuid = traceID.getTransactionSequence(); - // Span root = new Span("test", System.currentTimeMillis(), - // uuid.getMostSignificantBits(), uuid.getLeastSignificantBits(), - // Integer.toString(index++), "serviceName", traceID.getSpanId(), null, - // null, "http:ip:23"); - // root.setParentSpanId(traceID.getParentSpanId()); - // return root; - // } + public void printSpan(String msg, TSpan span) { + // System.out.println(msg + " id:" + span.getSpanID() + " pid:" + + // span.getParentSpanId() + " time:" + format.format(new + // Date(span.getTimestamp()))); + logger.debug(msg + " id:" + span.getSpanId() + " pid:" + span.getParentSpanId() + " time:" + span.getStartTime()); + } + // private Span root() { + // TraceID traceID = TraceID.newTraceId(); + // UUID uuid = traceID.getTransactionSequence(); + // Span root = new Span("test", System.currentTimeMillis(), + // uuid.getMostSignificantBits(), uuid.getLeastSignificantBits(), + // Integer.toString(index++), "serviceName", traceID.getSpanId(), null, + // null, "http:ip:23"); + // root.setParentSpanId(traceID.getParentSpanId()); + // return root; + // } - // private Span createNextSpan(Span span) { - // UUID uuid = new UUID(span.getMostTraceID(), span.getLeastTraceID()); - // TraceID traceID = new TraceID(uuid, span.getParentSpanId(), - // span.getSpanID(), true, 0); - // TraceID nextTraceId = traceID.getNextTraceId(); - // Span next = new Span("test", System.currentTimeMillis(), - // span.getMostTraceID(), span.getLeastTraceID(), Integer.toString(index++), - // "serviceName", nextTraceId.getSpanId(), null, null, "http:ip:23"); - // next.setParentSpanId(nextTraceId.getParentSpanId()); - // return next; - // } + // private Span createNextSpan(Span span) { + // UUID uuid = new UUID(span.getMostTraceID(), span.getLeastTraceID()); + // TraceID traceID = new TraceID(uuid, span.getParentSpanId(), + // span.getSpanID(), true, 0); + // TraceID nextTraceId = traceID.getNextTraceId(); + // Span next = new Span("test", System.currentTimeMillis(), + // span.getMostTraceID(), span.getLeastTraceID(), Integer.toString(index++), + // "serviceName", nextTraceId.getSpanId(), null, null, "http:ip:23"); + // next.setParentSpanId(nextTraceId.getParentSpanId()); + // return next; + // } } diff --git a/web/src/test/java/com/navercorp/pinpoint/web/vo/TransactionIdTest.java b/web/src/test/java/com/navercorp/pinpoint/web/vo/TransactionIdTest.java index 1aa88ae98..178d80d88 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/vo/TransactionIdTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/vo/TransactionIdTest.java @@ -34,59 +34,59 @@ public class TransactionIdTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Test - public void sameAll() { - TransactionId id1 = new TransactionId("A1", 1, 1); - TransactionId id2 = new TransactionId("A1", 1, 1); - Assert.assertEquals(0, id1.compareTo(id2)); - } + public void sameAll() { + TransactionId id1 = new TransactionId("A1", 1, 1); + TransactionId id2 = new TransactionId("A1", 1, 1); + Assert.assertEquals(0, id1.compareTo(id2)); + } - @Test - public void diffAgentStartTimeAsc() { - TransactionId id1 = new TransactionId("A1", 1, 1); - TransactionId id2 = new TransactionId("A1", 2, 1); - Assert.assertEquals(-1, id1.compareTo(id2)); - } + @Test + public void diffAgentStartTimeAsc() { + TransactionId id1 = new TransactionId("A1", 1, 1); + TransactionId id2 = new TransactionId("A1", 2, 1); + Assert.assertEquals(-1, id1.compareTo(id2)); + } - @Test - public void diffAgentStartTimeDesc() { - TransactionId id1 = new TransactionId("A1", 2, 1); - TransactionId id2 = new TransactionId("A1", 1, 1); - Assert.assertEquals(1, id1.compareTo(id2)); - } + @Test + public void diffAgentStartTimeDesc() { + TransactionId id1 = new TransactionId("A1", 2, 1); + TransactionId id2 = new TransactionId("A1", 1, 1); + Assert.assertEquals(1, id1.compareTo(id2)); + } - @Test - public void diffSeqAsc() { - TransactionId id1 = new TransactionId("A1", 1, 1); - TransactionId id2 = new TransactionId("A1", 1, 2); - Assert.assertEquals(-1, id1.compareTo(id2)); - } + @Test + public void diffSeqAsc() { + TransactionId id1 = new TransactionId("A1", 1, 1); + TransactionId id2 = new TransactionId("A1", 1, 2); + Assert.assertEquals(-1, id1.compareTo(id2)); + } - @Test - public void diffSeqDesc() { - TransactionId id1 = new TransactionId("A1", 1, 2); - TransactionId id2 = new TransactionId("A1", 1, 1); - Assert.assertEquals(1, id1.compareTo(id2)); - } + @Test + public void diffSeqDesc() { + TransactionId id1 = new TransactionId("A1", 1, 2); + TransactionId id2 = new TransactionId("A1", 1, 1); + Assert.assertEquals(1, id1.compareTo(id2)); + } - @Test - public void order() { - List numbers = new ArrayList(10); - for (int i = 0; i < 10; i++) { - numbers.add(i); - } - Collections.shuffle(numbers); + @Test + public void order() { + List numbers = new ArrayList(10); + for (int i = 0; i < 10; i++) { + numbers.add(i); + } + Collections.shuffle(numbers); - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - list.add(new TransactionId("A", 1, numbers.get(i))); - } + List list = new ArrayList(); + for (int i = 0; i < 10; i++) { + list.add(new TransactionId("A", 1, numbers.get(i))); + } logger.debug("{}", list); - SortedSet set = new TreeSet(list); - for (int i = 0; i < 10; i++) { - set.add(list.get(i)); - } + SortedSet set = new TreeSet(list); + for (int i = 0; i < 10; i++) { + set.add(list.get(i)); + } - logger.debug("{}", set); - } + logger.debug("{}", set); + } }