index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-slf4j/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-slf4j/src/test/java/com/amazonaws/xray/slf4j/SLF4JSegmentListenerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.slf4j;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.SegmentImpl;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.SubsegmentImpl;
import com.amazonaws.xray.entities.TraceID;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.slf4j.MDC;
public class SLF4JSegmentListenerTest {
private final TraceID traceID = TraceID.fromString("1-1-d0a73661177562839f503b9f");
private static final String TRACE_ID_KEY = "AWS-XRAY-TRACE-ID";
@Before
public void setupAWSXRay() {
Emitter blankEmitter = Mockito.mock(Emitter.class);
Mockito.doReturn(true).when(blankEmitter).sendSegment(Mockito.any());
Mockito.doReturn(true).when(blankEmitter).sendSubsegment(Mockito.any());
SLF4JSegmentListener segmentListener = new SLF4JSegmentListener();
AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder.standard()
.withEmitter(blankEmitter)
.withSegmentListener(segmentListener)
.build());
AWSXRay.clearTraceEntity();
MDC.clear();
}
@Test
public void testDefaultPrefix() {
SLF4JSegmentListener listener = (SLF4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0);
Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", traceID);
listener.onSetEntity(null, seg);
Assert.assertEquals(TRACE_ID_KEY + ": " + traceID.toString() + "@" + seg.getId(), MDC.get(TRACE_ID_KEY));
}
@Test
public void testSetPrefix() {
SLF4JSegmentListener listener = (SLF4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0);
listener.setPrefix("");
Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", traceID);
listener.onSetEntity(null, seg);
Assert.assertEquals(traceID.toString() + "@" + seg.getId(), MDC.get(TRACE_ID_KEY));
}
@Test
public void testSegmentInjection() {
SLF4JSegmentListener listener = (SLF4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0);
listener.setPrefix("");
Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", traceID);
listener.onSetEntity(null, seg);
Assert.assertEquals(traceID.toString() + "@" + seg.getId(), MDC.get(TRACE_ID_KEY));
}
@Test
public void testUnsampledSegmentInjection() {
SLF4JSegmentListener listener = (SLF4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0);
listener.setPrefix("");
Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", traceID);
seg.setSampled(false);
listener.onSetEntity(null, seg);
Assert.assertNull(MDC.get(TRACE_ID_KEY));
}
@Test
public void testSubsegmentInjection() {
SLF4JSegmentListener listener = (SLF4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0);
listener.setPrefix("");
Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", traceID);
listener.onSetEntity(null, seg);
Subsegment sub = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "test", seg);
listener.onSetEntity(seg, sub);
Assert.assertEquals(traceID.toString() + "@" + sub.getId(), MDC.get(TRACE_ID_KEY));
}
@Test
public void testNestedSubsegmentInjection() {
SLF4JSegmentListener listener = (SLF4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0);
listener.setPrefix("");
Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", traceID);
listener.onSetEntity(null, seg);
Subsegment sub1 = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "test1", seg);
listener.onSetEntity(seg, sub1);
Subsegment sub2 = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "test2", seg);
listener.onSetEntity(sub1, sub2);
Assert.assertEquals(traceID.toString() + "@" + sub2.getId(), MDC.get(TRACE_ID_KEY));
}
}
| 3,900 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-slf4j/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-slf4j/src/main/java/com/amazonaws/xray/slf4j/SLF4JSegmentListener.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.slf4j;
import com.amazonaws.xray.entities.Entity;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.StringValidator;
import com.amazonaws.xray.listeners.SegmentListener;
import org.slf4j.MDC;
/**
* Implementation of SegmentListener that's used for Trace ID injection into logs that are recorded using the SLF4J frontend API.
*
* To inject the X-Ray trace ID into your logging events, insert <code>%X{AWS-XRAY-TRACE-ID}</code> wherever you feel comfortable
* in the <code>PatternLayout</code> of your logging events. For applications that use the Logback backend for SLF4J (the default
* implementation), refer to the Logback <a href="https://logback.qos.ch/manual/layouts.html">layouts documentation</a> for how to
* do this. For applications using Log4J as their backend, refer to the Log4j
* <a href="https://logging.apache.org/log4j/2.x/manual/configuration.html">configuration documentation</a>.
*/
public class SLF4JSegmentListener implements SegmentListener {
private static final String TRACE_ID_KEY = "AWS-XRAY-TRACE-ID";
private String prefix;
/**
* Returns a default {@code SLF4JSegmentListener} using {@code AWS-XRAY-TRACE-ID} as the prefix for trace ID injections
*/
public SLF4JSegmentListener() {
this(TRACE_ID_KEY);
}
/**
* Returns a {@code SLF4JSegmentListener} using the provided prefix for trace ID injections
* @param prefix
*/
public SLF4JSegmentListener(String prefix) {
this.prefix = prefix;
}
public String getPrefix() {
return prefix;
}
/**
* Sets the trace ID injection prefix to provided value. A colon and space separate the prefix and trace ID, unless
* the {@code prefix} is null or blank.
* @param prefix
*/
public void setPrefix(String prefix) {
this.prefix = prefix;
}
/**
* Maps the AWS-XRAY-TRACE-ID key to the trace ID of the entity that's just been created in the MDC.
* Does not perform injection if entity is not available or not sampled, since then the given entity would not be displayed
* in X-Ray console.
*
* @param oldEntity the previous entity or null
* @param newEntity the new entity, either a subsegment or segment
*/
@Override
public void onSetEntity(Entity oldEntity, Entity newEntity) {
if (newEntity == null) {
MDC.remove(TRACE_ID_KEY);
return;
}
Segment segment = newEntity instanceof Segment ? ((Segment) newEntity) : newEntity.getParentSegment();
if (segment != null && segment.getTraceId() != null && segment.isSampled() && newEntity.getId() != null) {
String fullPrefix = StringValidator.isNullOrBlank(this.prefix) ? "" : this.prefix + ": ";
MDC.put(TRACE_ID_KEY, fullPrefix + segment.getTraceId() + "@" + newEntity.getId());
} else {
MDC.remove(TRACE_ID_KEY); // Ensure traces don't spill over to unlinked messages
}
}
/**
* Removes the AWS-XRAY-TRACE-ID key from the MDC upon the completion of each segment.
*
* @param entity
* The segment that has just ended
*/
@Override
public void onClearEntity(Entity entity) {
MDC.remove(TRACE_ID_KEY);
}
}
| 3,901 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-apache-http/src/test/java/com/amazonaws/xray/proxies/apache | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-apache-http/src/test/java/com/amazonaws/xray/proxies/apache/http/HttpClientBuilderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.proxies.apache.http;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import com.amazonaws.xray.emitters.Emitter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class HttpClientBuilderTest {
@BeforeEach
void setupAWSXRay() {
// Prevent accidental publish to Daemon
Emitter blankEmitter = Mockito.mock(Emitter.class);
Mockito.doReturn(true).when(blankEmitter).sendSegment(Mockito.anyObject());
Mockito.doReturn(true).when(blankEmitter).sendSubsegment(Mockito.anyObject());
AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder.standard().withEmitter(blankEmitter).build());
AWSXRay.clearTraceEntity();
}
@Test
void testConstructorProtected() throws NoSuchMethodException {
// Since the constructor is protected and this is in the same package, we have to test this using reflection.
Constructor clientBuilderConstructor = HttpClientBuilder.class.getDeclaredConstructor();
Assertions.assertEquals(Modifier.PROTECTED, clientBuilderConstructor.getModifiers()); // PROTECTED = 4;
}
}
| 3,902 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-apache-http/src/test/java/com/amazonaws/xray/proxies/apache | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-apache-http/src/test/java/com/amazonaws/xray/proxies/apache/http/TracedResponseHandlerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.proxies.apache.http;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ResponseHandler;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class TracedResponseHandlerTest {
@BeforeEach
void setupAWSXRay() {
Emitter blankEmitter = Mockito.mock(Emitter.class);
Mockito.doReturn(true).when(blankEmitter).sendSegment(Mockito.anyObject());
Mockito.doReturn(true).when(blankEmitter).sendSubsegment(Mockito.anyObject());
AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder.standard().withEmitter(blankEmitter).build());
AWSXRay.clearTraceEntity();
}
@Test
void testHandleResponse200SetsNoFlags() {
Segment segment = segmentInResponseToCode(200);
Subsegment subsegment = segment.getSubsegments().get(0);
Assertions.assertFalse(subsegment.isFault());
Assertions.assertFalse(subsegment.isError());
Assertions.assertFalse(subsegment.isThrottle());
}
@Test
void testHandleResponse400SetsErrorFlag() {
Segment segment = segmentInResponseToCode(400);
Subsegment subsegment = segment.getSubsegments().get(0);
Assertions.assertFalse(subsegment.isFault());
Assertions.assertTrue(subsegment.isError());
Assertions.assertFalse(subsegment.isThrottle());
}
@Test
void testHandleResponse429SetsErrorAndThrottleFlag() {
Segment segment = segmentInResponseToCode(429);
Subsegment subsegment = segment.getSubsegments().get(0);
Assertions.assertFalse(subsegment.isFault());
Assertions.assertTrue(subsegment.isError());
Assertions.assertTrue(subsegment.isThrottle());
}
@Test
void testHandleResponse500SetsFaultFlag() {
Segment segment = segmentInResponseToCode(500);
Subsegment subsegment = segment.getSubsegments().get(0);
Assertions.assertTrue(subsegment.isFault());
Assertions.assertFalse(subsegment.isError());
Assertions.assertFalse(subsegment.isThrottle());
}
private static class NoOpResponseHandler implements ResponseHandler<String> {
@Override
public String handleResponse(HttpResponse response) {
return "no-op";
}
}
private Segment segmentInResponseToCode(int code) {
NoOpResponseHandler responseHandler = new NoOpResponseHandler();
TracedResponseHandler<String> tracedResponseHandler = new TracedResponseHandler<>(responseHandler);
HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, code, ""));
Segment segment = AWSXRay.beginSegment("test");
AWSXRay.beginSubsegment("someHttpCall");
try {
tracedResponseHandler.handleResponse(httpResponse);
} catch (IOException e) {
throw new RuntimeException(e);
}
AWSXRay.endSubsegment();
AWSXRay.endSegment();
return segment;
}
}
| 3,903 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-apache-http/src/test/java/com/amazonaws/xray/proxies/apache | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-apache-http/src/test/java/com/amazonaws/xray/proxies/apache/http/TracedHttpClientTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.proxies.apache.http;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.ok;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.entities.TraceID;
import com.github.tomakehurst.wiremock.junit.WireMockClassRule;
import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHttpRequest;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
public class TracedHttpClientTest {
@ClassRule
public static WireMockClassRule server = new WireMockClassRule(wireMockConfig().dynamicPort());
private CloseableHttpClient client;
@Before
public void setUpClient() {
client = new TracedHttpClient(HttpClients.createDefault());
}
@Test
public void testGetUrlHttpUriRequest() {
assertThat(TracedHttpClient.getUrl(new HttpGet("http://amazon.com")), is("http://amazon.com"));
assertThat(TracedHttpClient.getUrl(new HttpGet("https://docs.aws.amazon.com/xray/latest/devguide/xray-api.html")), is("https://docs.aws.amazon.com/xray/latest/devguide/xray-api.html"));
assertThat(TracedHttpClient.getUrl(new HttpGet("https://localhost:8443/api/v1")), is("https://localhost:8443/api/v1"));
}
@Test
public void testGetUrlHttpHostHttpRequest() {
assertThat(TracedHttpClient.getUrl(new HttpHost("amazon.com"), new BasicHttpRequest("GET", "/")), is("http://amazon.com/"));
assertThat(TracedHttpClient.getUrl(new HttpHost("amazon.com", -1, "https"), new BasicHttpRequest("GET", "/")), is("https://amazon.com/"));
assertThat(TracedHttpClient.getUrl(new HttpHost("localhost", 8080), new BasicHttpRequest("GET", "/api/v1")), is("http://localhost:8080/api/v1"));
assertThat(TracedHttpClient.getUrl(new HttpHost("localhost", 8443, "https"), new BasicHttpRequest("GET", "/api/v1")), is("https://localhost:8443/api/v1"));
assertThat(TracedHttpClient.getUrl(new HttpHost("amazon.com", -1, "https"), new BasicHttpRequest("GET", "https://docs.aws.amazon.com/xray/latest/devguide/xray-api.html")), is("https://docs.aws.amazon.com/xray/latest/devguide/xray-api.html"));
}
@Test
public void normalPropagation() throws Exception {
stubFor(any(anyUrl()).willReturn(ok()));
TraceID traceID = TraceID.fromString("1-67891233-abcdef012345678912345678");
Segment segment = AWSXRay.beginSegment("test", traceID, null);
client.execute(new HttpGet(server.baseUrl())).close();
AWSXRay.endSegment();
Subsegment subsegment = segment.getSubsegments().get(0);
verify(getRequestedFor(urlPathEqualTo("/"))
.withHeader(TraceHeader.HEADER_KEY,
equalTo("Root=1-67891233-abcdef012345678912345678;Parent=" + subsegment.getId() + ";Sampled=1")));
}
@Test
public void unsampledPropagation() throws Exception {
stubFor(any(anyUrl()).willReturn(ok()));
AWSXRay.getGlobalRecorder().beginNoOpSegment();
client.execute(new HttpGet(server.baseUrl())).close();
AWSXRay.endSegment();
verify(getRequestedFor(urlPathEqualTo("/"))
.withHeader(TraceHeader.HEADER_KEY,
equalTo("Root=1-00000000-000000000000000000000000;Sampled=0")));
}
@Test
public void unsampledButForcedPropagation() throws Exception {
stubFor(any(anyUrl()).willReturn(ok()));
TraceID traceID = TraceID.fromString("1-67891233-abcdef012345678912345678");
Segment segment = AWSXRay.beginSegment("test", traceID, null);
segment.setSampled(false);
client.execute(new HttpGet(server.baseUrl())).close();
AWSXRay.endSegment();
verify(getRequestedFor(urlPathEqualTo("/"))
.withHeader(TraceHeader.HEADER_KEY,
equalTo("Root=1-67891233-abcdef012345678912345678;Sampled=0")));
}
@Test
public void testExceptionOnRelativeUrl() throws Exception {
stubFor(any(anyUrl()).willReturn(ok()));
TraceID traceID = TraceID.fromString("1-67891233-abcdef012345678912345678");
AWSXRay.beginSegment("test", traceID, null);
Exception exception = assertThrows(ClientProtocolException.class, () -> {
client.execute(new HttpGet("/hello/world/"));
});
AWSXRay.endSegment();
String expectedMessage = "URI does not specify a valid host name:";
String actualMessage = exception.getMessage();
assertTrue(actualMessage.contains(expectedMessage));
}
}
| 3,904 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-apache-http/src/main/java/com/amazonaws/xray/proxies/apache | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-apache-http/src/main/java/com/amazonaws/xray/proxies/apache/http/HttpClientBuilder.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.proxies.apache.http;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import org.apache.http.impl.client.CloseableHttpClient;
/**
* Wraps and overrides some of {@code org.apache.http.impl.client.HttpClientBuilder}'s methods. Will build a TracedHttpClient
* wrapping the usual CloseableHttpClient result. Uses the global recorder by default, with an option to provide an alternative.
*/
public class HttpClientBuilder extends org.apache.http.impl.client.HttpClientBuilder {
private AWSXRayRecorder recorder;
protected HttpClientBuilder() {
super();
}
public static HttpClientBuilder create() {
HttpClientBuilder newBuilder = new HttpClientBuilder();
newBuilder.setRecorder(AWSXRay.getGlobalRecorder());
return newBuilder;
}
public HttpClientBuilder setRecorder(AWSXRayRecorder recorder) {
this.recorder = recorder;
return this;
}
@Override
public CloseableHttpClient build() {
CloseableHttpClient result = super.build();
return new TracedHttpClient(result, recorder);
}
}
| 3,905 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-apache-http/src/main/java/com/amazonaws/xray/proxies/apache | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-apache-http/src/main/java/com/amazonaws/xray/proxies/apache/http/TracedResponseHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.proxies.apache.http;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.entities.Subsegment;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
/**
* Wraps an instance of {@code org.apache.http.client.ResponseHandler} and adds response information to the current subsegment.
*
*/
public class TracedResponseHandler<T> implements ResponseHandler<T> {
private final ResponseHandler<T> wrappedHandler;
public TracedResponseHandler(ResponseHandler<T> wrappedHandler) {
this.wrappedHandler = wrappedHandler;
}
public static void addResponseInformation(Subsegment subsegment, HttpResponse response) {
if (null == subsegment) {
return;
}
Map<String, Object> responseInformation = new HashMap<>();
int responseCode = response.getStatusLine().getStatusCode();
switch (responseCode / 100) {
case 4:
subsegment.setError(true);
if (429 == responseCode) {
subsegment.setThrottle(true);
}
break;
case 5:
subsegment.setFault(true);
break;
default:
}
responseInformation.put("status", responseCode);
if (null != response.getEntity()) {
responseInformation.put("content_length", response.getEntity().getContentLength());
}
subsegment.putHttp("response", responseInformation);
}
@Override
public T handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
T handled = wrappedHandler.handleResponse(response);
Subsegment currentSubsegment = AWSXRay.getCurrentSubsegment();
if (null != currentSubsegment) {
TracedResponseHandler.addResponseInformation(currentSubsegment, response);
}
return handled;
}
}
| 3,906 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-apache-http/src/main/java/com/amazonaws/xray/proxies/apache | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-apache-http/src/main/java/com/amazonaws/xray/proxies/apache/http/DefaultHttpClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.proxies.apache.http;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.entities.Subsegment;
import java.io.IOException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.protocol.HttpContext;
/**
* @deprecated Apache 4.3
*
* Wraps and overrides {@code org.apache.http.impl.client.DefaultHttpClient}'s execute() methods. Accesses the global recorder
* upon each invocation to generate {@code Segment}s.
*
* Only overrides those signatures which directly invoke doExecute. Other execute() signatures are wrappers which call these
* overridden methods.
*
*/
@Deprecated
public class DefaultHttpClient extends org.apache.http.impl.client.DefaultHttpClient {
private AWSXRayRecorder getRecorder() {
return AWSXRay.getGlobalRecorder();
}
@Override
public CloseableHttpResponse execute(
HttpHost target, HttpRequest request, HttpContext context) throws IOException, ClientProtocolException {
Subsegment subsegment = getRecorder().beginSubsegment(target.getHostName());
try {
TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(target, request));
CloseableHttpResponse response = super.execute(target, request, context);
TracedResponseHandler.addResponseInformation(subsegment, response);
return response;
} catch (Exception e) {
subsegment.addException(e);
throw e;
} finally {
getRecorder().endSubsegment();
}
}
@Override
public CloseableHttpResponse execute(
HttpUriRequest request, HttpContext context) throws IOException, ClientProtocolException {
Subsegment subsegment = getRecorder().beginSubsegment(TracedHttpClient.determineTarget(request).getHostName());
try {
TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(request));
CloseableHttpResponse response = super.execute(request, context);
TracedResponseHandler.addResponseInformation(subsegment, response);
return response;
} catch (Exception e) {
subsegment.addException(e);
throw e;
} finally {
getRecorder().endSubsegment();
}
}
@Override
public CloseableHttpResponse execute(HttpHost target, HttpRequest request) throws IOException, ClientProtocolException {
Subsegment subsegment = getRecorder().beginSubsegment(target.getHostName());
try {
TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(target, request));
CloseableHttpResponse response = super.execute(target, request);
TracedResponseHandler.addResponseInformation(subsegment, response);
return response;
} catch (Exception e) {
subsegment.addException(e);
throw e;
} finally {
getRecorder().endSubsegment();
}
}
}
| 3,907 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-apache-http/src/main/java/com/amazonaws/xray/proxies/apache | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-apache-http/src/main/java/com/amazonaws/xray/proxies/apache/http/TracedHttpClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.proxies.apache.http;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.entities.Namespace;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.TraceHeader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
@SuppressWarnings("deprecation")
public class TracedHttpClient extends CloseableHttpClient {
private final CloseableHttpClient wrappedClient;
private final AWSXRayRecorder recorder;
/**
* Constructs a TracedHttpClient instance using the provided client and global recorder.
*
* @param wrappedClient
* the HTTP client to wrap
*/
public TracedHttpClient(final CloseableHttpClient wrappedClient) {
this(wrappedClient, AWSXRay.getGlobalRecorder());
}
/**
* Constructs a TracedHttpClient instance using the provided client and provided recorder.
*
* @param wrappedClient
* the HTTP client to wrap
* @param recorder
* the recorder instance to use when generating subsegments around calls made by {@code wrappedClient}
*/
public TracedHttpClient(
final CloseableHttpClient wrappedClient,
AWSXRayRecorder recorder) {
this.wrappedClient = wrappedClient;
this.recorder = recorder;
}
public static HttpHost determineTarget(final HttpUriRequest request) throws ClientProtocolException {
final URI requestUri = request.getURI();
HttpHost target = URIUtils.extractHost(requestUri);
if (target == null) {
throw new ClientProtocolException("URI does not specify a valid host name: "
+ requestUri);
}
return target;
}
public static String getUrl(HttpUriRequest request) {
return request.getURI().toString();
}
public static String getUrl(HttpHost target, HttpRequest request) {
String uri = request.getRequestLine().getUri();
try {
URI requestUri = new URI(uri);
if (requestUri.isAbsolute()) {
return requestUri.toString();
}
} catch (URISyntaxException ex) {
// Not a valid URI
}
return target.toURI() + uri;
}
public static void addRequestInformation(Subsegment subsegment, HttpRequest request, String url) {
subsegment.setNamespace(Namespace.REMOTE.toString());
Segment parentSegment = subsegment.getParentSegment();
if (subsegment.shouldPropagate()) {
request.addHeader(TraceHeader.HEADER_KEY, TraceHeader.fromEntity(subsegment).toString());
}
Map<String, Object> requestInformation = new HashMap<>();
requestInformation.put("url", url);
requestInformation.put("method", request.getRequestLine().getMethod());
subsegment.putHttp("request", requestInformation);
}
@FunctionalInterface
public interface HttpSupplier<R> { //Necessary to define a get() method that may throw checked exceptions
R get() throws IOException, ClientProtocolException;
}
private <R> R wrapHttpSupplier(Subsegment subsegment, HttpSupplier<R> supplier) throws IOException, ClientProtocolException {
try {
return supplier.get();
} catch (Exception e) {
if (null != subsegment) {
subsegment.addException(e);
}
throw e;
} finally {
if (null != subsegment) {
recorder.endSubsegment();
}
}
}
@Override
public CloseableHttpResponse execute(
final HttpHost target,
final HttpRequest request,
final HttpContext context) throws IOException, ClientProtocolException {
Subsegment subsegment = recorder.beginSubsegment(target.getHostName());
return wrapHttpSupplier(
subsegment, () -> {
TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(target, request));
CloseableHttpResponse response = wrappedClient.execute(target, request, context);
TracedResponseHandler.addResponseInformation(subsegment, response);
return response;
});
}
@Override
public CloseableHttpResponse execute(
final HttpUriRequest request,
final HttpContext context) throws IOException, ClientProtocolException {
Subsegment subsegment = recorder.beginSubsegment(determineTarget(request).getHostName());
return wrapHttpSupplier(
subsegment, () -> {
TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(request));
CloseableHttpResponse response = wrappedClient.execute(request, context);
TracedResponseHandler.addResponseInformation(subsegment, response);
return response;
});
}
@Override
public CloseableHttpResponse execute(
final HttpUriRequest request) throws IOException, ClientProtocolException {
Subsegment subsegment = recorder.beginSubsegment(determineTarget(request).getHostName());
return wrapHttpSupplier(
subsegment, () -> {
TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(request));
CloseableHttpResponse response = wrappedClient.execute(request);
TracedResponseHandler.addResponseInformation(subsegment, response);
return response;
});
}
@Override
public CloseableHttpResponse execute(
final HttpHost target,
final HttpRequest request) throws IOException, ClientProtocolException {
Subsegment subsegment = recorder.beginSubsegment(target.getHostName());
return wrapHttpSupplier(
subsegment, () -> {
TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(target, request));
CloseableHttpResponse response = wrappedClient.execute(target, request);
TracedResponseHandler.addResponseInformation(subsegment, response);
return response;
});
}
@Override
public <T> T execute(final HttpUriRequest request,
final ResponseHandler<? extends T> responseHandler) throws IOException,
ClientProtocolException {
Subsegment subsegment = recorder.beginSubsegment(determineTarget(request).getHostName());
return wrapHttpSupplier(subsegment, () -> {
TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(request));
TracedResponseHandler<? extends T> wrappedHandler = new TracedResponseHandler<>(responseHandler);
return wrappedClient.execute(request, wrappedHandler);
});
}
@Override
public <T> T execute(final HttpUriRequest request,
final ResponseHandler<? extends T> responseHandler, final HttpContext context)
throws IOException, ClientProtocolException {
Subsegment subsegment = recorder.beginSubsegment(determineTarget(request).getHostName());
return wrapHttpSupplier(
subsegment, () -> {
TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(request));
TracedResponseHandler<? extends T> wrappedHandler = new TracedResponseHandler<>(responseHandler);
return wrappedClient.execute(request, wrappedHandler, context);
});
}
@Override
public <T> T execute(final HttpHost target, final HttpRequest request,
final ResponseHandler<? extends T> responseHandler) throws IOException,
ClientProtocolException {
Subsegment subsegment = recorder.beginSubsegment(target.getHostName());
return wrapHttpSupplier(
subsegment, () -> {
TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(target, request));
TracedResponseHandler<? extends T> wrappedHandler = new TracedResponseHandler<>(responseHandler);
return wrappedClient.execute(target, request, wrappedHandler);
});
}
@Override
public <T> T execute(final HttpHost target, final HttpRequest request,
final ResponseHandler<? extends T> responseHandler, final HttpContext context)
throws IOException, ClientProtocolException {
Subsegment subsegment = recorder.beginSubsegment(target.getHostName());
return wrapHttpSupplier(
subsegment, () -> {
TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(target, request));
TracedResponseHandler<? extends T> wrappedHandler = new TracedResponseHandler<>(responseHandler);
return wrappedClient.execute(target, request, wrappedHandler, context);
});
}
@Override
public ClientConnectionManager getConnectionManager() {
return wrappedClient.getConnectionManager();
}
@Override
public HttpParams getParams() {
return wrappedClient.getParams();
}
@Override
public void close() throws IOException {
wrappedClient.close();
}
@Override
protected CloseableHttpResponse doExecute(
HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext) throws IOException, ClientProtocolException {
// gross hack to call the wrappedClient's doExecute...
// see line 67 of Apache's CloseableHttpClient
return wrappedClient.execute(httpHost, httpRequest, httpContext);
}
}
| 3,908 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql-mysql/src/test/java/com/amazonaws/xray/sql | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql-mysql/src/test/java/com/amazonaws/xray/sql/mysql/SanitizeTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.sql.mysql;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.JVM)
public class SanitizeTest {
public String[] queries = {
"a",
"test 'asdf'",
"test 'aaaaaaaa''aaaaaa'",
"test 'aasdfasd' 'a' 'b'",
"test ''",
"test 'zz''''zz' ooo'aaa''aa'",
"test 544 3456 43 '43' 345f",
"test \"32f\" '32' 32",
"test 'abcd'''",
"now 'aabbccdd'''",
"now 'aabbccdd\'\''",
"now 'aabbccdd\'\''''",
"now 'aabbccdd\'\''''",
"now 'aabbccdd''\\''''"
};
public String[] sanitized = {
"a",
"test ?",
"test ?",
"test ? ? ?",
"test ?",
"test ? ooo?",
"test ? ? ? ? 345f",
"test ? ? ?",
"test ?",
"now ?",
"now ?",
"now ?",
"now ?",
"now ?"
};
/*@Test
public void testSanitizeQuery() {
for (int i = 0; i < queries.length; i++) {
Assert.assertEquals("Sanitizing: " + queries[i], sanitized[i], TracingInterceptor.sanitizeSql(queries[i]));
}
}*/
/*@Test
public void testVeryLongString() {
String delimiter = "$a$";
StringBuilder mega = new StringBuilder();
for (int i = 0; i < 1000000; i++) { // ten million copies
mega.append("Fkwekfjb2k3hf4@#$'fbb4kbf'$4'fbf''4$'");
}
String veryLong = "test " + delimiter + mega.toString() + delimiter;
Assert.assertEquals("test ?", TracingInterceptor.sanitizeSql(veryLong));
}*/
}
| 3,909 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql-mysql/src/main/java/com/amazonaws/xray/sql | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql-mysql/src/main/java/com/amazonaws/xray/sql/mysql/TracingInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.sql.mysql;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.entities.Namespace;
import com.amazonaws.xray.entities.Subsegment;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.jdbc.pool.ConnectionPool;
import org.apache.tomcat.jdbc.pool.JdbcInterceptor;
import org.apache.tomcat.jdbc.pool.PooledConnection;
/*
* Inspired by: http://grepcode.com/file/repo1.maven.org/maven2/org.apache.tomcat/tomcat-jdbc/8.0.24/org/apache/tomcat/jdbc/pool/interceptor/AbstractQueryReport.java#AbstractQueryReport
*/
public class TracingInterceptor extends JdbcInterceptor {
protected static final String CREATE_STATEMENT = "createStatement";
protected static final int CREATE_STATEMENT_INDEX = 0;
protected static final String PREPARE_STATEMENT = "prepareStatement";
protected static final int PREPARE_STATEMENT_INDEX = 1;
protected static final String PREPARE_CALL = "prepareCall";
protected static final int PREPARE_CALL_INDEX = 2;
protected static final String[] STATEMENT_TYPES = {CREATE_STATEMENT, PREPARE_STATEMENT, PREPARE_CALL};
protected static final int STATEMENT_TYPE_COUNT = STATEMENT_TYPES.length;
protected static final String EXECUTE = "execute";
protected static final String EXECUTE_QUERY = "executeQuery";
protected static final String EXECUTE_UPDATE = "executeUpdate";
protected static final String EXECUTE_BATCH = "executeBatch";
protected static final String[] EXECUTE_TYPES = {EXECUTE, EXECUTE_QUERY, EXECUTE_UPDATE, EXECUTE_BATCH};
/**
* @deprecated For internal use only.
*/
@SuppressWarnings("checkstyle:ConstantName")
@Deprecated
protected static final Constructor<?>[] constructors =
new Constructor[STATEMENT_TYPE_COUNT];
private static final Log logger =
LogFactory.getLog(TracingInterceptor.class);
private static final String DEFAULT_DATABASE_NAME = "database";
/**
* Creates a constructor for a proxy class, if one doesn't already exist
*
* @param index - the index of the constructor
* @param clazz - the interface that the proxy will implement
* @return - returns a constructor used to create new instances
* @throws NoSuchMethodException
*/
protected Constructor<?> getConstructor(int index, Class<?> clazz) throws NoSuchMethodException {
if (constructors[index] == null) {
Class<?> proxyClass = Proxy.getProxyClass(TracingInterceptor.class.getClassLoader(), new Class[] {clazz});
constructors[index] = proxyClass.getConstructor(new Class[] {InvocationHandler.class});
}
return constructors[index];
}
public Object createStatement(Object proxy, Method method, Object[] args, Object statementObject) {
try {
String name = method.getName();
String sql = null;
Constructor<?> constructor = null;
Map<String, Object> additionalParams = new HashMap<>();
if (compare(CREATE_STATEMENT, name)) {
//createStatement
constructor = getConstructor(CREATE_STATEMENT_INDEX, Statement.class);
} else if (compare(PREPARE_STATEMENT, name)) {
additionalParams.put("preparation", "statement");
sql = (String) args[0];
constructor = getConstructor(PREPARE_STATEMENT_INDEX, PreparedStatement.class);
} else if (compare(PREPARE_CALL, name)) {
additionalParams.put("preparation", "call");
sql = (String) args[0];
constructor = getConstructor(PREPARE_CALL_INDEX, CallableStatement.class);
} else {
//do nothing, might be a future unsupported method
//so we better bail out and let the system continue
return statementObject;
}
Statement statement = ((Statement) statementObject);
Connection connection = statement.getConnection();
DatabaseMetaData metadata = connection.getMetaData();
// parse cname for subsegment name
additionalParams.put("url", metadata.getURL());
additionalParams.put("user", metadata.getUserName());
additionalParams.put("driver_version", metadata.getDriverVersion());
additionalParams.put("database_type", metadata.getDatabaseProductName());
additionalParams.put("database_version", metadata.getDatabaseProductVersion());
String hostname = DEFAULT_DATABASE_NAME;
try {
URI normalizedUri = new URI(new URI(metadata.getURL()).getSchemeSpecificPart());
hostname = connection.getCatalog() + "@" + normalizedUri.getHost();
} catch (URISyntaxException e) {
logger.warn("Unable to parse database URI. Falling back to default '" + DEFAULT_DATABASE_NAME
+ "' for subsegment name.", e);
}
logger.debug("Instantiating new statement proxy.");
return constructor.newInstance(new TracingStatementProxy(statement, sql, hostname, additionalParams));
} catch (SQLException | InstantiationException | IllegalAccessException | InvocationTargetException |
NoSuchMethodException e) {
logger.warn("Unable to create statement proxy for tracing.", e);
}
return statementObject;
}
protected class TracingStatementProxy implements InvocationHandler {
protected boolean closed = false;
protected Object delegate;
protected final String query;
protected final String hostname;
protected Map<String, Object> additionalParams;
public TracingStatementProxy(Object parent, String query, String hostname, Map<String, Object> additionalParams) {
this.delegate = parent;
this.query = query;
this.hostname = hostname;
this.additionalParams = additionalParams;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//get the name of the method for comparison
final String name = method.getName();
//was close invoked?
boolean close = compare(JdbcInterceptor.CLOSE_VAL, name);
//allow close to be called multiple times
if (close && closed) {
return null;
}
//are we calling isClosed?
if (compare(JdbcInterceptor.ISCLOSED_VAL, name)) {
return Boolean.valueOf(closed);
}
//if we are calling anything else, bail out
if (closed) {
throw new SQLException("Statement closed.");
}
//check to see if we are about to execute a query
final boolean process = isExecute(method);
Object result = null;
Subsegment subsegment = null;
if (process) {
subsegment = AWSXRay.beginSubsegment(hostname);
}
try {
if (process && null != subsegment) {
subsegment.putAllSql(additionalParams);
subsegment.setNamespace(Namespace.REMOTE.toString());
}
result = method.invoke(delegate, args); //execute the query
} catch (Throwable t) {
if (null != subsegment) {
subsegment.addException(t);
}
if (t instanceof InvocationTargetException && t.getCause() != null) {
throw t.getCause();
} else {
throw t;
}
} finally {
if (process && null != subsegment) {
AWSXRay.endSubsegment();
}
}
//perform close cleanup
if (close) {
closed = true;
delegate = null;
}
return result;
}
}
/**
* {@inheritDoc}
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (compare(CLOSE_VAL, method)) {
return super.invoke(proxy, method, args);
} else {
boolean process = isStatement(method);
if (process) {
Object statement = super.invoke(proxy, method, args);
return createStatement(proxy, method, args, statement);
} else {
return super.invoke(proxy, method, args);
}
}
}
private boolean isStatement(Method method) {
return isMemberOf(STATEMENT_TYPES, method);
}
private boolean isExecute(Method method) {
return isMemberOf(EXECUTE_TYPES, method);
}
protected boolean isMemberOf(String[] names, Method method) {
boolean member = false;
final String name = method.getName();
for (int i = 0; !member && i < names.length; i++) {
member = compare(names[i], name);
}
return member;
}
@Override
public void reset(ConnectionPool parent, PooledConnection con) {
//do nothing
}
}
| 3,910 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/test/java/com/amazonaws/xray/utils/StringTransformTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.utils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class StringTransformTest {
@Test
void testToSnakeCase() {
Assertions.assertEquals("table_name", StringTransform.toSnakeCase("tableName"));
Assertions.assertEquals("consumed_capacity", StringTransform.toSnakeCase("ConsumedCapacity"));
Assertions.assertEquals("item_collection_metrics", StringTransform.toSnakeCase("ItemCollectionMetrics"));
}
@Test
void testToSnakeCaseNoExtraUnderscores() {
Assertions.assertEquals("table_name", StringTransform.toSnakeCase("table_name"));
}
}
| 3,911 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/test/java/com/amazonaws/xray/handlers | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/test/java/com/amazonaws/xray/handlers/config/AWSServiceHandlerManifestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.handlers.config;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import java.net.URL;
import java.util.HashSet;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.mockito.runners.MockitoJUnitRunner;
@FixMethodOrder(MethodSorters.JVM)
@RunWith(MockitoJUnitRunner.class)
public class AWSServiceHandlerManifestTest {
private static URL testParameterWhitelist =
AWSServiceHandlerManifestTest.class.getResource("/com/amazonaws/xray/handlers/config/OperationParameterWhitelist.json");
private ObjectMapper mapper = new ObjectMapper()
.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
@Test
public void testOperationRequestDescriptors() throws Exception {
AWSServiceHandlerManifest serviceManifest = mapper.readValue(testParameterWhitelist, AWSServiceHandlerManifest.class);
AWSOperationHandlerManifest operationManifest = serviceManifest.getOperationHandlerManifest("DynamoDb");
AWSOperationHandler operationHandler = operationManifest.getOperationHandler("BatchGetItem");
AWSOperationHandlerRequestDescriptor descriptor = operationHandler.getRequestDescriptors().get("RequestItems");
Assert.assertEquals(true, descriptor.isMap());
Assert.assertEquals(false, descriptor.isList());
Assert.assertEquals(true, descriptor.shouldGetKeys());
Assert.assertEquals(false, descriptor.shouldGetCount());
Assert.assertEquals("table_names", descriptor.getRenameTo());
}
@Test
public void testOperationRequestParameters() throws Exception {
AWSServiceHandlerManifest serviceManifest = mapper.readValue(testParameterWhitelist, AWSServiceHandlerManifest.class);
AWSOperationHandlerManifest operationManifest = serviceManifest.getOperationHandlerManifest("DynamoDb");
AWSOperationHandler operationHandler = operationManifest.getOperationHandler("CreateTable");
HashSet<String> parameters = operationHandler.getRequestParameters();
Assert.assertEquals(true, parameters.contains("GlobalSecondaryIndexes"));
Assert.assertEquals(true, parameters.contains("LocalSecondaryIndexes"));
Assert.assertEquals(true, parameters.contains("ProvisionedThroughput"));
Assert.assertEquals(true, parameters.contains("TableName"));
}
@Test
public void testOperationResponseDescriptors() throws Exception {
AWSServiceHandlerManifest serviceManifest = mapper.readValue(testParameterWhitelist, AWSServiceHandlerManifest.class);
AWSOperationHandlerManifest operationManifest = serviceManifest.getOperationHandlerManifest("DynamoDb");
AWSOperationHandler operationHandler = operationManifest.getOperationHandler("ListTables");
AWSOperationHandlerResponseDescriptor descriptor = operationHandler.getResponseDescriptors().get("TableNames");
Assert.assertEquals(false, descriptor.isMap());
Assert.assertEquals(true, descriptor.isList());
Assert.assertEquals(false, descriptor.shouldGetKeys());
Assert.assertEquals(true, descriptor.shouldGetCount());
Assert.assertEquals("table_count", descriptor.getRenameTo());
}
@Test
public void testOperationResponseParameters() throws Exception {
AWSServiceHandlerManifest serviceManifest = mapper.readValue(testParameterWhitelist, AWSServiceHandlerManifest.class);
AWSOperationHandlerManifest operationManifest = serviceManifest.getOperationHandlerManifest("DynamoDb");
AWSOperationHandler operationHandler = operationManifest.getOperationHandler("DeleteItem");
HashSet<String> parameters = operationHandler.getResponseParameters();
Assert.assertEquals(true, parameters.contains("ConsumedCapacity"));
Assert.assertEquals(true, parameters.contains("ItemCollectionMetrics"));
}
}
| 3,912 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/main/java/com/amazonaws/xray/utils/StringTransform.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.utils;
import java.util.regex.Pattern;
/**
* @deprecated For internal use only.
*/
@Deprecated
@SuppressWarnings("checkstyle:HideUtilityClassConstructor")
public class StringTransform {
private static final Pattern REGEX = Pattern.compile("([a-z])([A-Z])");
private static final String REPLACE = "$1_$2";
public static String toSnakeCase(String camelCase) {
return REGEX.matcher(camelCase).replaceAll(REPLACE).toLowerCase();
}
}
| 3,913 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/main/java/com/amazonaws/xray/handlers | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/main/java/com/amazonaws/xray/handlers/config/AWSOperationHandlerResponseDescriptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.handlers.config;
import com.fasterxml.jackson.annotation.JsonProperty;
public class AWSOperationHandlerResponseDescriptor {
@JsonProperty
private String renameTo;
@JsonProperty
private boolean map = false;
@JsonProperty
private boolean list = false;
@JsonProperty
private boolean getKeys = false;
@JsonProperty
private boolean getCount = false;
/**
* @return the renameTo
*/
public String getRenameTo() {
return renameTo;
}
/**
* @return the map
*/
public boolean isMap() {
return map;
}
/**
* @return the list
*/
public boolean isList() {
return list;
}
/**
* @return the getCount
*/
public boolean shouldGetCount() {
return getCount;
}
/**
* @return the getKeys
*/
public boolean shouldGetKeys() {
return getKeys;
}
}
| 3,914 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/main/java/com/amazonaws/xray/handlers | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/main/java/com/amazonaws/xray/handlers/config/AWSOperationHandlerRequestDescriptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.handlers.config;
import com.fasterxml.jackson.annotation.JsonProperty;
public class AWSOperationHandlerRequestDescriptor {
@JsonProperty
private String renameTo;
@JsonProperty
private boolean map = false;
@JsonProperty
private boolean list = false;
@JsonProperty
private boolean getKeys = false;
@JsonProperty
private boolean getCount = false;
/**
* @return the renameTo
*/
public String getRenameTo() {
return renameTo;
}
/**
* @return the map
*/
public boolean isMap() {
return map;
}
/**
* @return the list
*/
public boolean isList() {
return list;
}
/**
* @return the getCount
*/
public boolean shouldGetCount() {
return getCount;
}
/**
* @return the getKeys
*/
public boolean shouldGetKeys() {
return getKeys;
}
}
| 3,915 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/main/java/com/amazonaws/xray/handlers | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/main/java/com/amazonaws/xray/handlers/config/AWSServiceHandlerManifest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.handlers.config;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
public class AWSServiceHandlerManifest {
@JsonProperty
private Map<String, AWSOperationHandlerManifest> services;
public AWSOperationHandlerManifest getOperationHandlerManifest(String serviceName) {
return services.get(serviceName);
}
}
| 3,916 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/main/java/com/amazonaws/xray/handlers | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/main/java/com/amazonaws/xray/handlers/config/AWSOperationHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.handlers.config;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.HashMap;
import java.util.HashSet;
public class AWSOperationHandler {
@JsonProperty
private HashMap<String, AWSOperationHandlerRequestDescriptor> requestDescriptors;
@JsonProperty
private HashSet<String> requestParameters;
@JsonProperty
private HashMap<String, AWSOperationHandlerResponseDescriptor> responseDescriptors;
@JsonProperty
private HashSet<String> responseParameters;
@JsonProperty
private String requestIdHeader;
/**
* @return the requestKeys
*/
public HashMap<String, AWSOperationHandlerRequestDescriptor> getRequestDescriptors() {
return requestDescriptors;
}
/**
* @return the requestParameters
*/
public HashSet<String> getRequestParameters() {
return requestParameters;
}
/**
* @return the responseDescriptors
*/
public HashMap<String, AWSOperationHandlerResponseDescriptor> getResponseDescriptors() {
return responseDescriptors;
}
/**
* @return the responseParameters
*/
public HashSet<String> getResponseParameters() {
return responseParameters;
}
/**
* @return the requestIdHeader
*/
public String getRequestIdHeader() {
return requestIdHeader;
}
}
| 3,917 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/main/java/com/amazonaws/xray/handlers | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/main/java/com/amazonaws/xray/handlers/config/AWSOperationHandlerManifest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.handlers.config;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
public class AWSOperationHandlerManifest {
@JsonProperty
private Map<String, AWSOperationHandler> operations;
public AWSOperationHandler getOperationHandler(String operationRequestClassName) {
return operations.get(operationRequestClassName);
}
}
| 3,918 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/main/java/com/amazonaws/xray/handlers | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-core/src/main/java/com/amazonaws/xray/handlers/config/AWSServiceHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.handlers.config;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
public class AWSServiceHandler {
@JsonProperty
private Map<String, AWSOperationHandler> operations;
public AWSOperationHandler getOperationHandler(String operationName) {
return operations.get(operationName);
}
}
| 3,919 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-benchmark/tst/main/java/com/amazonaws | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-benchmark/tst/main/java/com/amazonaws/xray/AWSXRayRecorderBenchmark.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import java.net.SocketException;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@BenchmarkMode({Mode.Throughput, Mode.SampleTime})
@Measurement(iterations = 5, time = 1)
@Warmup(iterations = 10, time = 1)
@Fork(1)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class AWSXRayRecorderBenchmark {
private static final String SEGMENT_NAME = "BENCHMARK_SEGMENT";
private static final String SUBSEGMENT_NAME = "BENCHMARK_SUBSEGMENT";
// Base state; generates the default recorder.
@State(Scope.Thread)
public static class RecorderState {
// Recorder which always chooses to sample.
public AWSXRayRecorder recorder;
@Setup(Level.Trial)
public void setupOnce() throws SocketException {
recorder = AWSXRayRecorderBuilder.defaultRecorder();
}
}
// State that contains a recorder whose sampling decision is always true.
// This state automatically populates the X-Ray context with a segment and subsegment.
public static class PopulatedRecorderState extends RecorderState {
@Override
@Setup(Level.Trial)
public void setupOnce() throws SocketException {
super.setupOnce();
}
@Setup(Level.Iteration)
public void setupContext() {
recorder.beginSegment(SEGMENT_NAME);
recorder.beginSubsegment(SUBSEGMENT_NAME);
}
@TearDown(Level.Iteration)
public void clearContext() {
recorder.clearTraceEntity();
}
}
// Begin a segment and end the segment; usually in the case when the sampling decision is true.
@Benchmark
public void beginEndSegmentBenchmark(RecorderState state) {
state.recorder.beginSegment(SEGMENT_NAME);
state.recorder.endSegment();
}
// Begin a segment and end the segment; usually in the case when the sampling decision is false.
@Benchmark
public void beginEndDummySegmentBenchmark(RecorderState state) {
state.recorder.beginNoOpSegment();
state.recorder.endSegment();
}
// Begin a segment, begin a subsegment, end the subsegment, and end the segment,
// where the sampling decision is to true.
@Benchmark
public void beginEndSegmentSubsegmentBenchmark(RecorderState state) {
state.recorder.beginSegment(SEGMENT_NAME);
state.recorder.beginSubsegment(SUBSEGMENT_NAME);
state.recorder.endSubsegment();
state.recorder.endSegment();
}
// Begin a segment, begin a subsegment, end the subsegment, and end the segment,
// where the sampling decision is not true (and a parent dummy segment is generated).
@Benchmark
public void beginEndDummySegmentSubsegmentBenchmark(RecorderState state) {
state.recorder.beginNoOpSegment();
state.recorder.beginSubsegment(SUBSEGMENT_NAME);
state.recorder.endSubsegment();
state.recorder.endSegment();
}
// Get Segment benchmark
// We have to make sure the state that we choose has an entity already populated.
@Benchmark
public Segment getSegmentBenchmark(PopulatedRecorderState state) {
return state.recorder.getCurrentSegment();
}
// Get Subsegment benchmark.
// We have to make sure the context has a subsegment present.
@Benchmark
public Subsegment getSubsegmentBenchmark(PopulatedRecorderState state) {
return state.recorder.getCurrentSubsegment();
}
// Convenience main entry-point
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.addProfiler("gc")
.include(".*" + AWSXRayRecorderBenchmark.class.getSimpleName() + ".*Dummy.*")
.build();
new Runner(opt).run();
}
}
| 3,920 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-benchmark/tst/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-benchmark/tst/main/java/com/amazonaws/xray/entities/EntityBenchmark.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.entities;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@BenchmarkMode({Mode.Throughput, Mode.SampleTime})
@Fork(1)
@Warmup(iterations = 10, time = 1)
@Measurement(iterations = 5, time = 1)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class EntityBenchmark {
public static final String SEGMENT_NAME = "BENCHMARK_SEGMENT";
public static final int N_OPERATIONS = 10000;
// Benchmark state that initializes a parent segment to operate on.
@State(Scope.Thread)
public static class MultiSegmentBenchmarkState {
/**
* List of segments that we'll perform operations on individually. For consistency, we need a fresh segment
* for each invocation in most of these tests, but managing 1 segment at Level.Invocation would cause too
* much instability within the tests because of the speed of each invoke. So we artificially lengthen the time of
* each invoke by iterating through a large list of segments instead, which makes using Level.Invocation safer.
*/
public List<Segment> segments;
// X-Ray Recorder
public AWSXRayRecorder recorder;
// An exception object
public Exception theException;
@Setup(Level.Trial)
public void setupOnce() throws SocketException {
recorder = AWSXRayRecorderBuilder.defaultRecorder();
theException = new Exception("Test Exception");
}
@Setup(Level.Invocation)
public void doSetUp() {
segments = new ArrayList<>();
for (int i = 0; i < N_OPERATIONS; i++) {
segments.add(new SegmentImpl(recorder, SEGMENT_NAME));
}
}
}
@State(Scope.Thread)
public static class BenchmarkState {
// X-Ray Recorder
public AWSXRayRecorder recorder;
@Setup(Level.Trial)
public void setupOnce() throws SocketException {
recorder = AWSXRayRecorderBuilder.defaultRecorder();
}
}
// Construct a segment
@Benchmark
public Segment constructSegmentBenchmark(BenchmarkState state) {
return new SegmentImpl(state.recorder, SEGMENT_NAME);
}
// Construct a subsegment and add it to the parent segment.
@Benchmark
@OperationsPerInvocation(N_OPERATIONS)
public void constructSubsegmentPutInSegmentBenchmark(MultiSegmentBenchmarkState state) {
for (Segment segment : state.segments) {
new SubsegmentImpl(state.recorder, SEGMENT_NAME, segment);
}
}
// Add an annotation to a segment
@Benchmark
@OperationsPerInvocation(N_OPERATIONS)
public void putAnnotationBenchmark(MultiSegmentBenchmarkState state) {
for (Segment segment : state.segments) {
segment.putAnnotation("Key", "Value");
}
}
// Add metadata to a segment
@Benchmark
@OperationsPerInvocation(N_OPERATIONS)
public void putMetadataBenchmark(MultiSegmentBenchmarkState state) {
for (Segment segment : state.segments) {
segment.putMetadata("Key", "Value");
}
}
// Add exception into a segment
@Benchmark
@OperationsPerInvocation(N_OPERATIONS)
public void putExceptionSegmentBenchmark(MultiSegmentBenchmarkState state) {
for (Segment segment : state.segments){
segment.addException(state.theException);
}
}
// Convenience main entry-point
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.addProfiler("gc")
.include(".*" + EntityBenchmark.class.getSimpleName())
.build();
new Runner(opt).run();
}
}
| 3,921 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-benchmark/tst/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-benchmark/tst/main/java/com/amazonaws/xray/entities/EntitySerializerBenchmark.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.entities;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
@BenchmarkMode({Mode.Throughput, Mode.SampleTime})
@Fork(1)
@Warmup(iterations = 10, time = 1)
@Measurement(iterations = 5, time = 1)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class EntitySerializerBenchmark {
public static final String SEGMENT_NAME = "BENCHMARK_SEGMENT";
public static final String SUBSEGMENT_NAME = "BENCHMARK_SUBSEGMENT";
// Populate the entity with common metadata to make the conditions for serialization
// more practical.
private static void populateEntity(Entity entity) {
entity.putAnnotation("Annotation", "Data");
entity.putMetadata("Metadata", "Value");
Map<String, Object> request = new HashMap<>();
request.put("url", "http://localhost:8000/");
request.put("method", "POST");
request.put("user_agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36");
request.put("client_ip", "127.0.0.1");
Map<String, Object> response = new HashMap<>();
response.put("status", "200");
Map<String, Object> aws = new HashMap<>();
aws.put("sdk_version", "2.2.x-INTERNAL");
aws.put("sdk", "X-Ray for Java");
entity.putAllHttp(request);
entity.putAllHttp(response);
entity.putAllAws(aws);
}
// Remove all the child subsegments from the given segment.
private static void clearSegment(Segment parentSegment) {
List<Subsegment> toRemove = new ArrayList<>(parentSegment.getSubsegments());
for (Subsegment subsegment : toRemove) {
parentSegment.removeSubsegment(subsegment);
}
}
// Benchmark state that initializes a parent segment to operate on. Single level here
// represents that there is a single level of children after the parent segment.
@State(Scope.Thread)
public static class SingleLevelSegmentState {
// Segments which have a certain number of subsegments.
public Segment emptySegment;
public Segment oneChildSegment;
public Segment twoChildSegment;
public Segment threeChildSegment;
public Segment fourChildSegment;
// X-Ray Recorder
public AWSXRayRecorder recorder;
@Setup(Level.Trial)
public void setupOnce() throws SocketException {
recorder = AWSXRayRecorderBuilder.defaultRecorder();
}
@Setup(Level.Iteration)
public void setup() {
emptySegment = generateSegmentWithChildren(0);
oneChildSegment = generateSegmentWithChildren(1);
twoChildSegment = generateSegmentWithChildren(2);
threeChildSegment = generateSegmentWithChildren(3);
fourChildSegment = generateSegmentWithChildren(4);
}
@TearDown(Level.Iteration)
public void doTearDown() {
clearSegment(emptySegment);
clearSegment(oneChildSegment);
clearSegment(twoChildSegment);
clearSegment(threeChildSegment);
clearSegment(fourChildSegment);
}
// Generates a segment with n number of children,
// Populates the given Entity with annotations, metadata, and other information specific to
private Segment generateSegmentWithChildren(int numChildren) {
Segment parentSegment = new SegmentImpl(recorder, SEGMENT_NAME);
populateEntity(parentSegment);
for (int i = 0; i < numChildren; i++) {
Subsegment subsegment = new SubsegmentImpl(recorder, SUBSEGMENT_NAME, parentSegment);
populateEntity(subsegment);
subsegment.setParentSegment(parentSegment);
parentSegment.addSubsegment(subsegment);
}
return parentSegment;
}
}
// Benchmark state that initializes a parent segment to operate on. Single level here
// represents that there is a single level of children after the parent segment.
@State(Scope.Thread)
public static class MultiLevelSegmentState {
// Segments which have a certain depth of children.
// Two in this case represents Segment -> Subsegment -> Subsegment
public Segment twoLevelSegment;
public Segment threeLevelSegment;
public Segment fourLevelSegment;
// X-Ray Recorder
public AWSXRayRecorder recorder;
@Setup(Level.Trial)
public void setupOnce() throws SocketException {
recorder = AWSXRayRecorderBuilder.defaultRecorder();
}
@Setup(Level.Iteration)
public void setup() {
twoLevelSegment = generateSegmentWithDepth(2);
threeLevelSegment = generateSegmentWithDepth(3);
fourLevelSegment = generateSegmentWithDepth(4);
}
@TearDown(Level.Iteration)
public void doTearDown() {
clearSegment(twoLevelSegment);
clearSegment(threeLevelSegment);
clearSegment(fourLevelSegment);
}
// Generates a segment with n number of children,
// Populates the given Entity with annotations, metadata, and other information specific to
private Segment generateSegmentWithDepth(int numLevels) {
Segment parentSegment = new SegmentImpl(recorder, SEGMENT_NAME);
populateEntity(parentSegment);
Entity currentEntity = parentSegment;
for (int i = 0; i < numLevels; i++) {
Subsegment subsegment = new SubsegmentImpl(recorder, SUBSEGMENT_NAME, parentSegment);
populateEntity(subsegment);
currentEntity.addSubsegment(subsegment);
subsegment.setParentSegment(parentSegment);
subsegment.setParent(currentEntity);
currentEntity = subsegment;
}
return parentSegment;
}
}
// Serialize a segment with no child subsegments
@Benchmark
public String serializeZeroChildSegment(SingleLevelSegmentState state) {
return state.emptySegment.serialize();
}
// Serialize a segment with one child subsegment
@Benchmark
public String serializeOneChildSegment(SingleLevelSegmentState state) {
return state.oneChildSegment.serialize();
}
// Serialize a segment with two child subsegments
@Benchmark
public String serializeTwoChildSegment(SingleLevelSegmentState state) {
return state.twoChildSegment.serialize();
}
// Serialize a segment with three child subsegments
@Benchmark
public String serializeThreeChildSegment(SingleLevelSegmentState state) {
return state.threeChildSegment.serialize();
}
// Serialize a segment with three child subsegments
@Benchmark
public String serializeFourChildSegment(SingleLevelSegmentState state) {
return state.fourChildSegment.serialize();
}
// Serialize a segment with two generations of subsegments.
@Benchmark
public String serializeTwoGenerationSegment(MultiLevelSegmentState state) {
return state.twoLevelSegment.serialize();
}
// Serialize a segment with three generations of subsegments.
@Benchmark
public String serializeThreeGenerationSegment(MultiLevelSegmentState state) {
return state.threeLevelSegment.serialize();
}
// Serialize a segment with four generations of subsegments.
@Benchmark
public String serializeFourGenerationSegment(MultiLevelSegmentState state) {
return state.fourLevelSegment.serialize();
}
}
| 3,922 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-benchmark/tst/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-benchmark/tst/main/java/com/amazonaws/xray/entities/TraceHeaderBenchmark.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.entities;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@Measurement(iterations = 5, time = 1)
@Warmup(iterations = 10, time = 1)
@Fork(1)
@BenchmarkMode({Mode.Throughput, Mode.SampleTime})
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class TraceHeaderBenchmark {
private static final String HEADER_STRING = "Root=1-8a3c60f7-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=1";
private static final TraceHeader HEADER = TraceHeader.fromString(HEADER_STRING);
@Benchmark
public TraceHeader parse() {
return TraceHeader.fromString(HEADER_STRING);
}
@Benchmark
public String serialize() {
return HEADER.toString();
}
// Convenience main entry-point
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.addProfiler("gc")
.include(".*" + TraceHeaderBenchmark.class.getSimpleName() + ".serialize")
.build();
new Runner(opt).run();
}
}
| 3,923 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-benchmark/tst/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-benchmark/tst/main/java/com/amazonaws/xray/entities/IdsBenchmark.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.entities;
import com.amazonaws.xray.ThreadLocalStorage;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@Measurement(iterations = 5, time = 1)
@Warmup(iterations = 10, time = 1)
@Fork(1)
@BenchmarkMode({Mode.Throughput, Mode.SampleTime})
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Threads(16)
public class IdsBenchmark {
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
private static final TraceID TRACE_ID = TraceID.create();
@Benchmark
public TraceID traceId_create() {
return TraceID.create();
}
@Benchmark
public TraceID traceId_parse() {
return TraceID.fromString("1-57ff426a-80c11c39b0c928905eb0828d");
}
@Benchmark
public String traceId_serialize() {
return TRACE_ID.toString();
}
@Benchmark
public BigInteger traceId_secureRandom() {
return new BigInteger(96, SECURE_RANDOM);
}
@Benchmark
public BigInteger traceId_threadLocalSecureRandom() {
return new BigInteger(96, ThreadLocalStorage.getRandom());
}
@Benchmark
public BigInteger traceId_threadLocalRandom() {
return new BigInteger(96, ThreadLocalRandom.current());
}
@Benchmark
public String segmentId_secureRandom() {
return Long.toString(SECURE_RANDOM.nextLong() >>> 1, 16);
}
@Benchmark
public String segmentId_threadLocalSecureRandom() {
return Long.toString(ThreadLocalStorage.getRandom().nextLong() >>> 1, 16);
}
@Benchmark
public String segmentId_threadLocalRandom() {
return Long.toString(ThreadLocalRandom.current().nextLong() >>> 1, 16);
}
// Convenience main entry-point
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.addProfiler("gc")
.include(".*" + IdsBenchmark.class.getSimpleName() + ".*_(create|parse|serialize)")
.build();
new Runner(opt).run();
}
}
| 3,924 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-benchmark/tst/main/java/com/amazonaws/xray/strategy | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-benchmark/tst/main/java/com/amazonaws/xray/strategy/sampling/LocalizedSamplingStrategyBenchmark.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.strategy.sampling;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@BenchmarkMode({Mode.Throughput, Mode.SampleTime})
@Fork(1)
@Warmup(iterations = 10, time = 1)
@Measurement(iterations = 5, time = 1)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class LocalizedSamplingStrategyBenchmark {
@State(Scope.Thread)
public static class DefaultSamplingRulesState {
private LocalizedSamplingStrategy samplingStrategy;
private SamplingRequest samplingRequest;
@Setup(Level.Trial)
public void setupOnce() {
samplingStrategy = new LocalizedSamplingStrategy();
samplingRequest = new SamplingRequest("roleARN", "arn:aws:execute-api:us-east-1:1234566789012:qsxrty/test",
"serviceName", "hostName", "someMethod", "https://hostName.com", null, null);
}
}
@State(Scope.Thread)
public static class NoSampleSamplingRulesState {
private LocalizedSamplingStrategy samplingStrategy;
private SamplingRequest samplingRequest;
private static final URL NO_SAMPLE_RULE = LocalizedSamplingStrategy.class.getResource("/com/amazonaws/xray/strategy/sampling/NoSampleRule.json");
@Setup(Level.Trial)
public void setupOnce() {
samplingStrategy = new LocalizedSamplingStrategy(NO_SAMPLE_RULE);
samplingRequest = new SamplingRequest("roleARN", "arn:aws:execute-api:us-east-1:1234566789012:qsxrty/test",
"serviceName", "hostName", "someMethod", "https://hostName.com", null, null);
}
}
// Benchmark default sampling rules on a sampling Request that matches the rules.
@Benchmark
public boolean defaultSamplingRuleBenchmark(DefaultSamplingRulesState state) {
return state.samplingStrategy.shouldTrace(state.samplingRequest).isSampled();
}
// Benchmark a no match sampling rule on a sampling request.
@Benchmark
public boolean noSampleSamplingBenchmark(NoSampleSamplingRulesState state) {
return state.samplingStrategy.shouldTrace(state.samplingRequest).isSampled();
}
// Convenience main entry-point
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.addProfiler("gc")
.include(".*" + LocalizedSamplingStrategyBenchmark.class.getSimpleName())
.build();
new Runner(opt).run();
}
}
| 3,925 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-benchmark/tst/main/java/com/amazonaws/xray/strategy | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-benchmark/tst/main/java/com/amazonaws/xray/strategy/sampling/CentralizedSamplingStrategyBenchmark.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.strategy.sampling;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@BenchmarkMode({Mode.Throughput, Mode.SampleTime})
@Fork(1)
@Warmup(iterations = 10, time = 1)
@Measurement(iterations = 5, time = 1)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class CentralizedSamplingStrategyBenchmark {
@State(Scope.Thread)
public static class DefaultSamplingRulesState {
private CentralizedSamplingStrategy samplingStrategy;
private SamplingRequest samplingRequest;
@Setup(Level.Trial)
public void setupOnce() {
samplingStrategy = new CentralizedSamplingStrategy();
samplingRequest = new SamplingRequest("roleARN", "arn:aws:execute-api:us-east-1:1234566789012:qsxrty/test",
"serviceName", "hostName", "someMethod", "https://hostName.com", null, null);
}
}
@State(Scope.Thread)
public static class NoSampleSamplingRulesState {
private CentralizedSamplingStrategy samplingStrategy;
private SamplingRequest samplingRequest;
private static final URL NO_SAMPLE_RULE = LocalizedSamplingStrategy.class.getResource("/com/amazonaws/xray/strategy/sampling/NoSampleRule.json");
@Setup(Level.Trial)
public void setupOnce() {
samplingStrategy = new CentralizedSamplingStrategy(NO_SAMPLE_RULE);
samplingRequest = new SamplingRequest("roleARN", "arn:aws:execute-api:us-east-1:1234566789012:qsxrty/test",
"serviceName", "hostName", "someMethod", "https://hostName.com", null, null);
}
}
// Benchmark default sampling rules on a sampling Request that matches the rules.
@Benchmark
public boolean defaultSamplingRuleBenchmark(DefaultSamplingRulesState state) {
return state.samplingStrategy.shouldTrace(state.samplingRequest).isSampled();
}
// Benchmark a no match sampling rule on a sampling request.
@Benchmark
public boolean noSampleSamplingBenchmark(NoSampleSamplingRulesState state) {
return state.samplingStrategy.shouldTrace(state.samplingRequest).isSampled();
}
// Convenience main entry-point
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.addProfiler("gc")
.include(".*" + CentralizedSamplingStrategyBenchmark.class.getSimpleName())
.build();
new Runner(opt).run();
}
}
| 3,926 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-benchmark/src/jmh/java/com/amazonaws/xray/agent | Create_ds/aws-xray-java-agent/aws-xray-agent-benchmark/src/jmh/java/com/amazonaws/xray/agent/benchmark/SqlBenchmark.java | package com.amazonaws.xray.agent.benchmark;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.agent.benchmark.source.StatementImpl;
import com.amazonaws.xray.agent.utils.BenchmarkUtils;
import com.amazonaws.xray.sql.TracingStatement;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.sql.SQLException;
import java.sql.Statement;
public class SqlBenchmark {
@State(Scope.Benchmark)
public static class BenchmarkState {
Statement statement;
@Setup(Level.Trial)
public void setup() {
BenchmarkUtils.configureXRayRecorder();
if (System.getProperty("com.amazonaws.xray.sdk") != null) {
statement = TracingStatement.decorateStatement(new StatementImpl());
} else {
statement = new StatementImpl();
}
}
}
@Benchmark
public void sqlQuery(BenchmarkState state) throws SQLException {
AWSXRay.beginSegment("Benchmark");
state.statement.executeQuery("SQL");
AWSXRay.endSegment();
}
}
| 3,927 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-benchmark/src/jmh/java/com/amazonaws/xray/agent | Create_ds/aws-xray-java-agent/aws-xray-agent-benchmark/src/jmh/java/com/amazonaws/xray/agent/benchmark/ServletBenchmark.java | package com.amazonaws.xray.agent.benchmark;
import com.amazonaws.xray.agent.utils.BenchmarkUtils;
import com.amazonaws.xray.agent.utils.ClientProvider;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static org.mockito.Mockito.when;
public class ServletBenchmark {
@State(Scope.Benchmark)
public static class BenchmarkState {
HttpServlet servlet;
@Mock
HttpServletRequest servletRequest;
@Mock
HttpServletResponse servletResponse;
@Setup(Level.Trial)
public void setup() {
MockitoAnnotations.initMocks(this);
BenchmarkUtils.configureXRayRecorder();
when(servletRequest.getRequestURL()).thenReturn(new StringBuffer("http://example.com"));
when(servletRequest.getMethod()).thenReturn("GET");
when(servletResponse.getStatus()).thenReturn(200);
if (System.getProperty("com.amazonaws.xray.sdk") != null) {
servlet = ClientProvider.instrumentedHttpServlet();
} else {
servlet = ClientProvider.normalHttpServlet();
}
}
}
@Benchmark
public void serviceRequest(BenchmarkState state) throws IOException, ServletException {
state.servlet.service(state.servletRequest, state.servletResponse);
}
}
| 3,928 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-benchmark/src/jmh/java/com/amazonaws/xray/agent | Create_ds/aws-xray-java-agent/aws-xray-agent-benchmark/src/jmh/java/com/amazonaws/xray/agent/benchmark/HttpDownstreamBenchmark.java | package com.amazonaws.xray.agent.benchmark;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.agent.utils.BenchmarkUtils;
import com.amazonaws.xray.agent.utils.ClientProvider;
import com.amazonaws.xray.agent.utils.SimpleJettyServer;
import com.amazonaws.xray.entities.TraceHeader;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.eclipse.jetty.server.Server;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import java.io.IOException;
public class HttpDownstreamBenchmark {
private static final int PORT = 20808;
private static final String PATH = "/path/to/page";
@State(Scope.Benchmark)
public static class BenchmarkState {
CloseableHttpClient httpClient;
HttpGet httpGet;
AWSXRayRecorder recorder;
Server jettyServer;
@Setup(Level.Trial)
public void setup() {
recorder = BenchmarkUtils.configureXRayRecorder();
if (System.getProperty("com.amazonaws.xray.sdk") != null) {
httpClient = ClientProvider.instrumentedApacheHttpClient();
} else {
httpClient = ClientProvider.normalApacheHttpClient();
}
httpGet = new HttpGet("http://localhost:" + PORT + PATH);
jettyServer = SimpleJettyServer.create(PORT, PATH);
}
@TearDown(Level.Trial)
public void cleanup() {
try {
jettyServer.stop();
} catch (Exception e) {
e.printStackTrace();
} finally {
jettyServer.destroy();
}
}
}
/**
* This benchmark tests the time it takes to make a HTTP request with an Apache client wrapped in an X-Ray Segment.
* It can be tested with or without the agent running on the JVM. The segment is necessary because we only want to
* test the performance change introduced by the instrumentation of the Apache client, and without the segment we
* get CMEs, which do not accurately represent the instrumentation latency.
*
* As something of a hack, we add an additional JVM arg pointing to an agent config file in the resources directory
* that disables the agent's instrumentation of servlet requests. This prevents us from attempting to start a new
* segment when the Jetty server handles these HTTP requests, which would add latency.
*/
@Benchmark
@Fork(jvmArgsAppend = "-Dcom.amazonaws.xray.configFile=/com/amazonaws/xray/agent/agent-config.json")
public void makeHttpRequest(BenchmarkState state) throws IOException {
AWSXRay.beginSegment("Benchmark");
state.httpClient.execute(state.httpGet);
state.httpGet.releaseConnection(); // Prevents overwhelming max connections
state.httpGet.removeHeaders(TraceHeader.HEADER_KEY); // Prevents Trace ID headers stacking up
AWSXRay.endSegment();
}
}
| 3,929 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-benchmark/src/jmh/java/com/amazonaws/xray/agent | Create_ds/aws-xray-java-agent/aws-xray-agent-benchmark/src/jmh/java/com/amazonaws/xray/agent/benchmark/AwsSdkBenchmark.java | package com.amazonaws.xray.agent.benchmark;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.agent.utils.BenchmarkUtils;
import com.amazonaws.xray.agent.utils.ClientProvider;
import com.amazonaws.xray.agent.utils.SimpleJettyServer;
import org.eclipse.jetty.server.Server;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
/**
* For the AWS SDK benchmarks, we use the same trick as in {@link HttpDownstreamBenchmark} to stop the Agent from
* attempting to create segments for our jetty server and mess up the timing.
*/
@Fork(jvmArgsAppend = "-Dcom.amazonaws.xray.configFile=/com/amazonaws/xray/agent/agent-config.json")
public class AwsSdkBenchmark {
private static final int PORT = 20808;
private static final String PATH = "/"; // path for ListTables API
@State(Scope.Benchmark)
public static class BenchmarkState {
AmazonDynamoDB v1Client;
DynamoDbClient v2Client;
AWSXRayRecorder recorder;
Server jettyServer;
@Setup(Level.Trial)
public void setup() {
recorder = BenchmarkUtils.configureXRayRecorder();
if (System.getProperty("com.amazonaws.xray.sdk") != null) {
v1Client = ClientProvider.instrumentedV1Client(recorder);
v2Client = ClientProvider.instrumentedV2Client();
} else {
v1Client = ClientProvider.normalV1Client();
v2Client = ClientProvider.normalV2Client();
}
jettyServer = SimpleJettyServer.create(PORT, PATH);
}
@TearDown(Level.Trial)
public void cleanup() {
try {
jettyServer.stop();
} catch (Exception e) {
e.printStackTrace();
} finally {
jettyServer.destroy();
}
}
}
@Benchmark
public void awsV1Request(BenchmarkState state) {
AWSXRay.beginSegment("Benchmark");
state.v1Client.listTables();
AWSXRay.endSegment();
}
@Benchmark
public void awsV2Request(BenchmarkState state) {
AWSXRay.beginSegment("Benchmark");
state.v2Client.listTables();
AWSXRay.endSegment();
}
}
| 3,930 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-benchmark/src/jmh/java/com/amazonaws/xray/agent/benchmark | Create_ds/aws-xray-java-agent/aws-xray-agent-benchmark/src/jmh/java/com/amazonaws/xray/agent/benchmark/source/StatementImpl.java | package com.amazonaws.xray.agent.benchmark.source;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import static org.mockito.Mockito.when;
public class StatementImpl implements Statement {
@Mock
private Connection connection;
@Mock
private DatabaseMetaData metaData;
{
try {
MockitoAnnotations.initMocks(this);
when(connection.getMetaData()).thenReturn(metaData);
when(metaData.getURL()).thenReturn("http://example.com");
when(metaData.getUserName()).thenReturn("User");
when(metaData.getDriverVersion()).thenReturn("1.0");
when(metaData.getDatabaseProductName()).thenReturn("MyDb");
when(metaData.getDatabaseProductVersion()).thenReturn("1.0");
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public ResultSet executeQuery(String sql) throws SQLException {
try {
Thread.sleep(2);
} catch (Exception e) {
}
return null;
}
@Override
public int executeUpdate(String sql) throws SQLException {
return 0;
}
@Override
public void close() throws SQLException {
}
@Override
public int getMaxFieldSize() throws SQLException {
return 0;
}
@Override
public void setMaxFieldSize(int max) throws SQLException {
}
@Override
public int getMaxRows() throws SQLException {
return 0;
}
@Override
public void setMaxRows(int max) throws SQLException {
}
@Override
public void setEscapeProcessing(boolean enable) throws SQLException {
}
@Override
public int getQueryTimeout() throws SQLException {
return 0;
}
@Override
public void setQueryTimeout(int seconds) throws SQLException {
}
@Override
public void cancel() throws SQLException {
}
@Override
public SQLWarning getWarnings() throws SQLException {
return null;
}
@Override
public void clearWarnings() throws SQLException {
}
@Override
public void setCursorName(String name) throws SQLException {
}
@Override
public boolean execute(String sql) throws SQLException {
return false;
}
@Override
public ResultSet getResultSet() throws SQLException {
return null;
}
@Override
public int getUpdateCount() throws SQLException {
return 0;
}
@Override
public boolean getMoreResults() throws SQLException {
return false;
}
@Override
public void setFetchDirection(int direction) throws SQLException {
}
@Override
public int getFetchDirection() throws SQLException {
return 0;
}
@Override
public void setFetchSize(int rows) throws SQLException {
}
@Override
public int getFetchSize() throws SQLException {
return 0;
}
@Override
public int getResultSetConcurrency() throws SQLException {
return 0;
}
@Override
public int getResultSetType() throws SQLException {
return 0;
}
@Override
public void addBatch(String sql) throws SQLException {
}
@Override
public void clearBatch() throws SQLException {
}
@Override
public int[] executeBatch() throws SQLException {
return new int[0];
}
@Override
public Connection getConnection() throws SQLException {
return connection;
}
@Override
public boolean getMoreResults(int current) throws SQLException {
return false;
}
@Override
public ResultSet getGeneratedKeys() throws SQLException {
return null;
}
@Override
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
return 0;
}
@Override
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
return 0;
}
@Override
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
return 0;
}
@Override
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
return false;
}
@Override
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
return false;
}
@Override
public boolean execute(String sql, String[] columnNames) throws SQLException {
return false;
}
@Override
public int getResultSetHoldability() throws SQLException {
return 0;
}
@Override
public boolean isClosed() throws SQLException {
return false;
}
@Override
public void setPoolable(boolean poolable) throws SQLException {
}
@Override
public boolean isPoolable() throws SQLException {
return false;
}
@Override
public void closeOnCompletion() throws SQLException {
}
@Override
public boolean isCloseOnCompletion() throws SQLException {
return false;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
}
| 3,931 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-benchmark/src/jmh/java/com/amazonaws/xray/agent | Create_ds/aws-xray-java-agent/aws-xray-agent-benchmark/src/jmh/java/com/amazonaws/xray/agent/utils/BenchmarkUtils.java | package com.amazonaws.xray.agent.utils;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.strategy.sampling.AllSamplingStrategy;
public final class BenchmarkUtils {
private BenchmarkUtils() {
}
/**
* This initializes the static recorder if the agent is not present, and ensures we don't actually emit
* segments regardless of whether or not we're using the agent
*
* @return the configured X-Ray recorder, also retrievable by AWSXRay.getGlobalRecorder
*/
public static AWSXRayRecorder configureXRayRecorder() {
AWSXRayRecorder recorder = AWSXRay.getGlobalRecorder();
recorder.setEmitter(new NoOpEmitter());
recorder.setSamplingStrategy(new AllSamplingStrategy());
return AWSXRay.getGlobalRecorder();
}
private static class NoOpEmitter extends Emitter {
@Override
public boolean sendSegment(Segment segment) {
return true;
}
@Override
public boolean sendSubsegment(Subsegment subsegment) {
return true;
}
}
}
| 3,932 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-benchmark/src/jmh/java/com/amazonaws/xray/agent | Create_ds/aws-xray-java-agent/aws-xray-agent-benchmark/src/jmh/java/com/amazonaws/xray/agent/utils/SimpleJettyServer.java | package com.amazonaws.xray.agent.utils;
import com.amazonaws.xray.AWSXRay;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.component.AbstractLifeCycle;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetSocketAddress;
/**
* Utility class used in benchmarking tests to simulate a web server and negate unpredictable network interaction's
* impact on benchmarking results.
*
* Adapted from the OpenTelemetry benchmarking strategy
* https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/benchmark/src/jmh/java/io/opentelemetry/benchmark/classes/HttpClass.java
*/
public final class SimpleJettyServer {
private SimpleJettyServer() {
}
public static Server create(int port, String path) {
System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
System.setProperty("org.eclipse.jetty.LEVEL", "WARN");
Server jettyServer = new Server(new InetSocketAddress("localhost", port));
ServletContextHandler servletContext = new ServletContextHandler();
try {
servletContext.addServlet(MyServlet.class, path);
jettyServer.setHandler(servletContext);
jettyServer.start();
// Make sure the Server has started
while (!AbstractLifeCycle.STARTED.equals(jettyServer.getState())) {
Thread.sleep(500);
}
} catch (Exception e) {
e.printStackTrace();
}
return jettyServer;
}
public static class MyServlet extends HttpServlet {
/**
* Handles vanilla HTTP requests from Apache HTTP client benchmarks
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
Thread.sleep(2);
} catch (Exception e) {
}
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("{ \"status\": \"ok\"}");
}
/**
* Handles ListTables requests from AWS SDK benchmarks
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
Thread.sleep(2);
} catch (Exception e) {
}
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_OK);
response.addHeader("x-amz-request-id", "12345");
response.getWriter().println("{\"TableNames\":[\"ATestTable\",\"dynamodb-user\",\"scorekeep-state\",\"scorekeep-user\"]}");
}
}
}
| 3,933 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-benchmark/src/jmh/java/com/amazonaws/xray/agent | Create_ds/aws-xray-java-agent/aws-xray-agent-benchmark/src/jmh/java/com/amazonaws/xray/agent/utils/ClientProvider.java | package com.amazonaws.xray.agent.utils;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.handlers.TracingHandler;
import com.amazonaws.xray.interceptors.TracingInterceptor;
import com.amazonaws.xray.javax.servlet.AWSXRayServletFilter;
import com.amazonaws.xray.proxies.apache.http.HttpClientBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.client.builder.SdkClientBuilder;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.time.Duration;
/**
* Helper class to create various types of instrumented and non-instrumented clients for use in benchmark tests,
* so that we can ensure the tests are exactly the same and the only variable is the type (or lack) of instrumentation
* used.
*/
public final class ClientProvider {
private static final String ENDPOINT = "http://localhost:20808";
public static CloseableHttpClient normalApacheHttpClient() {
return HttpClients.createDefault();
}
public static CloseableHttpClient instrumentedApacheHttpClient() {
return HttpClientBuilder.create().build();
}
public static HttpServlet normalHttpServlet() {
return new NormalServlet();
}
public static HttpServlet instrumentedHttpServlet() {
return new InstrumentedServlet();
}
public static AmazonDynamoDB normalV1Client() {
return (AmazonDynamoDB) getTestableV1Client(AmazonDynamoDBClientBuilder.standard()).build();
}
public static AmazonDynamoDB instrumentedV1Client(AWSXRayRecorder recorder) {
return (AmazonDynamoDB) getTestableV1Client(AmazonDynamoDBClientBuilder.standard())
.withRequestHandlers(new TracingHandler(recorder))
.build();
}
public static DynamoDbClient normalV2Client() {
SdkClientBuilder builder = DynamoDbClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("x", "x")))
.region(Region.US_WEST_2);
return (DynamoDbClient) getTestableV2Client(builder, false).build();
}
public static DynamoDbClient instrumentedV2Client() {
SdkClientBuilder builder = DynamoDbClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("x", "x")))
.region(Region.US_WEST_2);
return (DynamoDbClient) getTestableV2Client(builder, true).build();
}
private static AwsClientBuilder getTestableV1Client(AwsClientBuilder builder) {
AWSCredentialsProvider fakeCredentials = new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake"));
AwsClientBuilder.EndpointConfiguration mockEndpoint = new AwsClientBuilder.EndpointConfiguration(ENDPOINT, "us-west-2");
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setMaxErrorRetry(0);
clientConfiguration.setRequestTimeout(1000);
return builder
.withEndpointConfiguration(mockEndpoint)
.withCredentials(fakeCredentials)
.withClientConfiguration(clientConfiguration);
}
private static SdkClientBuilder getTestableV2Client(SdkClientBuilder builder, boolean instrumented) {
ClientOverrideConfiguration.Builder configBuilder = ClientOverrideConfiguration.builder()
.apiCallTimeout(Duration.ofSeconds(1));
if (instrumented) {
configBuilder.addExecutionInterceptor(new TracingInterceptor());
}
return builder
.overrideConfiguration(configBuilder.build())
.endpointOverride(URI.create(ENDPOINT));
}
/**
* Simple servlet class that just waits 2 milliseconds to service a request then responds. Will be invoked by the "service"
* method, which is instrumented by the Agent. No point in manipulating response since it's a mock.
*/
private static class NormalServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
Thread.sleep(2);
} catch (Exception e) {
}
}
}
/**
* "Instrumented" servlet class that simulates the X-Ray SDK's filter by calling the pre-filter and post-filter
* methods around the activity of the servlet.
*/
private static class InstrumentedServlet extends HttpServlet {
private AWSXRayServletFilter filter = new AWSXRayServletFilter("Benchmark");
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
filter.preFilter(request, response);
try {
Thread.sleep(2);
} catch (Exception e) {
}
filter.postFilter(request, response);
}
}
}
| 3,934 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers/downstream/SqlHandlerIntegTest.java | package com.amazonaws.xray.agent.runtime.handlers.downstream;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.agent.runtime.handlers.downstream.source.sql.MyStatementImpl;
import com.amazonaws.xray.entities.Namespace;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.sql.SqlSubsegments;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.when;
/**
* Integ testing class for SQL calls. We use a stubbed out implementation of the JDBC Statement classes rather
* than mocks because mocking them interferes with Disco interception of their methods.
*/
public class SqlHandlerIntegTest {
private static final String QUERY = "SQL";
private static final String DB = "MY_DB";
private static final String DB_URL = "http://example.com";
private static final String DOMAIN = "example.com";
private Statement statement;
@Mock
private PreparedStatement preparedStatement;
@Mock
private CallableStatement callableStatement;
@Mock
private Connection mockConnection;
@Mock
private DatabaseMetaData mockMetaData;
@Before
public void setup() throws SQLException {
MockitoAnnotations.initMocks(this);
when(mockConnection.getCatalog()).thenReturn(DB);
when(mockConnection.getMetaData()).thenReturn(mockMetaData);
when(preparedStatement.getConnection()).thenReturn(mockConnection);
when(callableStatement.getConnection()).thenReturn(mockConnection);
when(mockMetaData.getURL()).thenReturn(DB_URL);
when(mockMetaData.getUserName()).thenReturn("user");
when(mockMetaData.getDriverVersion()).thenReturn("1.0");
when(mockMetaData.getDatabaseProductName()).thenReturn("MySQL");
when(mockMetaData.getDatabaseProductVersion()).thenReturn("2.0");
statement = new MyStatementImpl(mockConnection);
AWSXRay.beginSegment("test");
}
@After
public void cleanup() {
AWSXRay.clearTraceEntity();
}
@Test
public void testStatementCaptured() throws SQLException {
statement.executeQuery(QUERY);
assertThat(AWSXRay.getCurrentSegment().getSubsegments()).hasSize(1);
Subsegment sub = AWSXRay.getCurrentSegment().getSubsegments().get(0);
verifySubsegment(sub);
}
@Test
public void testPreparedStatementCaptured() throws SQLException {
preparedStatement.execute();
assertThat(AWSXRay.getCurrentSegment().getSubsegments()).hasSize(1);
Subsegment sub = AWSXRay.getCurrentSegment().getSubsegments().get(0);
verifySubsegment(sub);
}
@Test
public void testCallableStatementCaptured() throws SQLException {
callableStatement.execute();
assertThat(AWSXRay.getCurrentSegment().getSubsegments()).hasSize(1);
Subsegment sub = AWSXRay.getCurrentSegment().getSubsegments().get(0);
verifySubsegment(sub);
}
@Test
public void testSeveralQueriesOnStatement() throws SQLException {
statement.execute(QUERY);
statement.executeUpdate(QUERY);
statement.executeQuery(QUERY);
statement.executeLargeUpdate(QUERY);
assertThat(AWSXRay.getCurrentSegment().getSubsegments()).hasSize(4);
for (Subsegment sub : AWSXRay.getCurrentSegment().getSubsegments()) {
verifySubsegment(sub);
}
}
@Test
public void testExceptionIsRecordedAndThrown() {
assertThatThrownBy(() -> {
statement.executeUpdate(QUERY, 0); // Implemented to throw exception
}).isInstanceOf(SQLException.class);
assertThat(AWSXRay.getCurrentSegment().getSubsegments()).hasSize(1);
Subsegment sub = AWSXRay.getCurrentSegment().getSubsegments().get(0);
verifySubsegment(sub);
assertThat(sub.getCause().getExceptions()).hasSize(1);
}
@Test
public void testInternalQueriesDontGetCaptured() throws SQLException {
// Will be called by SqlSubsegments.forQuery
String user = "username";
when(mockMetaData.getUserName()).thenAnswer(new AnswerUsingQuery(statement, user));
statement.executeQuery(QUERY);
assertThat(AWSXRay.getCurrentSegment().getSubsegments()).hasSize(1);
Subsegment sub = AWSXRay.getCurrentSegment().getSubsegments().get(0);
assertThat(sub.getSql()).containsEntry(SqlSubsegments.USER, user);
verifySubsegment(sub);
}
private void verifySubsegment(Subsegment sub) {
assertThat(sub.getName()).isEqualTo(DB + "@" + DOMAIN);
assertThat(sub.getNamespace()).isEqualTo(Namespace.REMOTE.toString());
assertThat(sub.getSql()).containsEntry(SqlSubsegments.URL, DB_URL); // checking an arbitrary field in SQL namespace
assertThat(sub.isInProgress()).isFalse();
}
/**
* "Helper" class to simulate a getUserName() method whose internal implementation makes a query
*/
private static class AnswerUsingQuery implements Answer<String> {
private final Statement statement;
private final String user;
AnswerUsingQuery(Statement statement, String user) {
this.statement = statement;
this.user = user;
}
@Override
public String answer(InvocationOnMock invocationOnMock) throws Throwable {
statement.executeQuery("SELECT USER");
return user;
}
}
}
| 3,935 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers/downstream/AWSV2HandlerIntegTest.java | package com.amazonaws.xray.agent.runtime.handlers.downstream;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.Cause;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.async.EmptyPublisher;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.ListTablesRequest;
import software.amazon.awssdk.services.lambda.LambdaAsyncClient;
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.lambda.model.InvokeRequest;
import software.amazon.disco.agent.reflect.concurrent.TransactionContext;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import static org.mockito.ArgumentMatchers.any;
@RunWith(MockitoJUnitRunner.class)
public class AWSV2HandlerIntegTest {
@Before
public void setup() {
TransactionContext.create();
Emitter blankEmitter = Mockito.mock(Emitter.class);
Mockito.doReturn(true).when(blankEmitter).sendSegment(any());
AWSXRay.getGlobalRecorder().setEmitter(blankEmitter);
AWSXRay.clearTraceEntity();
AWSXRay.beginSegment("test");
}
@After
public void teardown() {
AWSXRay.endSegment();
TransactionContext.destroy();
}
private SdkHttpClient mockSdkHttpClient(SdkHttpResponse response) throws Exception {
return mockSdkHttpClient(response, "OK");
}
private SdkHttpClient mockSdkHttpClient(SdkHttpResponse response, String body) throws Exception {
ExecutableHttpRequest abortableCallable = Mockito.mock(ExecutableHttpRequest.class);
SdkHttpClient mockClient = Mockito.mock(SdkHttpClient.class);
Mockito.when(mockClient.prepareRequest(any())).thenReturn(abortableCallable);
Mockito.when(abortableCallable.call()).thenReturn(HttpExecuteResponse.builder()
.response(response)
.responseBody(AbortableInputStream.create(
new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8))
))
.build()
);
return mockClient;
}
private SdkAsyncHttpClient mockSdkAsyncHttpClient(SdkHttpResponse response) {
SdkAsyncHttpClient mockClient = Mockito.mock(SdkAsyncHttpClient.class);
Mockito.when(mockClient.execute(any(AsyncExecuteRequest.class))).thenAnswer((Answer<CompletableFuture<Void>>) invocationOnMock -> {
SdkAsyncHttpResponseHandler handler = invocationOnMock.getArgument(0, AsyncExecuteRequest.class).responseHandler();
handler.onHeaders(response);
handler.onStream(new EmptyPublisher<>());
return CompletableFuture.completedFuture(null);
});
return mockClient;
}
private SdkHttpResponse generateLambdaInvokeResponse(int statusCode) {
return SdkHttpResponse.builder()
.statusCode(statusCode)
.putHeader("x-amz-request-id", "1111-2222-3333-4444")
.putHeader("x-amz-id-2", "extended")
.putHeader("Content-Length", "2")
.putHeader("X-Amz-Function-Error", "Failure")
.build();
}
@Test
public void testResponseDescriptors() throws Exception {
String responseBody = "{\"LastEvaluatedTableName\":\"baz\",\"TableNames\":[\"foo\",\"bar\",\"baz\"]}";
SdkHttpResponse mockResponse = SdkHttpResponse.builder()
.statusCode(200)
.putHeader("x-amzn-requestid", "1111-2222-3333-4444")
.putHeader("Content-Length", "84")
.putHeader("Content-Type", "application/x-amz-json-1.0")
.build();
SdkHttpClient mockClient = mockSdkHttpClient(mockResponse, responseBody);
DynamoDbClient client = DynamoDbClient.builder()
.httpClient(mockClient)
.endpointOverride(URI.create("http://example.com"))
.region(Region.of("us-west-42"))
.credentialsProvider(StaticCredentialsProvider.create(
AwsSessionCredentials.create("key", "secret", "session")
))
.build();
Segment segment = AWSXRay.getCurrentSegment();
client.listTables(ListTablesRequest.builder()
.limit(3)
.build()
);
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
Map<String, Object> httpResponseStats = (Map<String, Object>)subsegment.getHttp().get("response");
Assert.assertEquals("ListTables", awsStats.get("operation"));
Assert.assertEquals(3, awsStats.get("limit"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals(3, awsStats.get("table_count"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(0, awsStats.get("retries"));
Assert.assertEquals(84L, httpResponseStats.get("content_length"));
Assert.assertEquals(200, httpResponseStats.get("status"));
Assert.assertEquals(false, subsegment.isInProgress());
}
@Test
public void testLambdaInvokeSubsegmentContainsFunctionName() throws Exception {
SdkHttpClient mockClient = mockSdkHttpClient(generateLambdaInvokeResponse(200));
LambdaClient client = LambdaClient.builder()
.httpClient(mockClient)
.endpointOverride(URI.create("http://example.com"))
.region(Region.of("us-west-42"))
.credentialsProvider(StaticCredentialsProvider.create(
AwsSessionCredentials.create("key", "secret", "session")
))
.build();
Segment segment = AWSXRay.getCurrentSegment();
client.invoke(InvokeRequest.builder()
.functionName("testFunctionName")
.build()
);
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
Map<String, Object> httpResponseStats = (Map<String, Object>)subsegment.getHttp().get("response");
Assert.assertEquals("Invoke", awsStats.get("operation"));
Assert.assertEquals("testFunctionName", awsStats.get("function_name"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals("extended", awsStats.get("id_2"));
Assert.assertEquals("Failure", awsStats.get("function_error"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(0, awsStats.get("retries"));
Assert.assertEquals(2L, httpResponseStats.get("content_length"));
Assert.assertEquals(200, httpResponseStats.get("status"));
Assert.assertEquals(false, subsegment.isInProgress());
}
@Test
public void testAsyncLambdaInvokeSubsegmentContainsFunctionName() {
SdkAsyncHttpClient mockClient = mockSdkAsyncHttpClient(generateLambdaInvokeResponse(200));
LambdaAsyncClient client = LambdaAsyncClient.builder()
.httpClient(mockClient)
.endpointOverride(URI.create("http://example.com"))
.region(Region.of("us-west-42"))
.credentialsProvider(StaticCredentialsProvider.create(
AwsSessionCredentials.create("key", "secret", "session")
))
.build();
Segment segment = AWSXRay.getCurrentSegment();
client.invoke(InvokeRequest.builder()
.functionName("testFunctionName")
.build()
).join();
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
Map<String, Object> httpResponseStats = (Map<String, Object>)subsegment.getHttp().get("response");
Assert.assertEquals("Invoke", awsStats.get("operation"));
Assert.assertEquals("testFunctionName", awsStats.get("function_name"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals("extended", awsStats.get("id_2"));
Assert.assertEquals("Failure", awsStats.get("function_error"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(0, awsStats.get("retries"));
Assert.assertEquals(2L, httpResponseStats.get("content_length"));
Assert.assertEquals(200, httpResponseStats.get("status"));
Assert.assertEquals(false, subsegment.isInProgress());
}
@Test
public void test400Exception() throws Exception {
SdkHttpClient mockClient = mockSdkHttpClient(generateLambdaInvokeResponse(400));
LambdaClient client = LambdaClient.builder()
.httpClient(mockClient)
.endpointOverride(URI.create("http://example.com"))
.region(Region.of("us-west-42"))
.credentialsProvider(StaticCredentialsProvider.create(
AwsSessionCredentials.create("key", "secret", "session")
))
.build();
Segment segment = AWSXRay.getCurrentSegment();
try {
client.invoke(InvokeRequest.builder()
.functionName("testFunctionName")
.build()
);
} catch (Exception e) {
// ignore SDK errors
} finally {
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
Map<String, Object> httpResponseStats = (Map<String, Object>)subsegment.getHttp().get("response");
Cause cause = subsegment.getCause();
Assert.assertEquals("Invoke", awsStats.get("operation"));
Assert.assertEquals("testFunctionName", awsStats.get("function_name"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals("extended", awsStats.get("id_2"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(0, awsStats.get("retries"));
Assert.assertEquals(2L, httpResponseStats.get("content_length"));
Assert.assertEquals(400, httpResponseStats.get("status"));
Assert.assertEquals(false, subsegment.isInProgress());
Assert.assertEquals(true, subsegment.isError());
Assert.assertEquals(false, subsegment.isThrottle());
Assert.assertEquals(false, subsegment.isFault());
Assert.assertEquals(1, cause.getExceptions().size());
Assert.assertEquals(true, cause.getExceptions().get(0).isRemote());
}
}
@Test
public void testAsync400Exception() {
SdkAsyncHttpClient mockClient = mockSdkAsyncHttpClient(generateLambdaInvokeResponse(400));
LambdaAsyncClient client = LambdaAsyncClient.builder()
.httpClient(mockClient)
.endpointOverride(URI.create("http://example.com"))
.region(Region.of("us-west-42"))
.credentialsProvider(StaticCredentialsProvider.create(
AwsSessionCredentials.create("key", "secret", "session")
))
.build();
Segment segment = AWSXRay.getCurrentSegment();
try {
client.invoke(InvokeRequest.builder()
.functionName("testFunctionName")
.build()
).get();
} catch (Exception e) {
// ignore exceptions
} finally {
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
Map<String, Object> httpResponseStats = (Map<String, Object>)subsegment.getHttp().get("response");
Cause cause = subsegment.getCause();
Assert.assertEquals("Invoke", awsStats.get("operation"));
Assert.assertEquals("testFunctionName", awsStats.get("function_name"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals("extended", awsStats.get("id_2"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(0, awsStats.get("retries"));
Assert.assertEquals(2L, httpResponseStats.get("content_length"));
Assert.assertEquals(400, httpResponseStats.get("status"));
Assert.assertEquals(false, subsegment.isInProgress());
Assert.assertEquals(true, subsegment.isError());
Assert.assertEquals(false, subsegment.isThrottle());
Assert.assertEquals(false, subsegment.isFault());
Assert.assertEquals(1, cause.getExceptions().size());
Assert.assertEquals(true, cause.getExceptions().get(0).isRemote());
}
}
@Test
public void testThrottledException() throws Exception {
SdkHttpClient mockClient = mockSdkHttpClient(generateLambdaInvokeResponse(429));
LambdaClient client = LambdaClient.builder()
.httpClient(mockClient)
.endpointOverride(URI.create("http://example.com"))
.region(Region.of("us-west-42"))
.credentialsProvider(StaticCredentialsProvider.create(
AwsSessionCredentials.create("key", "secret", "session")
))
.build();
Segment segment = AWSXRay.getCurrentSegment();
try {
client.invoke(InvokeRequest.builder()
.functionName("testFunctionName")
.build()
);
} catch (Exception e) {
// ignore SDK errors
} finally {
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
Map<String, Object> httpResponseStats = (Map<String, Object>)subsegment.getHttp().get("response");
Cause cause = subsegment.getCause();
Assert.assertEquals("Invoke", awsStats.get("operation"));
Assert.assertEquals("testFunctionName", awsStats.get("function_name"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals("extended", awsStats.get("id_2"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(2L, httpResponseStats.get("content_length"));
Assert.assertEquals(429, httpResponseStats.get("status"));
Assert.assertEquals(true, subsegment.isError());
Assert.assertEquals(true, subsegment.isThrottle());
Assert.assertEquals(false, subsegment.isFault());
Assert.assertEquals(1, cause.getExceptions().size());
Assert.assertEquals(true, cause.getExceptions().get(0).isRemote());
}
}
@Test
public void testAsyncThrottledException() {
SdkAsyncHttpClient mockClient = mockSdkAsyncHttpClient(generateLambdaInvokeResponse(429));
LambdaAsyncClient client = LambdaAsyncClient.builder()
.httpClient(mockClient)
.endpointOverride(URI.create("http://example.com"))
.region(Region.of("us-west-42"))
.credentialsProvider(StaticCredentialsProvider.create(
AwsSessionCredentials.create("key", "secret", "session")
))
.build();
Segment segment = AWSXRay.getCurrentSegment();
try {
client.invoke(InvokeRequest.builder()
.functionName("testFunctionName")
.build()
).join();
} catch (Exception e) {
// ignore exceptions
} finally {
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
Map<String, Object> httpResponseStats = (Map<String, Object>)subsegment.getHttp().get("response");
Cause cause = subsegment.getCause();
Assert.assertEquals("Invoke", awsStats.get("operation"));
Assert.assertEquals("testFunctionName", awsStats.get("function_name"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals("extended", awsStats.get("id_2"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(2L, httpResponseStats.get("content_length"));
Assert.assertEquals(429, httpResponseStats.get("status"));
Assert.assertEquals(true, subsegment.isError());
Assert.assertEquals(true, subsegment.isThrottle());
Assert.assertEquals(false, subsegment.isFault());
Assert.assertEquals(1, cause.getExceptions().size());
Assert.assertEquals(true, cause.getExceptions().get(0).isRemote());
}
}
@Test
public void test500Exception() throws Exception {
SdkHttpClient mockClient = mockSdkHttpClient(generateLambdaInvokeResponse(500));
LambdaClient client = LambdaClient.builder()
.httpClient(mockClient)
.endpointOverride(URI.create("http://example.com"))
.region(Region.of("us-west-42"))
.credentialsProvider(StaticCredentialsProvider.create(
AwsSessionCredentials.create("key", "secret", "session")
))
.build();
Segment segment = AWSXRay.getCurrentSegment();
try {
client.invoke(InvokeRequest.builder()
.functionName("testFunctionName")
.build()
);
} catch (Exception e) {
// ignore SDK errors
} finally {
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
Map<String, Object> httpResponseStats = (Map<String, Object>)subsegment.getHttp().get("response");
Cause cause = subsegment.getCause();
Assert.assertEquals("Invoke", awsStats.get("operation"));
Assert.assertEquals("testFunctionName", awsStats.get("function_name"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals("extended", awsStats.get("id_2"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(2L, httpResponseStats.get("content_length"));
Assert.assertEquals(500, httpResponseStats.get("status"));
Assert.assertEquals(false, subsegment.isError());
Assert.assertEquals(false, subsegment.isThrottle());
Assert.assertEquals(true, subsegment.isFault());
Assert.assertEquals(1, cause.getExceptions().size());
Assert.assertEquals(true, cause.getExceptions().get(0).isRemote());
}
}
@Test
public void testAsync500Exception() {
SdkAsyncHttpClient mockClient = mockSdkAsyncHttpClient(generateLambdaInvokeResponse(500));
LambdaAsyncClient client = LambdaAsyncClient.builder()
.httpClient(mockClient)
.endpointOverride(URI.create("http://example.com"))
.region(Region.of("us-west-42"))
.credentialsProvider(StaticCredentialsProvider.create(
AwsSessionCredentials.create("key", "secret", "session")
))
.build();
Segment segment = AWSXRay.getCurrentSegment();
try {
client.invoke(InvokeRequest.builder()
.functionName("testFunctionName")
.build()
).join();
} catch (Exception e) {
// ignore exceptions
} finally {
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
Map<String, Object> httpResponseStats = (Map<String, Object>)subsegment.getHttp().get("response");
Cause cause = subsegment.getCause();
Assert.assertEquals("Invoke", awsStats.get("operation"));
Assert.assertEquals("testFunctionName", awsStats.get("function_name"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals("extended", awsStats.get("id_2"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(2L, httpResponseStats.get("content_length"));
Assert.assertEquals(500, httpResponseStats.get("status"));
Assert.assertEquals(false, subsegment.isError());
Assert.assertEquals(false, subsegment.isThrottle());
Assert.assertEquals(true, subsegment.isFault());
Assert.assertEquals(1, cause.getExceptions().size());
Assert.assertEquals(true, cause.getExceptions().get(0).isRemote());
}
}
@Test
public void testMissingContentLength() throws Exception {
String responseBody = "{\"LastEvaluatedTableName\":\"baz\",\"TableNames\":[\"foo\",\"bar\",\"baz\"]}";
SdkHttpResponse mockResponse = SdkHttpResponse.builder()
.statusCode(200)
.putHeader("x-amzn-requestid", "1111-2222-3333-4444")
.putHeader("Content-Type", "application/x-amz-json-1.0")
.build();
SdkHttpClient mockClient = mockSdkHttpClient(mockResponse, responseBody);
DynamoDbClient client = DynamoDbClient.builder()
.httpClient(mockClient)
.endpointOverride(URI.create("http://example.com"))
.region(Region.of("us-west-42"))
.credentialsProvider(StaticCredentialsProvider.create(
AwsSessionCredentials.create("key", "secret", "session")
))
.build();
Segment segment = AWSXRay.getCurrentSegment();
client.listTables();
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
Map<String, Object> httpResponseStats = (Map<String, Object>)subsegment.getHttp().get("response");
Assert.assertEquals("ListTables", awsStats.get("operation"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(200, httpResponseStats.get("status"));
Assert.assertEquals(false, subsegment.isInProgress());
}
}
| 3,936 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers/downstream/SqlPrepareHandlerIntegTest.java | package com.amazonaws.xray.agent.runtime.handlers.downstream;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.agent.runtime.handlers.downstream.source.sql.MyConnectionImpl;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.sql.SqlSubsegments;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
public class SqlPrepareHandlerIntegTest {
private static final String SQL = "SELECT * FROM my_table";
private Connection connection;
@Mock
private PreparedStatement preparedStatement;
@Mock
private CallableStatement callableStatement;
@Mock
private DatabaseMetaData mockMetadata;
@Before
public void setup() throws SQLException {
MockitoAnnotations.initMocks(this);
connection = new MyConnectionImpl(preparedStatement, callableStatement, mockMetadata);
when(preparedStatement.getConnection()).thenReturn(connection);
when(preparedStatement.toString()).thenReturn(null);
when(callableStatement.getConnection()).thenReturn(connection);
when(callableStatement.toString()).thenReturn(null);
when(mockMetadata.getURL()).thenReturn("http://example.com");
when(mockMetadata.getUserName()).thenReturn("user");
when(mockMetadata.getDriverVersion()).thenReturn("1.0");
when(mockMetadata.getDatabaseProductName()).thenReturn("MySQL");
when(mockMetadata.getDatabaseProductVersion()).thenReturn("2.0");
AWSXRay.beginSegment("test");
}
@After
public void cleanup() {
AWSXRay.clearTraceEntity();
}
@Test
public void testPreparedStatementQueryCaptured() throws SQLException {
connection.prepareStatement(SQL); // insert into map
preparedStatement.execute();
assertThat(AWSXRay.getCurrentSegment().getSubsegments()).hasSize(1);
Subsegment sub = AWSXRay.getCurrentSegment().getSubsegments().get(0);
assertThat(sub.getSql()).containsEntry(SqlSubsegments.SANITIZED_QUERY, SQL);
}
@Test
public void testCallableStatementQueryCaptured() throws SQLException {
connection.prepareCall(SQL); // insert into map
callableStatement.execute();
assertThat(AWSXRay.getCurrentSegment().getSubsegments()).hasSize(1);
Subsegment sub = AWSXRay.getCurrentSegment().getSubsegments().get(0);
assertThat(sub.getSql()).containsEntry(SqlSubsegments.SANITIZED_QUERY, SQL);
}
}
| 3,937 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers/downstream/HttpClientHandlerIntegTest.java | package com.amazonaws.xray.agent.runtime.handlers.downstream;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.entities.Namespace;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.entities.TraceHeader.SampleDecision;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.net.URI;
import java.util.Map;
import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.ok;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class HttpClientHandlerIntegTest {
private static final String TRACE_HEADER_KEY = TraceHeader.HEADER_KEY;
private static final int PORT = 8089;
private static final String ENDPOINT = "http://127.0.0.1:" + PORT;
private Segment currentSegment;
@Rule
public WireMockRule wireMockRule = new WireMockRule(PORT);
@Before
public void setup() {
// Initializing WireMock tricks the agent into thinking an HTTP call is being made, which creates subsegments,
// so this segment is needed to avoid CMEs. It will be overridden with a fresh segment.
AWSXRay.beginSegment("ignore");
stubFor(get(anyUrl()).willReturn(ok()));
stubFor(post(anyUrl())
.willReturn(ok().withHeader("content-length", "42")));
// Generate the segment that would be normally made by the upstream instrumentor
currentSegment = AWSXRay.beginSegment("parentSegment");
}
@After
public void cleanup() {
AWSXRay.clearTraceEntity();
}
@Test
public void testBasicGetCall() throws Exception {
URI uri = new URI(ENDPOINT);
HttpClient httpClient = HttpClients.createMinimal();
HttpGet request = new HttpGet(uri);
HttpResponse httpResponse = httpClient.execute(request);
assertThat(currentSegment.getSubsegments()).hasSize(1);
Subsegment currentSubsegment = currentSegment.getSubsegments().get(0);
// Check Subsegment properties
assertThat(currentSubsegment.getName()).isEqualTo(uri.getHost());
assertThat(currentSubsegment.getNamespace()).isEqualTo(Namespace.REMOTE.toString());
assertThat(currentSubsegment.isInProgress()).isFalse();
// Check for http-specific request info
Map<String, Object> requestMap = (Map<String, Object>) currentSubsegment.getHttp().get("request");
assertThat(requestMap).hasSize(2);
assertThat(requestMap).containsEntry("method", "GET");
assertThat(requestMap).containsEntry("url", uri.toString());
// Check for http-specific response info
Map<String, Object> responseMap = (Map<String, Object>) currentSubsegment.getHttp().get("response");
assertThat(responseMap).hasSize(1);
assertThat(responseMap).containsEntry("status", httpResponse.getStatusLine().getStatusCode());
}
@Test
public void testTraceHeaderPropagation() throws Exception {
URI uri = new URI(ENDPOINT);
HttpClient httpClient = HttpClients.createMinimal();
HttpGet request = new HttpGet(uri);
httpClient.execute(request);
assertThat(currentSegment.getSubsegments()).hasSize(1);
Subsegment currentSubsegment = currentSegment.getSubsegments().get(0);
// Check for Trace propagation
Header httpTraceHeader = request.getAllHeaders()[0];
assertThat(httpTraceHeader.getName()).isEqualTo(TRACE_HEADER_KEY);
TraceHeader injectedTH = TraceHeader.fromString(httpTraceHeader.getValue());
SampleDecision sampleDecision = currentSegment.isSampled() ? SampleDecision.SAMPLED : SampleDecision.NOT_SAMPLED;
assertThat(injectedTH.toString())
.isEqualTo(new TraceHeader(currentSegment.getTraceId(), currentSubsegment.getId(), sampleDecision).toString()); // Trace header should be added
}
@Test
public void testBasicPostCall() throws Exception {
URI uri = new URI(ENDPOINT);
HttpClient httpClient = HttpClients.createMinimal();
HttpPost request = new HttpPost(uri);
HttpResponse httpResponse = httpClient.execute(request);
assertThat(currentSegment.getSubsegments()).hasSize(1);
Subsegment currentSubsegment = currentSegment.getSubsegments().get(0);
// Check Subsegment properties
assertThat(currentSubsegment.getName()).isEqualTo(uri.getHost());
assertThat(currentSubsegment.getNamespace()).isEqualTo(Namespace.REMOTE.toString());
assertThat(currentSubsegment.isInProgress()).isFalse();
// Check for http-specific request info
Map<String, Object> requestMap = (Map<String, Object>) currentSubsegment.getHttp().get("request");
assertThat(requestMap).hasSize(2);
assertThat(requestMap).containsEntry("method", "POST");
assertThat(requestMap).containsEntry("url", uri.toString());
// Check for http-specific response info
Map<String, Object> responseMap = (Map<String, Object>) currentSubsegment.getHttp().get("response");
assertThat(responseMap).hasSize(2);
assertThat(responseMap).containsEntry("status", httpResponse.getStatusLine().getStatusCode());
assertThat(responseMap).containsEntry("content_length", 42L);
}
@Test
public void testChainedCalls() throws Exception {
URI uri = new URI(ENDPOINT);
HttpClient httpClient = HttpClients.createMinimal();
HttpPost request = new HttpPost(uri);
assertThat(currentSegment.getSubsegments()).isEmpty();
httpClient.execute(request);
assertThat(currentSegment.getSubsegments()).hasSize(1);
httpClient.execute(request);
assertThat(currentSegment.getSubsegments()).hasSize(2);
}
@Test
public void testInvalidTargetHost() throws Exception {
URI uri = new URI("sdfkljdfs");
HttpClient httpClient = HttpClients.createMinimal();
HttpGet request = new HttpGet(uri);
assertThatThrownBy(() -> httpClient.execute(request)).isInstanceOf(IllegalArgumentException.class);
assertThat(currentSegment.getSubsegments()).hasSize(1);
Subsegment currentSubsegment = currentSegment.getSubsegments().get(0);
assertThat(currentSubsegment.getName()).isEqualTo(uri.toString());
assertThat(currentSubsegment.getCause().getExceptions()).hasSize(1);
assertThat(currentSubsegment.getCause().getExceptions().get(0).getThrowable()).isInstanceOf(IllegalArgumentException.class);
assertThat(currentSubsegment.getNamespace()).isEqualTo(Namespace.REMOTE.toString());
assertThat(currentSubsegment.isFault()).isTrue();
assertThat(currentSubsegment.isError()).isFalse();
assertThat(currentSubsegment.isInProgress()).isFalse();
// Even in failures, we should at least see the requested information.
Map<String, String> requestMap = (Map<String, String>) currentSubsegment.getHttp().get("request");
assertThat(requestMap).hasSize(2);
assertThat(requestMap).containsEntry("method", "GET");
assertThat(requestMap).containsEntry("url", uri.toString());
// No response because we passed in an invalid request.
assertThat(currentSubsegment.getHttp()).doesNotContainKey("response");
}
@Test
public void testIgnoreSamplingCalls() throws Exception {
URI targetsUri = new URI(ENDPOINT + "/SamplingTargets");
URI rulesUri = new URI(ENDPOINT + "/GetSamplingRules");
HttpClient httpClient = HttpClients.createMinimal();
HttpGet request = new HttpGet(targetsUri);
httpClient.execute(request);
assertThat(currentSegment.getSubsegments()).isEmpty();
request = new HttpGet(rulesUri);
httpClient.execute(request);
assertThat(currentSegment.getSubsegments()).isEmpty();
}
}
| 3,938 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers/downstream/AWSHandlerIntegTest.java | package com.amazonaws.xray.agent.runtime.handlers.downstream;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.http.AmazonHttpClient;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException;
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.lambda.AWSLambdaClientBuilder;
import com.amazonaws.services.lambda.model.InvokeRequest;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.AmazonSNSClientBuilder;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSClientBuilder;
import com.amazonaws.services.xray.AWSXRayClientBuilder;
import com.amazonaws.services.xray.model.GetSamplingRulesRequest;
import com.amazonaws.services.xray.model.GetSamplingTargetsRequest;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.agent.runtime.handlers.downstream.source.http.MockHttpClient;
import com.amazonaws.xray.entities.Namespace;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.TraceHeader;
import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.powermock.reflect.Whitebox;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class AWSHandlerIntegTest {
private final static String TRACE_HEADER_KEY = TraceHeader.HEADER_KEY;
private Segment currentSegment;
// Adopted from the AWS X-Ray SDK for Java - AWS package unit test.
// https://github.com/aws/aws-xray-sdk-java/blob/master/aws-xray-recorder-sdk-aws-sdk/src/test/java/com/amazonaws/xray/handlers/TracingHandlerTest.java#L61
private MockHttpClient mockHttpClient(Object client, String responseContent) {
AmazonHttpClient amazonHttpClient = new AmazonHttpClient(new ClientConfiguration());
MockHttpClient apacheHttpClient = new MockHttpClient();
apacheHttpClient.setResponseContent(responseContent);
Whitebox.setInternalState(amazonHttpClient, "httpClient", apacheHttpClient);
Whitebox.setInternalState(client, "client", amazonHttpClient);
return apacheHttpClient;
}
/**
* Creates a testable AWS SDK client by adding fake credentials and a predetermined region.
* @param builder The AWS SDK Builder for a given service
* @return The modified builder which could build a testable client
*/
private AwsClientBuilder createTestableClient(AwsClientBuilder builder) {
AWSCredentialsProvider fakeCredentials = new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake"));
return builder
.withRegion(Regions.US_WEST_2)
.withCredentials(fakeCredentials);
}
@Before
public void setup() {
// Generate the segment that would be normally made by the upstream instrumentor
currentSegment = AWSXRay.beginSegment("awsSegment");
}
@After
public void cleanup() {
AWSXRay.clearTraceEntity();
currentSegment = null;
}
@Test
public void testDynamoDBListTable() {
AmazonDynamoDB client = (AmazonDynamoDB) createTestableClient(AmazonDynamoDBClientBuilder.standard()).build();
// Acquired by intercepting the HTTP Request and copying the raw JSON.
String result = "{\"TableNames\":[\"ATestTable\",\"dynamodb-user\",\"some_random_table\",\"scorekeep-game\",\"scorekeep-move\",\"scorekeep-session\",\"scorekeep-state\",\"scorekeep-user\"]}";
mockHttpClient(client, result);
client.listTables();
assertEquals(1, currentSegment.getSubsegments().size());
Subsegment currentSubsegment = currentSegment.getSubsegments().get(0);
assertEquals("AmazonDynamoDBv2", currentSubsegment.getName());
assertEquals(Namespace.AWS.toString(), currentSubsegment.getNamespace());
Map<String, Object> awsMap = currentSubsegment.getAws();
assertEquals("ListTables", awsMap.get("operation"));
assertEquals(8, awsMap.get("table_count"));
Map<String, String> httpResponseMap = (Map<String, String>) currentSubsegment.getHttp().get("response");
assertEquals(200, httpResponseMap.get("status"));
}
@Test
public void testSQSSendMessage() {
AmazonSQS sqs = (AmazonSQS) createTestableClient(AmazonSQSClientBuilder.standard()).build();
// XML acquired by intercepting a valid AWS SQS response.
String result = "<SendMessageResponse xmlns=\"http://queue.amazonaws.com/doc/2012-11-05/\">\n" +
"\t<SendMessageResult>\n" +
"\t\t<MessageId>de9e2f1b-aa00-43a6-84b8-b5379085c0f2</MessageId>\n" +
"\t\t<MD5OfMessageBody>c1ddd94da830e09533d058f67d4ef56a</MD5OfMessageBody>\n" +
"\t</SendMessageResult>\n" +
"\t<ResponseMetadata>\n" +
"\t\t<RequestId>41edd773-d43f-5493-b43b-814e965a23f1</RequestId>\n" +
"\t</ResponseMetadata>\n" +
"</SendMessageResponse>";
mockHttpClient(sqs, result);
sqs.sendMessage("https://sqs.us-west-2.amazonaws.com/123611858231/xray-queue", "Koo lai ahh");
assertEquals(1, currentSegment.getSubsegments().size());
Subsegment currentSubsegment = currentSegment.getSubsegments().get(0);
assertEquals("AmazonSQS", currentSubsegment.getName());
assertEquals(Namespace.AWS.toString(), currentSubsegment.getNamespace());
// Validate AWS Response
Map<String, Object> awsMap = currentSubsegment.getAws();
assertEquals("SendMessage", awsMap.get("operation"));
assertEquals("https://sqs.us-west-2.amazonaws.com/123611858231/xray-queue", awsMap.get("queue_url"));
assertEquals("41edd773-d43f-5493-b43b-814e965a23f1", awsMap.get("request_id"));
assertEquals("de9e2f1b-aa00-43a6-84b8-b5379085c0f2", awsMap.get("message_id"));
assertEquals("[]", awsMap.get("message_attribute_names").toString());
Map<String, String> httpResponseMap = (Map<String, String>) currentSubsegment.getHttp().get("response");
assertEquals(200, httpResponseMap.get("status"));
}
@Test
public void testSNSCreateTopic() {
AmazonSNS sns = (AmazonSNS) createTestableClient(AmazonSNSClientBuilder.standard()).build();
String result =
"<CreateTopicResponse xmlns=\"http://sns.amazonaws.com/doc/2010-03-31/\">\n" +
" <CreateTopicResult>\n" +
" <TopicArn>arn:aws:sns:us-west-2:223528386801:testTopic</TopicArn>\n" +
" </CreateTopicResult>\n" +
" <ResponseMetadata>\n" +
" <RequestId>03e28ac9-f5a1-599b-8b57-dcf4b3ef028d</RequestId>\n" +
" </ResponseMetadata>\n" +
"</CreateTopicResponse>";
mockHttpClient(sns, result);
sns.createTopic("testTopic");
assertEquals(1, currentSegment.getSubsegments().size());
Subsegment currentSubsegment = currentSegment.getSubsegments().get(0);
assertEquals("AmazonSNS", currentSubsegment.getName());
assertEquals(Namespace.AWS.toString(), currentSubsegment.getNamespace());
// Validate AWS Response
Map<String, Object> awsMap = currentSubsegment.getAws();
assertEquals("CreateTopic", awsMap.get("operation"));
assertEquals("03e28ac9-f5a1-599b-8b57-dcf4b3ef028d", awsMap.get("request_id"));
Map<String, String> httpResponseMap = (Map<String, String>) currentSubsegment.getHttp().get("response");
assertEquals(200, httpResponseMap.get("status"));
}
@Test
public void testS3CreatesHttpClientSubsegment() {
// We know that S3 isn't supported. But when we do, this test should fail.
// This is a reminder to add Integ tests to S3 clients.
// Because the HttpClient handler is enabled, this will generate an httpClient subsegment.
// Though it's not as informative as an AWS subsegment, this still may provide some insight.
AmazonS3 s3 = (AmazonS3) createTestableClient(AmazonS3ClientBuilder.standard()).build();
String data = "testData";
mockHttpClient(s3, data);
InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(data.getBytes().length);
PutObjectRequest putRequest = new PutObjectRequest("fake-testing-bucket-jkwjfkdsf", "test.txt", stream, objectMetadata);
s3.putObject(putRequest);
assertEquals(1, currentSegment.getSubsegments().size());
Subsegment currentSubsegment = currentSegment.getSubsegments().get(0);
assertEquals("fake-testing-bucket-jkwjfkdsf.s3.us-west-2.amazonaws.com", currentSubsegment.getName());
Map<String, String> requestMap = (Map<String, String>) currentSubsegment.getHttp().get("request");
assertEquals("PUT", requestMap.get("method"));
assertEquals("https://fake-testing-bucket-jkwjfkdsf.s3.us-west-2.amazonaws.com/test.txt", requestMap.get("url"));
Map<String, String> responseMap = (Map<String, String>) currentSubsegment.getHttp().get("response");
assertEquals(200, responseMap.get("status"));
}
@Test
public void testLambda() {
// Setup test
AWSLambda lambda = (AWSLambda) createTestableClient(AWSLambdaClientBuilder.standard()).build();
mockHttpClient(lambda, "null"); // Lambda returns "null" on successful fn. with no return value
InvokeRequest request = new InvokeRequest();
request.setFunctionName("testFunctionName");
lambda.invoke(request);
assertEquals(1, currentSegment.getSubsegments().size());
Subsegment currentSubsegment = currentSegment.getSubsegments().get(0);
Map<String, Object> awsMap = currentSubsegment.getAws();
assertEquals("Invoke", awsMap.get("operation"));
assertEquals("testFunctionName", awsMap.get("function_name"));
}
@Test
public void testShouldNotTraceXRaySamplingOperations() {
com.amazonaws.services.xray.AWSXRay xray = (com.amazonaws.services.xray.AWSXRay) createTestableClient(AWSXRayClientBuilder.standard()).build();
mockHttpClient(xray, null);
xray.getSamplingRules(new GetSamplingRulesRequest());
assertEquals(0, currentSegment.getSubsegments().size());
xray.getSamplingTargets(new GetSamplingTargetsRequest());
assertEquals(0, currentSegment.getSubsegments().size());
}
@Test
public void testTraceHeaderPropagation() throws Exception {
AmazonDynamoDB client = (AmazonDynamoDB) createTestableClient(AmazonDynamoDBClientBuilder.standard()).build();
String result = "{\"TableNames\":[\"ATestTable\",\"dynamodb-user\",\"some_random_table\",\"scorekeep-game\",\"scorekeep-move\",\"scorekeep-session\",\"scorekeep-state\",\"scorekeep-user\"]}";
MockHttpClient httpClient = mockHttpClient(client, result);
client.listTables();
assertEquals(1, currentSegment.getSubsegments().size());
Subsegment currentSubsegment = currentSegment.getSubsegments().get(0);
// Find the trace header if it was injected.
HttpRequest request = httpClient.getLastRequest();
String traceHeader = null;
for (Header h : request.getAllHeaders()) {
if (h.getName().equals(TRACE_HEADER_KEY)) {
traceHeader = h.getValue();
break;
}
}
assertNotNull(traceHeader);
// Validate the trace header.
TraceHeader injectedTH = TraceHeader.fromString(traceHeader);
TraceHeader.SampleDecision ourSampleDecision = currentSegment.isSampled() ?
TraceHeader.SampleDecision.SAMPLED : TraceHeader.SampleDecision.NOT_SAMPLED;
TraceHeader ourTraceHeader = new TraceHeader(currentSegment.getTraceId(), currentSubsegment.getId(), ourSampleDecision);
// The trace header is as expected!
assertEquals(ourTraceHeader.toString(), injectedTH.toString());
}
@Test
public void testAWSCallsDontGenerateHttpSubsegments() {
// Ensure that the underlying HttpClient does not get instrumented
AmazonDynamoDB client = (AmazonDynamoDB) createTestableClient(AmazonDynamoDBClientBuilder.standard()).build();
String result = "{\"TableNames\":[\"ATestTable\",\"dynamodb-user\",\"some_random_table\",\"scorekeep-game\",\"scorekeep-move\",\"scorekeep-session\",\"scorekeep-state\",\"scorekeep-user\"]}";
mockHttpClient(client, result);
client.listTables();
assertEquals(1, currentSegment.getSubsegments().size());
Subsegment currentSubsegment = currentSegment.getSubsegments().get(0);
assertEquals(0, currentSubsegment.getSubsegments().size());
}
@Test
public void testAwsClientFailure() {
AmazonDynamoDB client = (AmazonDynamoDB) createTestableClient(AmazonDynamoDBClientBuilder.standard()).build();
String result = null;
mockHttpClient(client, result);
AmazonHttpClient amazonHttpClient = mock(AmazonHttpClient.class);
when(amazonHttpClient.execute(any(), any(), any(), any())).thenThrow(new SdkClientException("Fake timeout exception"));
Whitebox.setInternalState(client, "client", amazonHttpClient);
try {
client.listTables();
assertFalse(true); // Fail if we get here
} catch(SdkClientException e) {
// We expect to catch this.
}
// Make sure the subsegment has the exception stored.
assertEquals(1, currentSegment.getSubsegments().size());
Subsegment currentSubsegment = currentSegment.getSubsegments().get(0);
assertEquals("AmazonDynamoDBv2", currentSubsegment.getName());
assertEquals(Namespace.AWS.toString(), currentSubsegment.getNamespace());
Map<String, Object> awsMap = currentSubsegment.getAws();
assertEquals("ListTables", awsMap.get("operation"));
assertTrue(currentSubsegment.isFault());
assertEquals(SdkClientException.class, currentSubsegment.getCause().getExceptions().get(0).getThrowable().getClass());
assertEquals("Fake timeout exception", currentSubsegment.getCause().getExceptions().get(0).getThrowable().getMessage());
}
@Test
public void testAwsServiceFailure() {
AmazonDynamoDB client = (AmazonDynamoDB) createTestableClient(AmazonDynamoDBClientBuilder.standard()).build();
String result = null;
mockHttpClient(client, result);
AmazonHttpClient amazonHttpClient = mock(AmazonHttpClient.class);
AmazonDynamoDBException myException = new AmazonDynamoDBException("Failed to get response from DynamoDB");
myException.setServiceName("AmazonDynamoDBv2");
myException.setErrorCode("FakeErrorCode");
myException.setRequestId("FakeRequestId");
when(amazonHttpClient.execute(any(), any(), any(), any())).thenThrow(myException);
Whitebox.setInternalState(client, "client", amazonHttpClient);
try {
client.listTables();
assertFalse(true); // Fail if we get here
} catch(AmazonServiceException e) {
// We expect to catch this.
}
// Make sure the subsegment has the exception stored.
assertEquals(1, currentSegment.getSubsegments().size());
Subsegment currentSubsegment = currentSegment.getSubsegments().get(0);
assertEquals("AmazonDynamoDBv2", currentSubsegment.getName());
assertEquals(Namespace.AWS.toString(), currentSubsegment.getNamespace());
Map<String, Object> awsMap = currentSubsegment.getAws();
assertEquals("ListTables", awsMap.get("operation"));
assertTrue(currentSubsegment.isFault());
assertEquals(AmazonDynamoDBException.class, currentSubsegment.getCause().getExceptions().get(0).getThrowable().getClass());
}
}
| 3,939 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers/downstream/source | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers/downstream/source/http/MockHttpClient.java | package com.amazonaws.xray.agent.runtime.handlers.downstream.source.http;
import com.amazonaws.http.apache.client.impl.ConnectionManagerAwareHttpClient;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.io.EmptyInputStream;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
/**
* TODO: When Disco removes its data accessor pattern in a future version, delete this & use a mock instead
*/
public class MockHttpClient implements ConnectionManagerAwareHttpClient {
private String responseContent;
private HttpUriRequest lastRequest; // Hacky way of spying on the last made request
public void setResponseContent(String responseContent) {
this.responseContent = responseContent;
}
public HttpUriRequest getLastRequest() {
return lastRequest;
}
@Override
public HttpClientConnectionManager getHttpClientConnectionManager() {
return null;
}
@Override
public HttpParams getParams() {
return null;
}
@Override
public ClientConnectionManager getConnectionManager() {
return null;
}
@Override
public HttpResponse execute(HttpUriRequest httpUriRequest) throws IOException, ClientProtocolException {
return null;
}
@Override
public HttpResponse execute(HttpUriRequest httpUriRequest, HttpContext httpContext) throws IOException, ClientProtocolException {
this.lastRequest = httpUriRequest;
HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
BasicHttpEntity responseBody = new BasicHttpEntity();
InputStream in = EmptyInputStream.INSTANCE;
if(null != responseContent && !responseContent.isEmpty()) {
in = new ByteArrayInputStream(responseContent.getBytes(StandardCharsets.UTF_8));
}
responseBody.setContent(in);
httpResponse.setEntity(responseBody);
return httpResponse;
}
@Override
public HttpResponse execute(HttpHost httpHost, HttpRequest httpRequest) throws IOException, ClientProtocolException {
return null;
}
@Override
public HttpResponse execute(HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext) throws IOException, ClientProtocolException {
return null;
}
@Override
public <T> T execute(HttpUriRequest httpUriRequest, ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException {
return null;
}
@Override
public <T> T execute(HttpUriRequest httpUriRequest, ResponseHandler<? extends T> responseHandler, HttpContext httpContext) throws IOException, ClientProtocolException {
return null;
}
@Override
public <T> T execute(HttpHost httpHost, HttpRequest httpRequest, ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException {
return null;
}
@Override
public <T> T execute(HttpHost httpHost, HttpRequest httpRequest, ResponseHandler<? extends T> responseHandler, HttpContext httpContext) throws IOException, ClientProtocolException {
return (T) execute((HttpUriRequest) httpRequest, httpContext);
}
}
| 3,940 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers/downstream/source | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers/downstream/source/sql/MyStatementImpl.java | package com.amazonaws.xray.agent.runtime.handlers.downstream.source.sql;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
public class MyStatementImpl implements Statement {
public static final String QUERY = "SQL";
private final Connection connection;
public MyStatementImpl(Connection connection) {
this.connection = connection;
}
@Override
public ResultSet executeQuery(String sql) throws SQLException {
return null;
}
@Override
public int executeUpdate(String sql) throws SQLException {
return 0;
}
@Override
public void close() throws SQLException {
}
@Override
public int getMaxFieldSize() throws SQLException {
return 0;
}
@Override
public void setMaxFieldSize(int max) throws SQLException {
}
@Override
public int getMaxRows() throws SQLException {
return 0;
}
@Override
public void setMaxRows(int max) throws SQLException {
}
@Override
public void setEscapeProcessing(boolean enable) throws SQLException {
}
@Override
public int getQueryTimeout() throws SQLException {
return 0;
}
@Override
public void setQueryTimeout(int seconds) throws SQLException {
}
@Override
public void cancel() throws SQLException {
}
@Override
public SQLWarning getWarnings() throws SQLException {
return null;
}
@Override
public void clearWarnings() throws SQLException {
}
@Override
public void setCursorName(String name) throws SQLException {
}
@Override
public boolean execute(String sql) throws SQLException {
return false;
}
@Override
public ResultSet getResultSet() throws SQLException {
return null;
}
@Override
public int getUpdateCount() throws SQLException {
return 0;
}
@Override
public boolean getMoreResults() throws SQLException {
return false;
}
@Override
public void setFetchDirection(int direction) throws SQLException {
}
@Override
public int getFetchDirection() throws SQLException {
return 0;
}
@Override
public void setFetchSize(int rows) throws SQLException {
}
@Override
public int getFetchSize() throws SQLException {
return 0;
}
@Override
public int getResultSetConcurrency() throws SQLException {
return 0;
}
@Override
public int getResultSetType() throws SQLException {
return 0;
}
@Override
public void addBatch(String sql) throws SQLException {
}
@Override
public void clearBatch() throws SQLException {
}
@Override
public int[] executeBatch() throws SQLException {
return new int[0];
}
@Override
public Connection getConnection() throws SQLException {
return connection;
}
@Override
public boolean getMoreResults(int current) throws SQLException {
return false;
}
@Override
public ResultSet getGeneratedKeys() throws SQLException {
return null;
}
@Override
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
throw new SQLException();
}
@Override
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
return 0;
}
@Override
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
throw new SQLException();
}
@Override
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
return false;
}
@Override
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
return false;
}
@Override
public boolean execute(String sql, String[] columnNames) throws SQLException {
return false;
}
@Override
public int getResultSetHoldability() throws SQLException {
return 0;
}
@Override
public boolean isClosed() throws SQLException {
return false;
}
@Override
public void setPoolable(boolean poolable) throws SQLException {
}
@Override
public boolean isPoolable() throws SQLException {
return false;
}
@Override
public void closeOnCompletion() throws SQLException {
}
@Override
public boolean isCloseOnCompletion() throws SQLException {
return false;
}
@Override
public long executeLargeUpdate(String sql) throws SQLException {
return 0;
}
@Override
public long executeLargeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
return 0;
}
@Override
public long executeLargeUpdate(String sql, int[] columnIndexes) throws SQLException {
return 0;
}
@Override
public long executeLargeUpdate(String sql, String[] columnNames) throws SQLException {
return 0;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
@Override
public String toString() {
return QUERY;
}
}
| 3,941 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers/downstream/source | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers/downstream/source/sql/MyConnectionImpl.java | package com.amazonaws.xray.agent.runtime.handlers.downstream.source.sql;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
public class MyConnectionImpl implements Connection {
private PreparedStatement preparedStatement;
private CallableStatement callableStatement;
private DatabaseMetaData metaData;
public MyConnectionImpl(PreparedStatement ps, CallableStatement cs, DatabaseMetaData md) {
this.preparedStatement = ps;
this.callableStatement = cs;
this.metaData = md;
}
@Override
public Statement createStatement() throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return preparedStatement;
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
return callableStatement;
}
@Override
public String nativeSQL(String sql) throws SQLException {
return null;
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
}
@Override
public boolean getAutoCommit() throws SQLException {
return false;
}
@Override
public void commit() throws SQLException {
}
@Override
public void rollback() throws SQLException {
}
@Override
public void close() throws SQLException {
}
@Override
public boolean isClosed() throws SQLException {
return false;
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
return metaData;
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
}
@Override
public boolean isReadOnly() throws SQLException {
return false;
}
@Override
public void setCatalog(String catalog) throws SQLException {
}
@Override
public String getCatalog() throws SQLException {
return null;
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
}
@Override
public int getTransactionIsolation() throws SQLException {
return 0;
}
@Override
public SQLWarning getWarnings() throws SQLException {
return null;
}
@Override
public void clearWarnings() throws SQLException {
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
return null;
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
}
@Override
public void setHoldability(int holdability) throws SQLException {
}
@Override
public int getHoldability() throws SQLException {
return 0;
}
@Override
public Savepoint setSavepoint() throws SQLException {
return null;
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
return null;
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
return null;
}
@Override
public Clob createClob() throws SQLException {
return null;
}
@Override
public Blob createBlob() throws SQLException {
return null;
}
@Override
public NClob createNClob() throws SQLException {
return null;
}
@Override
public SQLXML createSQLXML() throws SQLException {
return null;
}
@Override
public boolean isValid(int timeout) throws SQLException {
return false;
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
}
@Override
public String getClientInfo(String name) throws SQLException {
return null;
}
@Override
public Properties getClientInfo() throws SQLException {
return null;
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
return null;
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
return null;
}
@Override
public void setSchema(String schema) throws SQLException {
}
@Override
public String getSchema() throws SQLException {
return null;
}
@Override
public void abort(Executor executor) throws SQLException {
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
}
@Override
public int getNetworkTimeout() throws SQLException {
return 0;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
}
| 3,942 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers/upstream/ServletHandlerIntegTest.java | package com.amazonaws.xray.agent.runtime.handlers.upstream;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.agent.runtime.handlers.upstream.source.SimpleHttpServlet;
import com.amazonaws.xray.emitters.UDPEmitter;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.strategy.sampling.AllSamplingStrategy;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class ServletHandlerIntegTest {
private final static String TRACE_HEADER_KEY = TraceHeader.HEADER_KEY;
private final static String PREDEFINED_TRACE_HEADER_SAMPLED = "Root=1-5dc20232-c5f804c16e231025e5cf0d74;Parent=1d62b25534e7d360;Sampled=1";
private final static String PREDEFINED_TRACE_HEADER_NOT_SAMPLED = "Root=1-5dc203d8-8d0b0d30aab25f0cfcfaf63a;Parent=38e0df8c9363d068;Sampled=0";
private final static String SERVICE_NAME = "IntegTest"; // This is hardcoded in the Pom.xml file
private HttpServlet theServlet;
private MockHttpServletRequest request;
private HttpServletResponse response;
private AWSXRayRecorder recorder;
private UDPEmitter mockEmitter;
@Before
public void setup() throws Exception {
theServlet = new SimpleHttpServlet();
request = new MockHttpServletRequest();
request.setMethod("GET");
request.setHeader(TRACE_HEADER_KEY, null);
response = mock(HttpServletResponse.class);
when(response.getStatus()).thenReturn(200);
mockEmitter = mock(UDPEmitter.class);
recorder = AWSXRay.getGlobalRecorder();
recorder.setSamplingStrategy(new AllSamplingStrategy());
recorder.setEmitter(mockEmitter); // Even though we're sampling them all, none are sent. This is to test.
}
@After
public void cleanup() {
AWSXRay.clearTraceEntity();
}
@Test
public void testReceiveGetRequest() throws Exception {
theServlet.service(request, response);
Segment currentSegment = interceptSegment();
// Check Subsegment properties
verifyHttpSegment(currentSegment);
}
@Test
public void testReceivePostRequest() throws Exception {
request.setMethod("POST");
theServlet.service(request, response);
Segment currentSegment = interceptSegment();
// Check Subsegment properties
verifyHttpSegment(currentSegment);
}
@Test
public void testReceive200() throws Exception {
when(response.getStatus()).thenReturn(200);
theServlet.service(request, response);
Segment currentSegment = interceptSegment();
// Check Subsegment properties
verifyHttpSegment(currentSegment);
}
@Test
public void testReceiveThrottle() throws Exception {
when(response.getStatus()).thenReturn(429);
theServlet.service(request, response);
Segment currentSegment = interceptSegment();
// Check Subsegment properties
verifyHttpSegment(currentSegment);
assertTrue(currentSegment.isError());
assertTrue(currentSegment.isThrottle());
assertFalse(currentSegment.isFault());
}
@Test
public void testReceiveFault() throws Exception {
when(response.getStatus()).thenReturn(500);
theServlet.service(request, response);
Segment currentSegment = interceptSegment();
// Check Subsegment properties
verifyHttpSegment(currentSegment);
assertFalse(currentSegment.isError());
assertFalse(currentSegment.isThrottle());
assertTrue(currentSegment.isFault());
}
@Test
public void testReceiveError() throws Exception {
when(response.getStatus()).thenReturn(400);
theServlet.service(request, response);
Segment currentSegment = interceptSegment();
// Check Subsegment properties
verifyHttpSegment(currentSegment);
assertTrue(currentSegment.isError());
assertFalse(currentSegment.isThrottle());
assertFalse(currentSegment.isFault());
}
@Test
public void testReceiveTraceHeaderSampled() throws Exception {
// Add trace header to X-Ray through the request object.
request.setHeader(TRACE_HEADER_KEY, PREDEFINED_TRACE_HEADER_SAMPLED);
theServlet.service(request, response);
Segment currentSegment = interceptSegment();
verifyHttpSegment(currentSegment);
TraceHeader origTH = TraceHeader.fromString(PREDEFINED_TRACE_HEADER_SAMPLED);
TraceHeader.SampleDecision segmentSampleDecision = TraceHeader.SampleDecision.SAMPLED;
assertEquals(origTH.toString(),
new TraceHeader(currentSegment.getTraceId(), currentSegment.getParentId(), segmentSampleDecision).toString());
}
@Test
public void testReceiveTraceHeaderUnsampled() throws Exception {
// Add trace header to X-Ray through the request object.
request.setHeader(TRACE_HEADER_KEY, PREDEFINED_TRACE_HEADER_NOT_SAMPLED);
theServlet.service(request, response);
verify(mockEmitter, times(0)).sendSegment(any());
}
private void verifyHttpSegment(Segment segment) {
assertEquals(SERVICE_NAME, segment.getName());
Map<String, String> httpRequestMap = (Map<String, String>) segment.getHttp().get("request");
assertEquals(request.getMethod(), httpRequestMap.get("method"));
assertEquals(request.getRemoteAddr(), httpRequestMap.get("client_ip"));
assertEquals(request.getRequestURL().toString(), httpRequestMap.get("url"));
Map<String, String> httpResponseMap = (Map<String, String>) segment.getHttp().get("response");
assertEquals(response.getStatus(), httpResponseMap.get("status"));
}
// Return the segment generated by the call to the servlet.
// Returns null if none had been intercepted.
private Segment interceptSegment() {
ArgumentCaptor<Segment> segmentArgumentCaptor = ArgumentCaptor.forClass(Segment.class);
verify(mockEmitter).sendSegment(segmentArgumentCaptor.capture());
List<Segment> capturedSegments = segmentArgumentCaptor.getAllValues();
assertEquals(1, capturedSegments.size()); // This should only be called after a single call to sendSegment has been made.
try {
return capturedSegments.get(0);
} catch (IndexOutOfBoundsException e) {
return null;
}
}
}
| 3,943 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers/upstream/MockHttpServletRequest.java | package com.amazonaws.xray.agent.runtime.handlers.upstream;
import javax.servlet.AsyncContext;
import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpUpgradeHandler;
import javax.servlet.http.Part;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* This is a "mocked" version of the HttpServletRequest interface that is actually implemented rather
* than simply mocked with Mockito because the reflection done by Mockito interferes with that done by
* Disco, causing incorrect stubbing.
*
* TODO: When Disco removes its data accessor pattern in a future version, delete this & use a mock instead
*/
public class MockHttpServletRequest implements HttpServletRequest {
private static Map<String, String> reqHeaderMap;
private String method;
static {
reqHeaderMap = new HashMap<>();
reqHeaderMap.put("host", "amazon.com");
reqHeaderMap.put("referer", "http://amazon.com/explore/something");
reqHeaderMap.put("user-agent", "Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/12.0");
}
@Override
public String getAuthType() {
return null;
}
@Override
public Cookie[] getCookies() {
return new Cookie[0];
}
@Override
public long getDateHeader(String s) {
return 0;
}
@Override
public String getHeader(String s) {
return reqHeaderMap.get(s);
}
public void setHeader(String key, String val) {
reqHeaderMap.put(key, val);
}
@Override
public Enumeration<String> getHeaders(String s) {
return null;
}
@Override
public Enumeration<String> getHeaderNames() {
return Collections.enumeration(reqHeaderMap.keySet());
}
@Override
public int getIntHeader(String s) {
return 0;
}
@Override
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
@Override
public String getPathInfo() {
return null;
}
@Override
public String getPathTranslated() {
return null;
}
@Override
public String getContextPath() {
return null;
}
@Override
public String getQueryString() {
return null;
}
@Override
public String getRemoteUser() {
return null;
}
@Override
public boolean isUserInRole(String s) {
return false;
}
@Override
public Principal getUserPrincipal() {
return null;
}
@Override
public String getRequestedSessionId() {
return null;
}
@Override
public String getRequestURI() {
return null;
}
@Override
public StringBuffer getRequestURL() {
return new StringBuffer("http://request.amazon.com");
}
@Override
public String getServletPath() {
return null;
}
@Override
public HttpSession getSession(boolean b) {
return null;
}
@Override
public HttpSession getSession() {
return null;
}
@Override
public String changeSessionId() {
return null;
}
@Override
public boolean isRequestedSessionIdValid() {
return false;
}
@Override
public boolean isRequestedSessionIdFromCookie() {
return false;
}
@Override
public boolean isRequestedSessionIdFromURL() {
return false;
}
@Override
public boolean isRequestedSessionIdFromUrl() {
return false;
}
@Override
public boolean authenticate(HttpServletResponse httpServletResponse) throws IOException, ServletException {
return false;
}
@Override
public void login(String s, String s1) throws ServletException {
}
@Override
public void logout() throws ServletException {
}
@Override
public Collection<Part> getParts() throws IOException, ServletException {
return null;
}
@Override
public Part getPart(String s) throws IOException, ServletException {
return null;
}
@Override
public <T extends HttpUpgradeHandler> T upgrade(Class<T> aClass) throws IOException, ServletException {
return null;
}
@Override
public Object getAttribute(String s) {
return null;
}
@Override
public Enumeration<String> getAttributeNames() {
return null;
}
@Override
public String getCharacterEncoding() {
return null;
}
@Override
public void setCharacterEncoding(String s) throws UnsupportedEncodingException {
}
@Override
public int getContentLength() {
return 0;
}
@Override
public long getContentLengthLong() {
return 0;
}
@Override
public String getContentType() {
return null;
}
@Override
public ServletInputStream getInputStream() throws IOException {
return null;
}
@Override
public String getParameter(String s) {
return null;
}
@Override
public Enumeration<String> getParameterNames() {
return null;
}
@Override
public String[] getParameterValues(String s) {
return new String[0];
}
@Override
public Map<String, String[]> getParameterMap() {
return null;
}
@Override
public String getProtocol() {
return "http";
}
@Override
public String getScheme() {
return null;
}
@Override
public String getServerName() {
return null;
}
@Override
public int getServerPort() {
return 0;
}
@Override
public BufferedReader getReader() throws IOException {
return null;
}
@Override
public String getRemoteAddr() {
return "1.1.1.1";
}
@Override
public String getRemoteHost() {
return null;
}
@Override
public void setAttribute(String s, Object o) {
}
@Override
public void removeAttribute(String s) {
}
@Override
public Locale getLocale() {
return null;
}
@Override
public Enumeration<Locale> getLocales() {
return null;
}
@Override
public boolean isSecure() {
return false;
}
@Override
public RequestDispatcher getRequestDispatcher(String s) {
return null;
}
@Override
public String getRealPath(String s) {
return null;
}
@Override
public int getRemotePort() {
return 0;
}
@Override
public String getLocalName() {
return null;
}
@Override
public String getLocalAddr() {
return "0.0.0.0";
}
@Override
public int getLocalPort() {
return 0;
}
@Override
public ServletContext getServletContext() {
return null;
}
@Override
public AsyncContext startAsync() throws IllegalStateException {
return null;
}
@Override
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException {
return null;
}
@Override
public boolean isAsyncStarted() {
return false;
}
@Override
public boolean isAsyncSupported() {
return false;
}
@Override
public AsyncContext getAsyncContext() {
return null;
}
@Override
public DispatcherType getDispatcherType() {
return null;
}
}
| 3,944 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers/upstream | Create_ds/aws-xray-java-agent/aws-xray-agent-plugin/src/test/java/com/amazonaws/xray/agent/runtime/handlers/upstream/source/SimpleHttpServlet.java | package com.amazonaws.xray.agent.runtime.handlers.upstream.source;
import javax.servlet.http.HttpServlet;
public class SimpleHttpServlet extends HttpServlet {
}
| 3,945 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime/AgentRuntimeLoaderTest.java | package com.amazonaws.xray.agent.runtime;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import com.amazonaws.xray.agent.runtime.config.XRaySDKConfiguration;
import com.amazonaws.xray.agent.runtime.listeners.ListenerFactory;
import com.amazonaws.xray.agent.runtime.listeners.XRayListener;
import com.amazonaws.xray.agent.runtime.models.XRayTransactionState;
import org.apache.commons.io.FilenameUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import software.amazon.disco.agent.event.EventBus;
import java.io.File;
import java.net.URL;
import static org.mockito.Mockito.when;
public class AgentRuntimeLoaderTest {
private final String serviceName = "TestService";
private static final String CONFIG_FILE_SYS_PROPERTY = "com.amazonaws.xray.configFile";
private static final String CONFIG_FILE_DEFAULT_NAME = "xray-agent.json";
@Mock
private XRayListener listenerMock;
@Mock
private ListenerFactory factoryMock;
private XRaySDKConfiguration config;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
when(factoryMock.generateListener()).thenReturn(listenerMock);
AgentRuntimeLoader.setListenerFactory(factoryMock);
System.clearProperty(CONFIG_FILE_SYS_PROPERTY);
config = XRaySDKConfiguration.getInstance();
config.init(null); // resets any static config properties
}
@After
public void cleanup() {
EventBus.removeAllListeners();
AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder.defaultRecorder()); // Refresh this.
}
@Test
public void testCommandLineNameSet() {
AgentRuntimeLoader.init(serviceName);
Assert.assertEquals(XRayTransactionState.getServiceName(), serviceName);
}
@Test
public void testListenerAddedToEventBus() {
AgentRuntimeLoader.init(null);
Assert.assertTrue(EventBus.isListenerPresent(listenerMock));
}
@Test
public void testGetDefaultConfigFile() {
URL configFile = AgentRuntimeLoader.getConfigFile();
Assert.assertEquals(CONFIG_FILE_DEFAULT_NAME, FilenameUtils.getName(configFile.getPath()));
}
@Test
public void testGetCustomConfigFileFromFileSystem() {
String fileName = "emptyAgentConfig.json";
System.setProperty(CONFIG_FILE_SYS_PROPERTY,
AgentRuntimeLoaderTest.class.getResource("/com/amazonaws/xray/agent/" + fileName).getPath());
URL configFile = AgentRuntimeLoader.getConfigFile();
Assert.assertEquals(fileName, FilenameUtils.getName(configFile.getPath()));
}
@Test
public void testGetCustomConfigFileFromClassPath() {
String fileName = "emptyAgentConfig.json";
System.setProperty(CONFIG_FILE_SYS_PROPERTY, "/com/amazonaws/xray/agent/" + fileName);
URL configFile = AgentRuntimeLoader.getConfigFile();
// Make sure it's not using the file system
Assert.assertFalse(new File("/com/amazonaws/xray/agent/" + fileName).exists());
Assert.assertEquals(fileName, FilenameUtils.getName(configFile.getPath()));
}
@Test
public void testNonExistentCustomConfigFile() {
System.setProperty(CONFIG_FILE_SYS_PROPERTY, "/some/totally/fake/file");
URL configFile = AgentRuntimeLoader.getConfigFile();
Assert.assertNull(configFile);
}
}
| 3,946 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime/config/XRaySDKConfigurationTest.java | package com.amazonaws.xray.agent.runtime.config;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import com.amazonaws.xray.agent.runtime.models.XRayTransactionContext;
import com.amazonaws.xray.agent.runtime.models.XRayTransactionState;
import com.amazonaws.xray.contexts.ThreadLocalSegmentContext;
import com.amazonaws.xray.emitters.UDPEmitter;
import com.amazonaws.xray.log4j.Log4JSegmentListener;
import com.amazonaws.xray.strategy.DefaultStreamingStrategy;
import com.amazonaws.xray.strategy.DefaultThrowableSerializationStrategy;
import com.amazonaws.xray.strategy.IgnoreErrorContextMissingStrategy;
import com.amazonaws.xray.strategy.LogErrorContextMissingStrategy;
import com.amazonaws.xray.strategy.SegmentNamingStrategy;
import com.amazonaws.xray.strategy.sampling.AllSamplingStrategy;
import com.amazonaws.xray.strategy.sampling.CentralizedSamplingStrategy;
import com.amazonaws.xray.strategy.sampling.LocalizedSamplingStrategy;
import com.amazonaws.xray.strategy.sampling.NoSamplingStrategy;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.mockito.ArgumentCaptor;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
public class XRaySDKConfigurationTest {
private static final String JVM_NAME = "jvm_name";
private static final String ENV_NAME = "env_name";
private static final String SYS_NAME = "sys_name";
private static final String CONFIG_NAME = "config_name";
XRaySDKConfiguration config;
Map<String, String> configMap;
@Rule
public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
@Before
public void setup() {
AWSXRay.setGlobalRecorder(new AWSXRayRecorder());
configMap = new HashMap<>();
configMap.put("pluginsEnabled", "false"); // Checking for EC2 endpoint on each test takes a long time
config = new XRaySDKConfiguration();
}
@After
public void cleanup() {
XRayTransactionState.setServiceName(null);
System.clearProperty(SegmentNamingStrategy.NAME_OVERRIDE_SYSTEM_PROPERTY_KEY);
System.clearProperty(XRaySDKConfiguration.ENABLED_SYSTEM_PROPERTY_KEY);
environmentVariables.set(SegmentNamingStrategy.NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY, null);
environmentVariables.set(XRaySDKConfiguration.ENABLED_ENVIRONMENT_VARIABLE_KEY, null);
}
@Test(expected = InvalidAgentConfigException.class)
public void testInitWithNonexistentFile() throws MalformedURLException {
config.init(new File("/some/nonexistent/file").toURI().toURL());
}
@Test(expected = InvalidAgentConfigException.class)
public void testInitWithMalformedFile() {
config.init(XRaySDKConfigurationTest.class.getResource("/com/amazonaws/xray/agent/malformedAgentConfig.json"));
}
@Test
public void testInitWithValidFile() {
configMap.put("serviceName", "myServiceName");
configMap.put("contextMissingStrategy", "myTestContext");
configMap.put("daemonAddress", "myTestAddress");
configMap.put("samplingStrategy", "myTestSampling");
configMap.put("samplingRulesManifest", "myTestManifest");
configMap.put("traceIdInjection", "Log4J");
configMap.put("traceIdInjectionPrefix", "prefix");
configMap.put("maxStackTraceLength", "20");
configMap.put("streamingThreshold", "10");
configMap.put("awsSdkVersion", "1");
configMap.put("awsServiceHandlerManifest", "myTestHandler");
configMap.put("pluginsEnabled", "false");
configMap.put("tracingEnabled", "false");
configMap.put("collectSqlQueries", "true");
configMap.put("contextPropagation", "false");
configMap.put("traceIncomingRequests", "false");
AgentConfiguration agentConfig = new AgentConfiguration(configMap);
config.init(XRaySDKConfigurationTest.class.getResource("/com/amazonaws/xray/agent/validAgentConfig.json"));
Assert.assertEquals(agentConfig, config.getAgentConfiguration());
}
@Test
public void testEnvTracingDisabled() {
AWSXRayRecorderBuilder builderMock = mock(AWSXRayRecorderBuilder.class);
environmentVariables.set(XRaySDKConfiguration.ENABLED_ENVIRONMENT_VARIABLE_KEY, "false");
System.setProperty(XRaySDKConfiguration.ENABLED_SYSTEM_PROPERTY_KEY, "true");
config.init(builderMock);
Assert.assertNull(XRayTransactionState.getServiceName());
verify(builderMock, never()).build();
}
@Test
public void testSysTracingDisabled() {
AWSXRayRecorderBuilder builderMock = mock(AWSXRayRecorderBuilder.class);
System.setProperty(XRaySDKConfiguration.ENABLED_SYSTEM_PROPERTY_KEY, "false");
config.init(builderMock);
Assert.assertNull(XRayTransactionState.getServiceName());
verify(builderMock, never()).build();
}
@Test
public void testFileTracingDisabled() {
AWSXRayRecorderBuilder builderMock = mock(AWSXRayRecorderBuilder.class);
configMap.put("tracingEnabled", "false");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(builderMock);
Assert.assertNull(XRayTransactionState.getServiceName());
verify(builderMock, never()).build();
}
@Test
public void testJVMServiceName() {
XRayTransactionState.setServiceName(JVM_NAME);
environmentVariables.set(SegmentNamingStrategy.NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY, ENV_NAME);
System.setProperty(SegmentNamingStrategy.NAME_OVERRIDE_SYSTEM_PROPERTY_KEY, SYS_NAME);
configMap.put("serviceName", CONFIG_NAME);
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
Assert.assertEquals(JVM_NAME, XRayTransactionState.getServiceName());
}
@Test
public void testEnvServiceName() {
environmentVariables.set(SegmentNamingStrategy.NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY, ENV_NAME);
System.setProperty(SegmentNamingStrategy.NAME_OVERRIDE_SYSTEM_PROPERTY_KEY, SYS_NAME);
configMap.put("serviceName", CONFIG_NAME);
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
Assert.assertEquals(ENV_NAME, XRayTransactionState.getServiceName());
}
@Test
public void testSysServiceName() {
System.setProperty(SegmentNamingStrategy.NAME_OVERRIDE_SYSTEM_PROPERTY_KEY, SYS_NAME);
configMap.put("serviceName", CONFIG_NAME);
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
Assert.assertEquals(SYS_NAME, XRayTransactionState.getServiceName());
}
@Test
public void testConfigServiceName() {
configMap.put("serviceName", CONFIG_NAME);
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
Assert.assertEquals(CONFIG_NAME, XRayTransactionState.getServiceName());
}
@Test
public void testDefaultServiceName() {
config.init();
Assert.assertEquals(AgentConfiguration.DEFAULT_SERVICE_NAME, XRayTransactionState.getServiceName());
}
@Test
public void testPluginsEnabledByDefault() {
AWSXRayRecorderBuilder builderMock = mock(AWSXRayRecorderBuilder.class);
config.init(builderMock);
verify(builderMock).withDefaultPlugins();
}
@Test
public void testPluginsDisabled() {
AWSXRayRecorderBuilder builderMock = mock(AWSXRayRecorderBuilder.class);
configMap.put("pluginsEnabled", "false");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(builderMock);
verify(builderMock, never()).withDefaultPlugins();
}
@Test
public void testDefaultContextMissingStrategy() {
config.init();
Assert.assertTrue(AWSXRay.getGlobalRecorder().getContextMissingStrategy() instanceof LogErrorContextMissingStrategy);
}
@Test(expected = InvalidAgentConfigException.class)
public void testInvalidContextMissingStrategy() {
configMap.put("contextMissingStrategy", "FAKE_STRATEGY");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
}
@Test
public void testIgnoreErrorContextMissingStrategy() {
configMap.put("contextMissingStrategy", "IGNORE_ERROR");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
Assert.assertTrue(AWSXRay.getGlobalRecorder().getContextMissingStrategy() instanceof IgnoreErrorContextMissingStrategy);
}
@Test
public void testContextMissingStrategyIsCaseInsensitive() {
configMap.put("contextMissingStrategy", "igNoRe_ErrOR");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
Assert.assertTrue(AWSXRay.getGlobalRecorder().getContextMissingStrategy() instanceof IgnoreErrorContextMissingStrategy);
}
@Test(expected = InvalidAgentConfigException.class)
public void testInvalidDaemonAddress() {
AWSXRayRecorderBuilder builderMock = mock(AWSXRayRecorderBuilder.class);
configMap.put("daemonAddress", "invalidAddress");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(builderMock);
}
@Test
public void testValidDaemonAddress() {
AWSXRayRecorderBuilder builderMock = mock(AWSXRayRecorderBuilder.class);
configMap.put("daemonAddress", "123.4.5.6:1234");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(builderMock);
// TODO: Make these tests simpler & better by comparing the actual value we set to the recorder's daemon
// address once it's exposed. See https://github.com/aws/aws-xray-sdk-java/issues/148
ArgumentCaptor<UDPEmitter> captor = ArgumentCaptor.forClass(UDPEmitter.class);
verify(builderMock).withEmitter(captor.capture());
Assert.assertNotNull(captor.getValue());
}
@Test
public void testInvalidSamplingRuleManifest() {
AWSXRayRecorderBuilder builderMock = mock(AWSXRayRecorderBuilder.class);
configMap.put("samplingRulesManifest", "notAFile");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(builderMock);
ArgumentCaptor<CentralizedSamplingStrategy> captor = ArgumentCaptor.forClass(CentralizedSamplingStrategy.class);
verify(builderMock).withSamplingStrategy(captor.capture());
Assert.assertNotNull(captor.getValue());
}
@Test
public void testValidSamplingRuleManifest() {
AWSXRayRecorderBuilder builderMock = mock(AWSXRayRecorderBuilder.class);
configMap.put("samplingRulesManifest", "/path/to/file");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(builderMock);
// TODO: Verify the correct URL is used and add more Manifest tests once this PR is released:
// https://github.com/aws/aws-xray-sdk-java/pull/149
ArgumentCaptor<CentralizedSamplingStrategy> captor = ArgumentCaptor.forClass(CentralizedSamplingStrategy.class);
verify(builderMock).withSamplingStrategy(captor.capture());
Assert.assertNotNull(captor.getValue());
}
@Test
public void testDefaultSamplingStrategy() {
config.init();
Assert.assertTrue(AWSXRay.getGlobalRecorder().getSamplingStrategy() instanceof CentralizedSamplingStrategy);
}
@Test(expected = InvalidAgentConfigException.class)
public void testInvalidSamplingStrategy() {
configMap.put("samplingStrategy", "FakeStrategy");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
}
@Test
public void testLocalSamplingStrategy() {
configMap.put("samplingStrategy", "LOCAL");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
Assert.assertTrue(AWSXRay.getGlobalRecorder().getSamplingStrategy() instanceof LocalizedSamplingStrategy);
}
@Test
public void testNoSamplingStrategy() {
configMap.put("samplingStrategy", "NONE");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
Assert.assertTrue(AWSXRay.getGlobalRecorder().getSamplingStrategy() instanceof NoSamplingStrategy);
}
@Test
public void testAllSamplingStrategy() {
configMap.put("samplingStrategy", "ALL");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
Assert.assertTrue(AWSXRay.getGlobalRecorder().getSamplingStrategy() instanceof AllSamplingStrategy);
}
@Test
public void testSamplingStrategyIsCaseInsensitive() {
configMap.put("samplingStrategy", "LoCaL");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
Assert.assertTrue(AWSXRay.getGlobalRecorder().getSamplingStrategy() instanceof LocalizedSamplingStrategy);
}
@Test
public void testTraceIdInjection() {
config.init(AWSXRayRecorderBuilder.standard());
// A little fragile, depends on the order they're added in XRaySDKConfiguration
Log4JSegmentListener listener = (Log4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0);
Assert.assertEquals(2, AWSXRay.getGlobalRecorder().getSegmentListeners().size());
Assert.assertEquals("", listener.getPrefix());
}
@Test
public void testDisableTraceIdInjection() {
configMap.put("traceIdInjection", "false");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
// A little fragile, depends on the order they're added in XRaySDKConfiguration
Assert.assertEquals(0, AWSXRay.getGlobalRecorder().getSegmentListeners().size());
}
@Test
public void testTraceIdInjectionPrefix() {
configMap.put("traceIdInjectionPrefix", "my-prefix");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
Log4JSegmentListener listener = (Log4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0);
Assert.assertEquals(2, AWSXRay.getGlobalRecorder().getSegmentListeners().size());
Assert.assertEquals("my-prefix", listener.getPrefix());
}
@Test
public void testMaxStackTraceLength() {
configMap.put("maxStackTraceLength", "42");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
DefaultThrowableSerializationStrategy strategy =
(DefaultThrowableSerializationStrategy) AWSXRay.getGlobalRecorder().getThrowableSerializationStrategy();
Assert.assertEquals(42, strategy.getMaxStackTraceLength());
}
@Test
public void testStreamingThreshold() {
AWSXRayRecorderBuilder builderMock = mock(AWSXRayRecorderBuilder.class);
configMap.put("streamingThreshold", "42");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(builderMock);
// TODO: Verify the correct threshold is used once this PR is released:
// https://github.com/aws/aws-xray-sdk-java/pull/149
ArgumentCaptor<DefaultStreamingStrategy> captor = ArgumentCaptor.forClass(DefaultStreamingStrategy.class);
verify(builderMock).withStreamingStrategy(captor.capture());
Assert.assertNotNull(captor.getValue());
}
@Test(expected = InvalidAgentConfigException.class)
public void testInvalidVersionNumber() {
configMap.put("awsSdkVersion", "11");
configMap.put("awsServiceHandlerManifest", "/path/to/manifest");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
}
@Test
public void testValidServiceManifest() throws MalformedURLException {
configMap.put("awsServiceHandlerManifest", "/path/to/manifest");
config.setAgentConfiguration(new AgentConfiguration(configMap));
URL location = new File("/path/to/manifest").toURI().toURL();
config.init(AWSXRayRecorderBuilder.standard());
Assert.assertEquals(location.getPath(), config.getAwsServiceHandlerManifest().getPath());
}
@Test
public void testCollectSqlQueries() {
configMap.put("collectSqlQueries", "true");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
Assert.assertTrue(config.shouldCollectSqlQueries());
}
@Test
public void testDefaultContextPropagation() {
config.init();
Assert.assertTrue(AWSXRay.getGlobalRecorder().getSegmentContextResolverChain().resolve() instanceof XRayTransactionContext);
}
@Test
public void testContextPropagation() {
configMap.put("contextPropagation", "false");
config.setAgentConfiguration(new AgentConfiguration(configMap));
config.init(AWSXRayRecorderBuilder.standard());
Assert.assertTrue(AWSXRay.getGlobalRecorder().getSegmentContextResolverChain().resolve() instanceof ThreadLocalSegmentContext);
}
@Test
public void testLazyLoadTraceIdInjection() {
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.defaultRecorder();
config.setAgentConfiguration(new AgentConfiguration());
config.lazyLoadTraceIdInjection(recorder);
Assert.assertEquals(2, recorder.getSegmentListeners().size());
}
}
| 3,947 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime/config/AgentConfigurationTest.java | package com.amazonaws.xray.agent.runtime.config;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
public class AgentConfigurationTest {
@Test
public void testEmptyMapUsesDefaults() {
AgentConfiguration defaultConfig = new AgentConfiguration();
AgentConfiguration mapConfig = new AgentConfiguration(new HashMap<>());
Assert.assertEquals(defaultConfig, mapConfig);
}
}
| 3,948 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime/dispatcher/EventDispatcherTest.java | package com.amazonaws.xray.agent.runtime.dispatcher;
import com.amazonaws.xray.agent.runtime.handlers.XRayHandlerInterface;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.modules.junit4.PowerMockRunner;
import software.amazon.disco.agent.event.ServiceActivityRequestEvent;
import software.amazon.disco.agent.event.ServiceActivityResponseEvent;
import software.amazon.disco.agent.event.ServiceRequestEvent;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@RunWith(PowerMockRunner.class)
public class EventDispatcherTest {
private final String ORIGIN = "testOrigin";
private final String SERVICE = "testService";
private final String OPERATION = "testOperation";
@Mock
private XRayHandlerInterface mockHandler;
private EventDispatcher eventDispatcher;
@Before
public void setup() {
eventDispatcher = new EventDispatcher();
eventDispatcher.addHandler(ORIGIN, mockHandler);
}
@Test
public void testAddHandler() {
String testOrigin = "SOMEORIGIN";
ServiceRequestEvent serviceRequestEvent = new ServiceActivityRequestEvent(testOrigin, SERVICE, OPERATION);
eventDispatcher.dispatchRequestEvent(serviceRequestEvent);
verify(mockHandler, times(0)).handleRequest(serviceRequestEvent);
eventDispatcher.addHandler(testOrigin, mockHandler);
eventDispatcher.dispatchRequestEvent(serviceRequestEvent);
verify(mockHandler, times(1)).handleRequest(serviceRequestEvent);
}
@Test
public void testDispatchRequest() {
ServiceActivityRequestEvent serviceRequestEvent = new ServiceActivityRequestEvent(ORIGIN, SERVICE, OPERATION);
eventDispatcher.dispatchRequestEvent(serviceRequestEvent);
verify(mockHandler, times(1)).handleRequest(serviceRequestEvent);
}
@Test
public void testDispatchResponse() {
ServiceActivityRequestEvent serviceRequestEvent = mock(ServiceActivityRequestEvent.class);
ServiceActivityResponseEvent serviceResponseEvent = new ServiceActivityResponseEvent(ORIGIN, SERVICE, OPERATION, serviceRequestEvent);
eventDispatcher.dispatchResponseEvent(serviceResponseEvent);
verify(mockHandler, times(1)).handleResponse(serviceResponseEvent);
}
@Test
public void testDispatchNoHandler() {
ServiceActivityRequestEvent serviceRequestEvent = new ServiceActivityRequestEvent("NotUsedOrigin", null, null);
eventDispatcher.dispatchRequestEvent(serviceRequestEvent);
verify(mockHandler, times(0)).handleRequest(serviceRequestEvent);
}
}
| 3,949 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime/listeners/XRayListenerTest.java | package com.amazonaws.xray.agent.runtime.listeners;
import com.amazonaws.xray.agent.runtime.dispatcher.EventDispatcher;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.modules.junit4.PowerMockRunner;
import software.amazon.disco.agent.event.HttpServletNetworkRequestEvent;
import software.amazon.disco.agent.event.HttpServletNetworkResponseEvent;
import software.amazon.disco.agent.event.ServiceActivityRequestEvent;
import software.amazon.disco.agent.event.ServiceActivityResponseEvent;
import software.amazon.disco.agent.event.ServiceDownstreamRequestEvent;
import software.amazon.disco.agent.event.ServiceDownstreamResponseEvent;
import software.amazon.disco.agent.event.TransactionBeginEvent;
import software.amazon.disco.agent.event.TransactionEvent;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@RunWith(PowerMockRunner.class)
public class XRayListenerTest {
private final String ORIGIN = "TestOrigin";
private final String SERVICE = "TestService";
private final String OPERATION = "TestOperation";
@Mock
private EventDispatcher upstreamDispatcher;
@Mock
private EventDispatcher downstreamDispatcher;
private XRayListener xRayListener;
@Before
public void setup() {
xRayListener = new XRayListener(upstreamDispatcher, downstreamDispatcher);
}
@Test
public void testGetPriority() {
Assert.assertEquals(0, xRayListener.getPriority());
}
@Test
public void testListenUpstream() {
ServiceActivityRequestEvent upstreamRequestEvent = new ServiceActivityRequestEvent(ORIGIN, SERVICE, OPERATION);
ServiceActivityResponseEvent upstreamResponseEvent = new ServiceActivityResponseEvent(ORIGIN, SERVICE, OPERATION, upstreamRequestEvent);
xRayListener.listen(upstreamRequestEvent);
verify(upstreamDispatcher, times(1)).dispatchRequestEvent(upstreamRequestEvent);
verify(upstreamDispatcher, times(0)).dispatchResponseEvent(upstreamResponseEvent);
xRayListener.listen(upstreamResponseEvent);
verify(upstreamDispatcher, times(1)).dispatchRequestEvent(upstreamRequestEvent);
verify(upstreamDispatcher, times(1)).dispatchResponseEvent(upstreamResponseEvent);
verify(downstreamDispatcher, times(0)).dispatchResponseEvent(upstreamRequestEvent);
verify(downstreamDispatcher, times(0)).dispatchResponseEvent(upstreamResponseEvent);
}
@Test
public void testListenDownstream() {
ServiceDownstreamRequestEvent downstreamRequestEvent = new ServiceDownstreamRequestEvent(ORIGIN, SERVICE, OPERATION);
ServiceDownstreamResponseEvent downstreamResponseEvent = new ServiceDownstreamResponseEvent(ORIGIN, SERVICE, OPERATION, downstreamRequestEvent);
xRayListener.listen(downstreamRequestEvent);
verify(downstreamDispatcher, times(1)).dispatchRequestEvent(downstreamRequestEvent);
verify(downstreamDispatcher, times(0)).dispatchResponseEvent(downstreamResponseEvent);
xRayListener.listen(downstreamResponseEvent);
verify(downstreamDispatcher, times(1)).dispatchRequestEvent(downstreamRequestEvent);
verify(downstreamDispatcher, times(1)).dispatchResponseEvent(downstreamResponseEvent);
verify(upstreamDispatcher, times(0)).dispatchResponseEvent(downstreamRequestEvent);
verify(upstreamDispatcher, times(0)).dispatchResponseEvent(downstreamResponseEvent);
}
@Test
public void testValidEvents() {
ServiceActivityRequestEvent serviceRequestEvent = new ServiceActivityRequestEvent(ORIGIN, SERVICE, OPERATION);
xRayListener.listen(serviceRequestEvent);
verify(upstreamDispatcher, times(1)).dispatchRequestEvent(serviceRequestEvent);
ServiceActivityResponseEvent serviceResponseEvent = new ServiceActivityResponseEvent(ORIGIN, SERVICE, OPERATION, serviceRequestEvent);
xRayListener.listen(serviceResponseEvent);
verify(upstreamDispatcher, times(1)).dispatchResponseEvent(serviceResponseEvent);
HttpServletNetworkRequestEvent httpRequestEvent = new HttpServletNetworkRequestEvent(ORIGIN, 0, 0 ,"", "");
xRayListener.listen(httpRequestEvent);
verify(upstreamDispatcher, times(1)).dispatchRequestEvent(httpRequestEvent);
HttpServletNetworkResponseEvent httpResponseEvent = new HttpServletNetworkResponseEvent(ORIGIN, httpRequestEvent);
xRayListener.listen(httpResponseEvent);
verify(upstreamDispatcher, times(1)).dispatchResponseEvent(httpResponseEvent);
ServiceDownstreamRequestEvent downstreamRequestEvent = new ServiceDownstreamRequestEvent(ORIGIN, SERVICE, OPERATION);
xRayListener.listen(downstreamRequestEvent);
verify(downstreamDispatcher, times(1)).dispatchRequestEvent(downstreamRequestEvent);
ServiceDownstreamResponseEvent downstreamResponseEvent = new ServiceDownstreamResponseEvent(ORIGIN, SERVICE, OPERATION, downstreamRequestEvent);
xRayListener.listen(downstreamResponseEvent);
verify(downstreamDispatcher, times(1)).dispatchResponseEvent(downstreamResponseEvent);
}
@Test
public void testInvalidEvent() {
TransactionEvent invalidEvent = new TransactionBeginEvent(ORIGIN);
xRayListener.listen(invalidEvent);
verify(downstreamDispatcher, times(0)).dispatchResponseEvent(any());
verify(downstreamDispatcher, times(0)).dispatchResponseEvent(any());
verify(upstreamDispatcher, times(0)).dispatchResponseEvent(any());
verify(upstreamDispatcher, times(0)).dispatchResponseEvent(any());
}
@Test
public void testDispatcherException() {
// We expect the listener to be a catch-all for any exception,
// so ultimately, it shouldn't throw exceptions and mess up application code.
doThrow(new RuntimeException("Test Exception")).when(downstreamDispatcher).dispatchRequestEvent(any());
ServiceDownstreamRequestEvent downstreamRequestEvent = new ServiceDownstreamRequestEvent(ORIGIN, SERVICE, OPERATION);
verify(downstreamDispatcher, times(0)).dispatchRequestEvent(any());
xRayListener.listen(downstreamRequestEvent);
verify(downstreamDispatcher, times(1)).dispatchRequestEvent(any());
}
}
| 3,950 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime/handlers/XRayHandlerTest.java | package com.amazonaws.xray.agent.runtime.handlers;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import com.amazonaws.xray.agent.runtime.models.XRayTransactionState;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.strategy.sampling.SamplingResponse;
import com.amazonaws.xray.strategy.sampling.SamplingStrategy;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import software.amazon.disco.agent.event.Event;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class XRayHandlerTest {
private FakeHandler fakeHandler;
@Mock
private SamplingStrategy mockSamplingStrategy;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
when(mockSamplingStrategy.shouldTrace(any())).thenReturn(new SamplingResponse());
fakeHandler = new FakeHandler();
AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder.standard()
.withSamplingStrategy(mockSamplingStrategy)
.build()
);
AWSXRay.clearTraceEntity();
}
@Test
public void testRespectUpstreamSamplingDecision() {
XRayTransactionState state = new XRayTransactionState();
TraceHeader header = new TraceHeader(null, null, TraceHeader.SampleDecision.SAMPLED);
state.withTraceheaderString(header.toString());
boolean decision = fakeHandler.getSamplingDecision(state);
assertThat(decision).isTrue();
verify(mockSamplingStrategy, never()).shouldTrace(any());
}
@Test
public void testComputeSamplingDecisionForUnknown() {
XRayTransactionState state = new XRayTransactionState();
fakeHandler.getSamplingDecision(state);
assertThat(state.getTraceHeader()).isNull();
verify(mockSamplingStrategy, times((1))).shouldTrace(any());
}
private static class FakeHandler extends XRayHandler {
@Override
public void handleRequest(Event event) {
}
@Override
public void handleResponse(Event event) {
}
}
}
| 3,951 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime/handlers/downstream/SqlHandlerTest.java | package com.amazonaws.xray.agent.runtime.handlers.downstream;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.agent.runtime.config.XRaySDKConfiguration;
import com.amazonaws.xray.entities.Namespace;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.sql.SqlSubsegments;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import software.amazon.disco.agent.concurrent.TransactionContext;
import software.amazon.disco.agent.event.ServiceDownstreamRequestEvent;
import software.amazon.disco.agent.event.ServiceDownstreamResponseEvent;
import java.net.URL;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
/**
* Tests for the X-Ray Agent's handler of Disco SQL events.
* See unit tests for {@link com.amazonaws.xray.sql.SqlSubsegments} for more on expected contents of a SQL subsegment.
*/
public class SqlHandlerTest {
private static final String DB = "myDB";
private static final String QUERY = "SQL";
private static final String DB_URL = "http://example.com";
private SqlHandler handler;
private ServiceDownstreamRequestEvent requestEvent;
private ServiceDownstreamResponseEvent responseEvent;
@Mock
Statement mockStatement;
@Mock
Connection mockConnection;
@Mock
DatabaseMetaData mockMetaData;
@Before
public void setup() throws SQLException {
MockitoAnnotations.initMocks(this);
when(mockStatement.getConnection()).thenReturn(mockConnection);
when(mockConnection.getCatalog()).thenReturn(DB);
when(mockConnection.getMetaData()).thenReturn(mockMetaData);
when(mockMetaData.getURL()).thenReturn(DB_URL);
when(mockMetaData.getUserName()).thenReturn("USER");
when(mockMetaData.getDriverVersion()).thenReturn("DRIVER_VERSION");
when(mockMetaData.getDatabaseProductName()).thenReturn("DB_TYPE");
when(mockMetaData.getDatabaseProductVersion()).thenReturn("DB_VERSION");
handler = new SqlHandler();
TransactionContext.clear();
requestEvent = (ServiceDownstreamRequestEvent) new ServiceDownstreamRequestEvent("SQL", DB, QUERY)
.withRequest(mockStatement);
responseEvent = (ServiceDownstreamResponseEvent) new ServiceDownstreamResponseEvent("SQL", DB, QUERY, requestEvent)
.withThrown(new SQLException());
}
@After
public void cleanup() {
AWSXRay.clearTraceEntity();
}
@Test
public void testSubsegmentCreatedWithoutSql() {
XRaySDKConfiguration.getInstance().init();
AWSXRay.beginSegment("test"); // must be after config init
handler.handleRequest(requestEvent);
Subsegment sqlSub = AWSXRay.getCurrentSubsegment();
assertThat(sqlSub.isInProgress()).isTrue();
assertThat(sqlSub.getName()).isEqualTo(DB + "@example.com");
assertThat(sqlSub.getNamespace()).isEqualTo(Namespace.REMOTE.toString());
assertThat(sqlSub.getSql()).doesNotContainKey(SqlSubsegments.SANITIZED_QUERY);
}
@Test
public void testSubsegmentCreatedWithSql() {
URL configFile = SqlHandlerTest.class.getResource("/com/amazonaws/xray/agent/collectSqlConfig.json");
XRaySDKConfiguration.getInstance().init(configFile);
AWSXRay.beginSegment("test"); // must be after config init
handler.handleRequest(requestEvent);
Subsegment sqlSub = AWSXRay.getCurrentSubsegment();
assertThat(sqlSub.isInProgress()).isTrue();
assertThat(sqlSub.getName()).isEqualTo(DB + "@example.com");
assertThat(sqlSub.getNamespace()).isEqualTo(Namespace.REMOTE.toString());
assertThat(sqlSub.getSql()).containsEntry(SqlSubsegments.SANITIZED_QUERY, QUERY);
}
@Test
public void testSubsegmentCreatedDespiteException() throws SQLException {
when(mockStatement.getConnection()).thenThrow(new SQLException());
XRaySDKConfiguration.getInstance().init();
AWSXRay.beginSegment("test"); // must be after config init
handler.handleRequest(requestEvent);
Subsegment sqlSub = AWSXRay.getCurrentSubsegment();
assertThat(sqlSub.isInProgress()).isTrue();
assertThat(sqlSub.getName()).isEqualTo(SqlSubsegments.DEFAULT_DATABASE_NAME);
}
@Test
public void testSubsegmentEndedWithThrowable() {
XRaySDKConfiguration.getInstance().init();
Segment seg = AWSXRay.beginSegment("test"); // must be after config init
Subsegment sub = AWSXRay.beginSubsegment("FakeSqlSub");
TransactionContext.putMetadata(SqlHandler.SQL_SUBSEGMENT_COUNT_KEY, 1);
handler.handleResponse(responseEvent);
assertThat(seg.getSubsegments().size()).isEqualTo(1);
assertThat(sub.isInProgress()).isFalse();
assertThat(sub.getCause().getExceptions().size()).isEqualTo(1);
assertThat(sub.isFault()).isTrue();
}
}
| 3,952 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime/handlers/downstream/HttpClientHandlerTest.java | package com.amazonaws.xray.agent.runtime.handlers.downstream;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.entities.Namespace;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.entities.TraceID;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.modules.junit4.PowerMockRunner;
import software.amazon.disco.agent.event.HttpServiceDownstreamRequestEvent;
import software.amazon.disco.agent.event.HttpServiceDownstreamResponseEvent;
import java.net.URI;
import java.util.Map;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.net.ssl.*")
public class HttpClientHandlerTest {
private final String ORIGIN = "ApacheHttpClient";
private final String SERVICE = "https://amazon.com";
private final String OPERATION = "GET";
private final int STATUS_CODE = 200;
private final int CONTENT_LENGTH = 48343;
private HttpClientHandler httpClientHandler;
private Segment parentSegment;
private HttpServiceDownstreamRequestEvent httpClientRequestEvent;
private HttpServiceDownstreamResponseEvent httpClientResponseEvent;
@Before
public void setup() {
parentSegment = AWSXRay.beginSegment("HttpClientTestSegment");
httpClientHandler = new HttpClientHandler();
httpClientRequestEvent = new HttpServiceDownstreamRequestEvent(ORIGIN, SERVICE, OPERATION);
httpClientRequestEvent.withMethod(OPERATION);
httpClientRequestEvent.withUri(SERVICE);
httpClientResponseEvent = new HttpServiceDownstreamResponseEvent(ORIGIN, SERVICE, OPERATION, httpClientRequestEvent);
httpClientResponseEvent.withStatusCode(STATUS_CODE);
httpClientResponseEvent.withContentLength(CONTENT_LENGTH);
}
@After
public void clean() {
AWSXRay.clearTraceEntity();
}
@Test
public void testHandleGetRequest() throws Exception {
HttpServiceDownstreamRequestEvent requestEventSpy = spy(httpClientRequestEvent);
httpClientHandler.handleRequest(requestEventSpy);
Subsegment httpClientSubsegment = AWSXRay.getCurrentSubsegment();
Assert.assertEquals(Namespace.REMOTE.toString(), httpClientSubsegment.getNamespace());
Assert.assertEquals(new URI(SERVICE).getHost(), httpClientSubsegment.getName());
Assert.assertTrue(httpClientSubsegment.isInProgress());
Map<String, String> requestMap = (Map<String, String>) httpClientSubsegment.getHttp().get("request");
Assert.assertEquals(OPERATION, requestMap.get("method"));
// Trace header check
TraceID traceID = httpClientSubsegment.getParentSegment().getTraceId();
String parentID = httpClientSubsegment.getId();
TraceHeader.SampleDecision sampleDecision = parentSegment.isSampled() ? TraceHeader.SampleDecision.SAMPLED : TraceHeader.SampleDecision.NOT_SAMPLED;
TraceHeader theTraceHeader = new TraceHeader(traceID, parentID, sampleDecision);
verify(requestEventSpy).replaceHeader(TraceHeader.HEADER_KEY, theTraceHeader.toString());
Assert.assertEquals(parentSegment, httpClientSubsegment.getParentSegment());
Assert.assertEquals(1, parentSegment.getSubsegments().size());
}
@Test
public void testHandleGetResponse() {
Subsegment httpClientSubsegment = AWSXRay.beginSubsegment("responseSubsegment");
httpClientHandler.handleResponse(httpClientResponseEvent);
Map<String, String> responseMap = (Map<String, String>) httpClientSubsegment.getHttp().get("response");
Assert.assertFalse(httpClientSubsegment.isInProgress());
Assert.assertEquals(200,responseMap.get("status"));
Assert.assertEquals(1, parentSegment.getSubsegments().size());
}
@Test
public void testHandleInvalidRequest() {
HttpServiceDownstreamResponseEvent failedResponseEvent = new HttpServiceDownstreamResponseEvent(ORIGIN, SERVICE, OPERATION, httpClientRequestEvent);
failedResponseEvent.withStatusCode(500);
failedResponseEvent.withContentLength(1000);
Throwable ourThrowable = new IllegalArgumentException("Some illegal exception");
failedResponseEvent.withThrown(ourThrowable);
Subsegment httpClientSubsegment = AWSXRay.beginSubsegment("failedResponseSubsegment");
httpClientHandler.handleResponse(failedResponseEvent);
Assert.assertTrue(httpClientSubsegment.isFault());
Assert.assertEquals(1, httpClientSubsegment.getCause().getExceptions().size());
Assert.assertEquals(ourThrowable, httpClientSubsegment.getCause().getExceptions().get(0).getThrowable());
}
@Test
public void testHandle4xxStatusCode() {
httpClientResponseEvent.withStatusCode(400);
Subsegment httpClientSubsegment = AWSXRay.beginSubsegment("failedResponseSubsegment");
httpClientHandler.handleResponse(httpClientResponseEvent);
Assert.assertTrue(httpClientSubsegment.isError());
Assert.assertFalse(httpClientSubsegment.isFault());
Assert.assertFalse(httpClientSubsegment.isThrottle());
Map<String, Integer> httpResponseMap = (Map<String, Integer>) httpClientSubsegment.getHttp().get("response");
Assert.assertEquals(400, (int) httpResponseMap.get("status"));
}
@Test
public void testHandleThrottlingStatusCode() {
httpClientResponseEvent.withStatusCode(429);
Subsegment httpClientSubsegment = AWSXRay.beginSubsegment("failedResponseSubsegment");
httpClientHandler.handleResponse(httpClientResponseEvent);
Assert.assertTrue(httpClientSubsegment.isError());
Assert.assertFalse(httpClientSubsegment.isFault());
Assert.assertTrue(httpClientSubsegment.isThrottle());
Map<String, Integer> httpResponseMap = (Map<String, Integer>) httpClientSubsegment.getHttp().get("response");
Assert.assertEquals(429, (int) httpResponseMap.get("status"));
}
@Test
public void testHandle5xxStatusCode() {
httpClientResponseEvent.withStatusCode(500);
Subsegment httpClientSubsegment = AWSXRay.beginSubsegment("failedResponseSubsegment");
httpClientHandler.handleResponse(httpClientResponseEvent);
Assert.assertTrue(httpClientSubsegment.isFault());
Assert.assertFalse(httpClientSubsegment.isError());
Assert.assertFalse(httpClientSubsegment.isThrottle());
Map<String, Integer> httpResponseMap = (Map<String, Integer>) httpClientSubsegment.getHttp().get("response");
Assert.assertEquals(500, (int) httpResponseMap.get("status"));
}
}
| 3,953 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime/handlers/downstream/SqlPrepareHandlerTest.java | package com.amazonaws.xray.agent.runtime.handlers.downstream;
import com.amazonaws.xray.agent.runtime.models.XRayTransactionState;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import software.amazon.disco.agent.event.ServiceDownstreamRequestEvent;
import software.amazon.disco.agent.event.ServiceDownstreamResponseEvent;
import java.sql.PreparedStatement;
import static org.assertj.core.api.Assertions.assertThat;
public class SqlPrepareHandlerTest {
private SqlPrepareHandler handler;
@Mock
private PreparedStatement preparedStatementMock;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
handler = new SqlPrepareHandler();
}
@Test
public void testPreparedStatementMapInsertion() {
String sql = "SELECT * FROM my_table";
ServiceDownstreamRequestEvent requestEvent = new ServiceDownstreamRequestEvent("origin", "service", sql);
ServiceDownstreamResponseEvent responseEvent = new ServiceDownstreamResponseEvent("origin", "service", sql, requestEvent);
responseEvent.withResponse(preparedStatementMock);
handler.handleResponse(responseEvent);
assertThat(XRayTransactionState.getPreparedQuery(preparedStatementMock)).isEqualTo(sql);
}
}
| 3,954 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime/handlers/downstream/AWSHandlerTest.java | package com.amazonaws.xray.agent.runtime.handlers.downstream;
import com.amazonaws.Request;
import com.amazonaws.Response;
import com.amazonaws.ResponseMetadata;
import com.amazonaws.http.HttpResponse;
import com.amazonaws.http.SdkHttpMetadata;
import com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException;
import com.amazonaws.services.dynamodbv2.model.ScanRequest;
import com.amazonaws.services.dynamodbv2.model.ScanResult;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.entities.TraceID;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.modules.junit4.PowerMockRunner;
import software.amazon.disco.agent.event.ServiceDownstreamRequestEvent;
import software.amazon.disco.agent.event.ServiceDownstreamResponseEvent;
import java.util.HashMap;
import java.util.Map;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.net.ssl.*")
public class AWSHandlerTest {
private final String ORIGIN = "AWSv1";
private final String SERVICE = "AmazonDynamoDBv2";
private final String OPERATION = "ScanRequest";
// DynamoDB Specific fake request and response object properties
private final String TABLE_NAME = "TestTableName";
private final String AWS_REQUEST_ID = "SOMERANDOMID";
private final int COUNT = 25;
private final int SCAN_COUNT = 10;
private AWSHandler awsHandler;
@Mock
private Request awsRequest;
private Response awsResponse;
private ScanRequest scanRequest;
private ScanResult scanResult;
private Segment parentSegment;
private ScanResult generateFakeScanResult() {
ScanResult theScanResult = new ScanResult();
Map<String, String> metadataMap = new HashMap<>();
metadataMap.put("AWS_REQUEST_ID", AWS_REQUEST_ID);
ResponseMetadata sdkResponseMetadata = new ResponseMetadata(metadataMap);
theScanResult.setSdkResponseMetadata(sdkResponseMetadata);
Map<String, String> headerMap = new HashMap<>();
HttpResponse fakeHttpResponse = mock(HttpResponse.class);
when(fakeHttpResponse.getHeaders()).thenReturn(headerMap);
when(fakeHttpResponse.getStatusCode()).thenReturn(200);
SdkHttpMetadata sdkHttpMetadata = SdkHttpMetadata.from(fakeHttpResponse);
theScanResult.setSdkHttpMetadata(sdkHttpMetadata);
return theScanResult;
}
@Before
public void setup() {
parentSegment = AWSXRay.beginSegment("TestSegment");
awsHandler = new AWSHandler();
// We create an imitation DynamoDB request/response for this test.
// Mock the request object
scanRequest = new ScanRequest("TestName");
when(awsRequest.getOriginalRequest()).thenReturn(scanRequest);
when(awsRequest.getServiceName()).thenReturn(SERVICE);
scanRequest.setTableName(TABLE_NAME);
// Generate a "fake" response now; populate it with metadata X-Ray would gather.
scanResult = generateFakeScanResult();
scanResult.setCount(COUNT);
scanResult.setScannedCount(SCAN_COUNT);
HttpResponse fakeHttpResponse = mock(HttpResponse.class);
when(fakeHttpResponse.getHeaders()).thenReturn(scanResult.getSdkHttpMetadata().getHttpHeaders());
when(fakeHttpResponse.getStatusCode()).thenReturn(scanResult.getSdkHttpMetadata().getHttpStatusCode());
awsResponse = new Response(scanResult, fakeHttpResponse);
}
@After
public void cleanup() {
AWSXRay.clearTraceEntity();
}
@Test
public void testHandleAWSRequest() {
ServiceDownstreamRequestEvent awsRequestEvent = new ServiceDownstreamRequestEvent(ORIGIN, SERVICE, OPERATION);
awsRequestEvent.withRequest(awsRequest);
awsHandler.handleRequest(awsRequestEvent);
Subsegment awsSubsegment = AWSXRay.getCurrentSubsegment();
Assert.assertEquals("aws", awsSubsegment.getNamespace());
Assert.assertEquals(SERVICE, awsSubsegment.getName());
Assert.assertTrue(awsSubsegment.isInProgress());
Map<String, Object> awsMap = awsSubsegment.getAws();
Assert.assertEquals("Scan", awsMap.get("operation"));
Assert.assertEquals(TABLE_NAME, awsMap.get("table_name"));
Assert.assertEquals(parentSegment, awsSubsegment.getParentSegment());
Assert.assertEquals(1, parentSegment.getSubsegments().size());
}
@Test
public void testPopulateTraceHeaderToHttpHeader() {
// Ensure that we propagate the trace header to the request's http header.
ServiceDownstreamRequestEvent awsRequestEvent = new ServiceDownstreamRequestEvent(ORIGIN, SERVICE, OPERATION);
awsRequestEvent.withRequest(awsRequest);
awsHandler.handleRequest(awsRequestEvent);
TraceID traceID = parentSegment.getTraceId();
String parentID = AWSXRay.getCurrentSubsegment().getId();
TraceHeader.SampleDecision sampleDecision = parentSegment.isSampled() ? TraceHeader.SampleDecision.SAMPLED : TraceHeader.SampleDecision.NOT_SAMPLED;
TraceHeader theTraceHeader = new TraceHeader(traceID, parentID, sampleDecision);
verify(awsRequest).addHeader(TraceHeader.HEADER_KEY, theTraceHeader.toString());
}
@Test
public void testHandleAWSResponse() {
ServiceDownstreamRequestEvent awsRequestEvent = new ServiceDownstreamRequestEvent(ORIGIN, SERVICE, OPERATION);
awsRequestEvent.withRequest(awsRequest);
ServiceDownstreamResponseEvent awsResponseEvent = new ServiceDownstreamResponseEvent(ORIGIN, SERVICE, OPERATION, awsRequestEvent);
awsResponseEvent.withResponse(awsResponse);
Subsegment awsSubsegment = AWSXRay.beginSubsegment(SERVICE);
awsSubsegment.setNamespace("aws"); // Mimic aws namespace so that the subsegment would be processed.
awsHandler.handleResponse(awsResponseEvent);
Map<String, Object> awsMap = awsSubsegment.getAws();
Assert.assertEquals(AWS_REQUEST_ID, awsMap.get("request_id"));
Assert.assertEquals(SCAN_COUNT, awsMap.get("scanned_count"));
Assert.assertEquals(COUNT, awsMap.get("count"));
Map<String, Object> httpMap = awsSubsegment.getHttp();
Assert.assertEquals(200, ((Map<String, Integer>) httpMap.get("response")).get("status").intValue());
}
@Test
public void testHandleEventFault() {
ServiceDownstreamRequestEvent awsRequestEvent = new ServiceDownstreamRequestEvent(ORIGIN, SERVICE, OPERATION);
awsRequestEvent.withRequest(awsRequest);
ServiceDownstreamResponseEvent awsResponseEvent = new ServiceDownstreamResponseEvent(ORIGIN, SERVICE, OPERATION, awsRequestEvent);
awsResponseEvent.withResponse(null);
awsResponseEvent.withThrown(new AmazonDynamoDBException("Some error"));
Subsegment awsSubsegment = AWSXRay.beginSubsegment(SERVICE);
awsSubsegment.setNamespace("aws"); // Mimic aws namespace so that the subsegment would be processed.
Assert.assertEquals(0, awsSubsegment.getCause().getExceptions().size());
awsHandler.handleResponse(awsResponseEvent);
// Ensure that our subsegment has the error in it.
Assert.assertEquals(1, awsSubsegment.getCause().getExceptions().size());
Assert.assertTrue(awsSubsegment.isFault());
}
}
| 3,955 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent/src/test/java/com/amazonaws/xray/agent/runtime/handlers/upstream/ServletHandlerTest.java | package com.amazonaws.xray.agent.runtime.handlers.upstream;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import com.amazonaws.xray.agent.runtime.config.XRaySDKConfiguration;
import com.amazonaws.xray.agent.runtime.models.XRayTransactionState;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.entities.TraceID;
import com.amazonaws.xray.strategy.LogErrorContextMissingStrategy;
import com.amazonaws.xray.strategy.sampling.NoSamplingStrategy;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import software.amazon.disco.agent.event.HttpServletNetworkRequestEvent;
import software.amazon.disco.agent.event.HttpServletNetworkResponseEvent;
import java.util.HashMap;
import java.util.Map;
import static org.mockito.Mockito.mock;
public class ServletHandlerTest {
public static final String HEADER_KEY = "X-Amzn-Trace-Id";
private final String ORIGIN = "httpServlet";
private final String SERVICE_NAME = "SomeServletHostedService";
private final String SDK = "X-Ray for Java";
// Transaction State configurations
private final String HOST = "localhost:8080";
private final String METHOD = "POST";
private final String URL = "http://localhost:8080/";
private final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36";
private final String DST_IP = "192.52.32.10";
private final String SRC_IP = "152.152.152.2";
private ServletHandler servletHandler;
@Mock
private Emitter blankEmitter;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
XRaySDKConfiguration.getInstance().init();
AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder
.standard()
.withContextMissingStrategy(new LogErrorContextMissingStrategy())
.withSamplingStrategy(new NoSamplingStrategy())
.withEmitter(blankEmitter)
.build());
servletHandler = new ServletHandler();
XRayTransactionState.setServiceName(SERVICE_NAME);
}
@After
public void cleanup() {
AWSXRay.clearTraceEntity();
}
@Test
public void testHandleRequest() {
HttpServletNetworkRequestEvent requestEvent = new HttpServletNetworkRequestEvent(ORIGIN, 54, 32, SRC_IP, DST_IP);
requestEvent.withHost(HOST)
.withMethod(METHOD)
.withURL(URL)
.withUserAgent(USER_AGENT);
Assert.assertFalse(AWSXRay.getCurrentSegmentOptional().isPresent());
servletHandler.handleRequest(requestEvent);
Assert.assertTrue(AWSXRay.getCurrentSegmentOptional().isPresent());
Segment servletSegment = AWSXRay.getCurrentSegment();
Assert.assertEquals(SERVICE_NAME, servletSegment.getName());
Map<String, String> httpMap = (Map<String, String>) servletSegment.getHttp().get("request");
Assert.assertEquals(METHOD, httpMap.get("method"));
Assert.assertEquals(SRC_IP, httpMap.get("client_ip"));
Assert.assertNull(httpMap.get("x_forwarded_for"));
Assert.assertEquals(URL, httpMap.get("url"));
Assert.assertEquals(USER_AGENT, httpMap.get("user_agent"));
Map<String, Object> xrayMap = (Map<String, Object>) servletSegment.getAws().get("xray");
Assert.assertEquals(SDK, xrayMap.get("sdk"));
Assert.assertEquals(Boolean.TRUE, xrayMap.get("auto_instrumentation"));
}
@Test
public void testHandleRequestWithTraceHeader() {
HttpServletNetworkRequestEvent requestEvent = new HttpServletNetworkRequestEvent(ORIGIN, 54, 32, SRC_IP, DST_IP);
TraceID traceID = new TraceID();
String parentId = "1fb64b3cbdcd5705";
TraceHeader thSampled = new TraceHeader(traceID, parentId, TraceHeader.SampleDecision.SAMPLED);
Map<String, String> headerMap = new HashMap<>();
headerMap.put(HEADER_KEY.toLowerCase(), thSampled.toString());
requestEvent.withHeaderMap(headerMap);
servletHandler.handleRequest(requestEvent);
Segment servletSegment = AWSXRay.getCurrentSegment();
Assert.assertTrue(servletSegment.isSampled());
Assert.assertEquals(thSampled.getRootTraceId(), servletSegment.getTraceId());
Assert.assertEquals(thSampled.getParentId(), parentId);
Assert.assertEquals(thSampled.getSampled() == TraceHeader.SampleDecision.SAMPLED, servletSegment.isSampled());
AWSXRay.clearTraceEntity();
TraceHeader thUnsampled = new TraceHeader(traceID, parentId, TraceHeader.SampleDecision.NOT_SAMPLED);
headerMap = new HashMap<>();
headerMap.put(HEADER_KEY.toLowerCase(), thUnsampled.toString());
requestEvent.withHeaderMap(headerMap);
servletHandler.handleRequest(requestEvent);
servletSegment = AWSXRay.getCurrentSegment();
Assert.assertFalse(servletSegment.isSampled());
Assert.assertEquals(thSampled.getRootTraceId(), servletSegment.getTraceId());
Assert.assertEquals(thSampled.getParentId(), parentId);
Assert.assertEquals(thSampled.getSampled() == TraceHeader.SampleDecision.NOT_SAMPLED, servletSegment.isSampled());
}
@Test
public void testClienIPFallsBackToHeader() {
String forwardedForIP = "My IP address";
HttpServletNetworkRequestEvent requestEvent = new HttpServletNetworkRequestEvent(ORIGIN, 54, 32, SRC_IP, null);
Map<String, String> headers = new HashMap<>();
headers.put("X-Forwarded-For", forwardedForIP);
requestEvent.withHeaderMap(headers);
servletHandler.handleRequest(requestEvent);
Segment segment = AWSXRay.getCurrentSegment();
Assert.assertNull(requestEvent.getLocalIPAddress());
Assert.assertNotNull(segment);
Map<String, Object> requestMap = (Map<String, Object>) segment.getHttp().get("request");
Assert.assertEquals(forwardedForIP, requestMap.get("client_ip"));
Assert.assertEquals(true, requestMap.get("x_forwarded_for"));
}
@Test
public void testHandleResponse() {
HttpServletNetworkRequestEvent requestEvent = mock(HttpServletNetworkRequestEvent.class);
HttpServletNetworkResponseEvent responseEvent = new HttpServletNetworkResponseEvent(ORIGIN, requestEvent);
responseEvent.withStatusCode(200);
Segment servletSegment = AWSXRay.beginSegment(SERVICE_NAME);
servletHandler.handleResponse(responseEvent);
Assert.assertEquals(200, ((Map<String, Integer>) servletSegment.getHttp().get("response")).get("status").intValue());
}
@Test
public void testHandleResponseErrors() {
HttpServletNetworkRequestEvent requestEvent = mock(HttpServletNetworkRequestEvent.class);
HttpServletNetworkResponseEvent responseEvent = new HttpServletNetworkResponseEvent(ORIGIN, requestEvent);
Segment servletSegment = AWSXRay.beginSegment(SERVICE_NAME);
responseEvent.withStatusCode(400);
servletHandler.handleResponse(responseEvent);
Assert.assertEquals(400, ((Map<String, Integer>) servletSegment.getHttp().get("response")).get("status").intValue());
Assert.assertTrue(servletSegment.isError());
Assert.assertFalse(servletSegment.isFault());
AWSXRay.clearTraceEntity();
servletSegment = AWSXRay.beginSegment(SERVICE_NAME);
responseEvent.withStatusCode(500);
servletHandler.handleResponse(responseEvent);
Assert.assertEquals(500, ((Map<String, Integer>) servletSegment.getHttp().get("response")).get("status").intValue());
Assert.assertFalse(servletSegment.isError());
Assert.assertTrue(servletSegment.isFault());
}
@Test
public void testContextMissingInResponse() {
HttpServletNetworkRequestEvent requestEvent = new HttpServletNetworkRequestEvent(ORIGIN, 1, 1, "test", "test");
HttpServletNetworkResponseEvent responseEvent = new HttpServletNetworkResponseEvent(ORIGIN, requestEvent);
// Explicitly clear context
AWSXRay.clearTraceEntity();
Assert.assertNull(AWSXRay.getTraceEntity());
// Verifies no NPEs or similar are thrown
servletHandler.handleResponse(responseEvent);
}
}
| 3,956 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/AgentRuntimeLoader.java | package com.amazonaws.xray.agent.runtime;
import com.amazonaws.xray.agent.runtime.config.XRaySDKConfiguration;
import com.amazonaws.xray.agent.runtime.listeners.ListenerFactory;
import com.amazonaws.xray.agent.runtime.listeners.XRayListenerFactory;
import com.amazonaws.xray.agent.runtime.models.XRayTransactionState;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.checkerframework.checker.nullness.qual.Nullable;
import software.amazon.disco.agent.event.EventBus;
import software.amazon.disco.agent.event.Listener;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Bridge between classes residing in the bootstrap classloader or application classloader;
* basically, modules that need to be invoked during application runtime--not the Agent's premain.
*/
public class AgentRuntimeLoader {
private static final String CONFIG_FILE_SYS_PROPERTY = "com.amazonaws.xray.configFile";
private static final String CONFIG_FILE_DEFAULT_LOCATION = "/xray-agent.json";
private static final String CONFIG_FILE_SPRING_BOOT_LOCATION = "/BOOT-INF/classes/xray-agent.json";
private static final Log log = LogFactory.getLog(AgentRuntimeLoader.class);
private static ListenerFactory listenerFactory = new XRayListenerFactory();
// exposed for testing
static void setListenerFactory(ListenerFactory factory) {
listenerFactory = factory;
}
/**
* Wrapper for main init method used by DiSCo Plugin model.
*/
public static void init() {
init(null);
}
/**
* Initialize the classes belonging in the runtime.
* @param serviceName - The service name that this agent represents passed from the command line.
*/
public static void init(@Nullable String serviceName) {
if (serviceName != null) {
log.warn("Setting the X-Ray service name via JVM arguments is deprecated. Use the agent's " +
"configuration file instead.");
XRayTransactionState.setServiceName(serviceName);
}
// Configuration needs to be done before we initialize the listener because its handlers
// rely on X-Ray configurations upon init.
boolean enabled = configureXRay();
if (!enabled) {
return;
}
Listener listener = listenerFactory.generateListener();
EventBus.addListener(listener);
}
/**
* Helper method to configure the internal global recorder. It can throw exceptions to interrupt customer's
* code at startup to notify them of invalid configuration rather than assuming defaults which might be unexpected.
*/
private static boolean configureXRay() {
XRaySDKConfiguration configuration = XRaySDKConfiguration.getInstance();
URL configFile = getConfigFile();
if (configFile != null) {
configuration.init(configFile);
} else {
configuration.init();
}
return configuration.isEnabled();
}
/**
* Helper method to retrieve the xray-agent config file's URL. First checks the provided path on the file system,
* then falls back to checking the system classpath, before giving up and returning null.
*
* @return the URL of config file or null if it wasn't found
*
* Visible for testing
*/
@Nullable
static URL getConfigFile() {
String customLocation = System.getProperty(CONFIG_FILE_SYS_PROPERTY);
if (customLocation != null && !customLocation.isEmpty()) {
try {
File file = new File(customLocation);
if (file.exists()) {
return file.toURI().toURL();
} else {
return AgentRuntimeLoader.class.getResource(customLocation);
}
} catch (MalformedURLException e) {
log.error("X-Ray agent config file's custom location was malformed. " +
"Falling back to default configuration.");
return null;
}
}
// Search root of classpath first, then check root of Spring Boot classpath
URL defaultLocation = AgentRuntimeLoader.class.getResource(CONFIG_FILE_DEFAULT_LOCATION);
if (defaultLocation == null) {
defaultLocation = AgentRuntimeLoader.class.getResource(CONFIG_FILE_SPRING_BOOT_LOCATION);
}
return defaultLocation;
}
}
| 3,957 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/package-info.java | /**
* Classes used for initializing the X-Ray Recorder used by the agent and handling events at runtime.
*/
package com.amazonaws.xray.agent.runtime; | 3,958 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/config/InvalidAgentConfigException.java | package com.amazonaws.xray.agent.runtime.config;
public class InvalidAgentConfigException extends RuntimeException {
public InvalidAgentConfigException(String msg) {
super(msg);
}
public InvalidAgentConfigException(String msg, Throwable err) {
super(msg, err);
}
}
| 3,959 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/config/AgentConfiguration.java | package com.amazonaws.xray.agent.runtime.config;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Map;
import java.util.Objects;
/**
* Class represents the agent configuration's JSON file. It is immutable and thus completely thread-safe.
*/
public final class AgentConfiguration {
static final String DEFAULT_SERVICE_NAME = "XRayInstrumentedService";
private static final Log log = LogFactory.getLog(AgentConfiguration.class);
private final String serviceName;
private final String contextMissingStrategy;
private final String daemonAddress;
private final String samplingStrategy;
private final String traceIdInjectionPrefix;
private final int maxStackTraceLength;
private final int streamingThreshold;
private final int awsSdkVersion;
private final boolean pluginsEnabled;
private final boolean tracingEnabled;
private final boolean collectSqlQueries;
private final boolean traceIdInjection;
private final boolean contextPropagation;
private final boolean traceIncomingRequests;
@Nullable
private final String samplingRulesManifest;
@Nullable
private final String awsServiceHandlerManifest;
/**
* Sets default values
*/
public AgentConfiguration() {
serviceName = DEFAULT_SERVICE_NAME;
contextMissingStrategy = "LOG_ERROR";
daemonAddress = "127.0.0.1:2000";
samplingStrategy = "CENTRAL";
traceIdInjectionPrefix = "";
maxStackTraceLength = 50;
streamingThreshold = 100;
samplingRulesManifest = null; // Manifests are null by default since the default location file will be found later
awsSdkVersion = 2;
awsServiceHandlerManifest = null;
pluginsEnabled = true;
tracingEnabled = true;
collectSqlQueries = false;
traceIdInjection = true;
contextPropagation = true;
traceIncomingRequests = true;
}
/**
* Constructs agent configuration from provided map. Does not do any validation since that is taken care of in
* {@link XRaySDKConfiguration}. Can throw {@code InvalidAgentConfigException} if improper type is assigned to any
* property. Assigns all non-configured properties to default values.
* @param properties - Map of property names to their values in string representation, which will be cast to proper types.
*/
public AgentConfiguration(@Nullable Map<String, String> properties) {
String serviceName = DEFAULT_SERVICE_NAME,
contextMissingStrategy = "LOG_ERROR",
daemonAddress = "127.0.0.1:2000",
samplingStrategy = "CENTRAL",
traceIdInjectionPrefix = "",
samplingRulesManifest = null,
awsServiceHandlerManifest = null;
int maxStackTraceLength = 50,
streamingThreshold = 100,
awsSdkVersion = 2;
boolean pluginsEnabled = true,
tracingEnabled = true,
collectSqlQueries = false,
traceIdInjection = true,
contextPropagation = true,
traceIncomingRequests = true;
if (properties != null) {
try {
for (Map.Entry<String, String> entry : properties.entrySet()) {
switch (entry.getKey()) {
case "serviceName":
serviceName = entry.getValue();
break;
case "contextMissingStrategy":
contextMissingStrategy = entry.getValue();
break;
case "daemonAddress":
daemonAddress = entry.getValue();
break;
case "samplingStrategy":
samplingStrategy = entry.getValue();
break;
case "traceIdInjectionPrefix":
traceIdInjectionPrefix = entry.getValue();
break;
case "maxStackTraceLength":
maxStackTraceLength = Integer.parseInt(entry.getValue());
break;
case "streamingThreshold":
streamingThreshold = Integer.parseInt(entry.getValue());
break;
case "samplingRulesManifest":
samplingRulesManifest = entry.getValue();
break;
case "awsSdkVersion":
awsSdkVersion = Integer.parseInt(entry.getValue());
break;
case "awsServiceHandlerManifest":
awsServiceHandlerManifest = entry.getValue();
break;
case "pluginsEnabled":
pluginsEnabled = Boolean.parseBoolean(entry.getValue());
break;
case "tracingEnabled":
tracingEnabled = Boolean.parseBoolean(entry.getValue());
break;
case "collectSqlQueries":
collectSqlQueries = Boolean.parseBoolean(entry.getValue());
break;
case "traceIdInjection":
traceIdInjection = Boolean.parseBoolean(entry.getValue());
break;
case "contextPropagation":
contextPropagation = Boolean.parseBoolean(entry.getValue());
break;
case "traceIncomingRequests":
traceIncomingRequests = Boolean.parseBoolean(entry.getValue());
break;
default:
log.warn("Encountered unknown property " + entry.getKey() + " in X-Ray agent configuration. Ignoring.");
break;
}
}
} catch (Exception e) {
throw new InvalidAgentConfigException("Invalid type given in X-Ray Agent configuration file", e);
}
}
this.serviceName = serviceName;
this.contextMissingStrategy = contextMissingStrategy;
this.daemonAddress = daemonAddress;
this.samplingStrategy = samplingStrategy;
this.traceIdInjectionPrefix = traceIdInjectionPrefix;
this.maxStackTraceLength = maxStackTraceLength;
this.streamingThreshold = streamingThreshold;
this.samplingRulesManifest = samplingRulesManifest;
this.awsSdkVersion = awsSdkVersion;
this.awsServiceHandlerManifest = awsServiceHandlerManifest;
this.pluginsEnabled = pluginsEnabled;
this.tracingEnabled = tracingEnabled;
this.collectSqlQueries = collectSqlQueries;
this.traceIdInjection = traceIdInjection;
this.contextPropagation = contextPropagation;
this.traceIncomingRequests = traceIncomingRequests;
}
public String getServiceName() {
return serviceName;
}
public String getContextMissingStrategy() {
return contextMissingStrategy;
}
public String getDaemonAddress() {
return daemonAddress;
}
public String getSamplingStrategy() {
return samplingStrategy;
}
public String getTraceIdInjectionPrefix() { return traceIdInjectionPrefix; }
public int getMaxStackTraceLength() {
return maxStackTraceLength;
}
public int getStreamingThreshold() {
return streamingThreshold;
}
@Nullable
public String getSamplingRulesManifest() {
return samplingRulesManifest;
}
public int getAwsSdkVersion() {
return awsSdkVersion;
}
@Nullable
public String getAwsServiceHandlerManifest() {
return awsServiceHandlerManifest;
}
public boolean arePluginsEnabled() { return pluginsEnabled; }
public boolean isTracingEnabled() {
return tracingEnabled;
}
public boolean shouldCollectSqlQueries() { return collectSqlQueries; }
public boolean isTraceIdInjection() { return traceIdInjection; }
public boolean isContextPropagation() { return contextPropagation; }
public boolean isTraceIncomingRequests() { return traceIncomingRequests; }
@Override
public String toString() {
return "AgentConfiguration{" +
"serviceName='" + serviceName + '\'' +
", contextMissingStrategy='" + contextMissingStrategy + '\'' +
", daemonAddress='" + daemonAddress + '\'' +
", samplingStrategy='" + samplingStrategy + '\'' +
", traceIdInjectionPrefix='" + traceIdInjectionPrefix + '\'' +
", maxStackTraceLength=" + maxStackTraceLength +
", streamingThreshold=" + streamingThreshold +
", samplingRulesManifest='" + samplingRulesManifest + '\'' +
", awsSdkVersion='" + awsSdkVersion + '\'' +
", awsServiceHandlerManifest='" + awsServiceHandlerManifest + '\'' +
", pluginsEnabled=" + pluginsEnabled +
", tracingEnabled=" + tracingEnabled +
", collectSqlQueries=" + collectSqlQueries +
", traceIdInjection=" + traceIdInjection +
", contextPropagation=" + contextPropagation +
", traceIncomingRequests=" + traceIncomingRequests +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AgentConfiguration that = (AgentConfiguration) o;
return maxStackTraceLength == that.maxStackTraceLength &&
streamingThreshold == that.streamingThreshold &&
awsSdkVersion == that.awsSdkVersion &&
pluginsEnabled == that.pluginsEnabled &&
tracingEnabled == that.tracingEnabled &&
collectSqlQueries == that.collectSqlQueries &&
traceIdInjection == that.traceIdInjection &&
contextPropagation == that.contextPropagation &&
traceIncomingRequests == that.traceIncomingRequests &&
serviceName.equals(that.serviceName) &&
contextMissingStrategy.equals(that.contextMissingStrategy) &&
daemonAddress.equals(that.daemonAddress) &&
samplingStrategy.equals(that.samplingStrategy) &&
traceIdInjectionPrefix.equals(that.traceIdInjectionPrefix) &&
Objects.equals(samplingRulesManifest, that.samplingRulesManifest) &&
Objects.equals(awsServiceHandlerManifest, that.awsServiceHandlerManifest);
}
@Override
public int hashCode() {
return Objects.hash(serviceName, contextMissingStrategy, daemonAddress, samplingStrategy, traceIdInjection, traceIdInjectionPrefix, maxStackTraceLength, streamingThreshold, awsSdkVersion, pluginsEnabled, tracingEnabled, collectSqlQueries, contextPropagation, traceIncomingRequests, samplingRulesManifest, awsServiceHandlerManifest);
}
}
| 3,960 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/config/XRaySDKConfiguration.java | package com.amazonaws.xray.agent.runtime.config;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import com.amazonaws.xray.agent.runtime.models.XRayTransactionContextResolver;
import com.amazonaws.xray.agent.runtime.models.XRayTransactionState;
import com.amazonaws.xray.config.DaemonConfiguration;
import com.amazonaws.xray.contexts.LambdaSegmentContextResolver;
import com.amazonaws.xray.contexts.SegmentContextResolverChain;
import com.amazonaws.xray.contexts.ThreadLocalSegmentContextResolver;
import com.amazonaws.xray.emitters.UDPEmitter;
import com.amazonaws.xray.entities.StringValidator;
import com.amazonaws.xray.listeners.SegmentListener;
import com.amazonaws.xray.strategy.DefaultStreamingStrategy;
import com.amazonaws.xray.strategy.DefaultThrowableSerializationStrategy;
import com.amazonaws.xray.strategy.IgnoreErrorContextMissingStrategy;
import com.amazonaws.xray.strategy.LogErrorContextMissingStrategy;
import com.amazonaws.xray.strategy.SegmentNamingStrategy;
import com.amazonaws.xray.strategy.sampling.AllSamplingStrategy;
import com.amazonaws.xray.strategy.sampling.CentralizedSamplingStrategy;
import com.amazonaws.xray.strategy.sampling.LocalizedSamplingStrategy;
import com.amazonaws.xray.strategy.sampling.NoSamplingStrategy;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Singleton class that represents the X-Ray Agent's configuration programmatically. This class is responsible for
* parsing and validating the contents of the agent's configuration file. It also reads the environment variables
* and system properties for relevant configurations. Priority for settings is as follows:
*
* 1. Environment variables
* 2. System properties
* 3. Configuration file values
* 4. Default value
*
* For now, environment variable and system property overrides are handled in various locations of the SDK.
* Note that configuring these values programmatically is still possible, and will override the configuration file and
* default value set here, but that is not recommended.
*/
public class XRaySDKConfiguration {
// Visible for testing
static final String LAMBDA_TASK_ROOT_KEY = "LAMBDA_TASK_ROOT";
static final String ENABLED_ENVIRONMENT_VARIABLE_KEY = "AWS_XRAY_TRACING_ENABLED";
static final String ENABLED_SYSTEM_PROPERTY_KEY = "com.amazonaws.xray.tracingEnabled";
private static final String[] TRACE_ID_INJECTION_CLASSES = {
"com.amazonaws.xray.log4j.Log4JSegmentListener",
"com.amazonaws.xray.slf4j.SLF4JSegmentListener"
};
private static final Log log = LogFactory.getLog(XRaySDKConfiguration.class);
/* JSON factory used instead of mapper for performance */
private static final JsonFactory factory = new JsonFactory();
/* Singleton instance */
private static final XRaySDKConfiguration instance = new XRaySDKConfiguration();
/* Configuration storage */
private AgentConfiguration agentConfiguration;
/* Indicator for whether trace ID injection has been configured */
private boolean traceIdInjectionConfigured;
/* AWS Manifest whitelist, for runtime loader access */
@Nullable
private URL awsServiceHandlerManifest = null;
private int awsSdkVersion;
/* Context missing enums */
enum ContextMissingStrategy {
LOG_ERROR,
IGNORE_ERROR,
}
/* Sampling strategy enums */
enum SamplingStrategy {
LOCAL,
CENTRAL,
NONE,
ALL,
}
public int getAwsSdkVersion() {
return awsSdkVersion;
}
@Nullable
public URL getAwsServiceHandlerManifest() {
return awsServiceHandlerManifest;
}
// Visible for testing
AgentConfiguration getAgentConfiguration() {
return agentConfiguration;
}
// Visible for testing
void setAgentConfiguration(AgentConfiguration agentConfiguration) {
this.agentConfiguration = agentConfiguration;
}
public boolean isEnabled() {
return agentConfiguration.isTracingEnabled();
}
public boolean shouldCollectSqlQueries() { return agentConfiguration.shouldCollectSqlQueries(); }
public boolean isTraceIncomingRequests() {
return agentConfiguration.isTraceIncomingRequests();
}
// Visible for testing
XRaySDKConfiguration() {
}
/**
* @return XRaySDKConfiguration - The global instance of this agent recorder configuration.
*/
public static XRaySDKConfiguration getInstance() {
return instance;
}
/**
* Parses the given agent configuration file and stores its properties. If file is missing or incorrectly formatted,
* throw an {@code InvalidAgentConfigException}. If {@code null} is passed in, configures the agent with default
* properties.
* @param configFile - Location of configuration file
*/
public void init(@Nullable URL configFile) {
if (configFile == null) {
this.agentConfiguration = new AgentConfiguration();
} else {
try {
log.info("Reading X-Ray Agent config file at: " + configFile.getPath());
this.agentConfiguration = parseConfig(configFile);
} catch (IOException e) {
throw new InvalidAgentConfigException("Failed to read X-Ray Agent configuration file " + configFile.getPath(), e);
}
}
if (log.isDebugEnabled()) {
log.debug("Starting the X-Ray Agent with the following properties:\n" + agentConfiguration.toString());
}
init(AWSXRayRecorderBuilder.standard());
}
/**
* Initialize the X-Ray SDK's Recorder used by the agent with default settings.
* Clears out any previously stored configuration.
*/
public void init() {
this.agentConfiguration = null;
init(AWSXRayRecorderBuilder.standard());
}
// Visible for testing
void init(AWSXRayRecorderBuilder builder) {
log.info("Initializing the X-Ray Agent Recorder");
// Reset to defaults
if (agentConfiguration == null) {
agentConfiguration = new AgentConfiguration();
}
this.awsServiceHandlerManifest = null;
this.awsSdkVersion = 0;
// X-Ray Enabled
if ("false".equalsIgnoreCase(System.getenv(ENABLED_ENVIRONMENT_VARIABLE_KEY)) ||
"false".equalsIgnoreCase(System.getProperty(ENABLED_SYSTEM_PROPERTY_KEY)) ||
!agentConfiguration.isTracingEnabled())
{
log.info("Instrumentation via the X-Ray Agent has been disabled by user configuration.");
return;
}
/*
Service name is unique since it can still be set via JVM arg. So we check for that first, then proceed with
the normal priority of properties. Once the JVM arg option is removed, we can remove the first condition
*/
if (XRayTransactionState.getServiceName() == null) {
String environmentNameOverrideValue = System.getenv(SegmentNamingStrategy.NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY);
String systemNameOverrideValue = System.getProperty(SegmentNamingStrategy.NAME_OVERRIDE_SYSTEM_PROPERTY_KEY);
if (StringValidator.isNotNullOrBlank(environmentNameOverrideValue)) {
XRayTransactionState.setServiceName(environmentNameOverrideValue);
} else if (StringValidator.isNotNullOrBlank(systemNameOverrideValue)) {
XRayTransactionState.setServiceName(systemNameOverrideValue);
} else {
XRayTransactionState.setServiceName(agentConfiguration.getServiceName());
}
}
// Plugins
// Do not add plugins in Lambda environment to improve performance & avoid irrelevant metadata
if (StringValidator.isNullOrBlank(System.getenv(LAMBDA_TASK_ROOT_KEY)) &&
agentConfiguration.arePluginsEnabled())
{
builder.withDefaultPlugins();
}
// Context missing
final ContextMissingStrategy contextMissing;
try {
contextMissing = ContextMissingStrategy.valueOf(agentConfiguration.getContextMissingStrategy().toUpperCase());
} catch (IllegalArgumentException e) {
throw new InvalidAgentConfigException("Invalid context missing strategy given in X-Ray Agent " +
"configuration file: " + agentConfiguration.getContextMissingStrategy());
}
switch (contextMissing) {
case LOG_ERROR:
builder.withContextMissingStrategy(new LogErrorContextMissingStrategy());
break;
case IGNORE_ERROR:
builder.withContextMissingStrategy(new IgnoreErrorContextMissingStrategy());
break;
default:
}
// Daemon address
DaemonConfiguration daemonConfiguration = new DaemonConfiguration();
try {
// SDK handles all validation & environment overrides
daemonConfiguration.setDaemonAddress(agentConfiguration.getDaemonAddress());
builder.withEmitter(new UDPEmitter(daemonConfiguration));
} catch (Exception e) {
throw new InvalidAgentConfigException("Invalid daemon address provided in X-Ray Agent configuration " +
"file: " + agentConfiguration.getDaemonAddress(), e);
}
// Sampling Rules manifest
URL samplingManifest = null;
if (agentConfiguration.getSamplingRulesManifest() != null) {
try {
samplingManifest = new File(agentConfiguration.getSamplingRulesManifest()).toURI().toURL();
} catch (MalformedURLException e) {
throw new InvalidAgentConfigException("Invalid sampling rules manifest location provided in X-Ray Agent " +
"configuration file: " + agentConfiguration.getSamplingRulesManifest(), e);
}
}
// Sampling strategy
final SamplingStrategy samplingStrategy;
try {
samplingStrategy = SamplingStrategy.valueOf(agentConfiguration.getSamplingStrategy().toUpperCase());
} catch (IllegalArgumentException e) {
throw new InvalidAgentConfigException("Invalid sampling strategy given in X-Ray Agent " +
"configuration file: " + agentConfiguration.getSamplingStrategy());
}
switch (samplingStrategy) {
case ALL:
builder.withSamplingStrategy(new AllSamplingStrategy());
break;
case NONE:
builder.withSamplingStrategy(new NoSamplingStrategy());
break;
case LOCAL:
builder.withSamplingStrategy(samplingManifest != null ?
new LocalizedSamplingStrategy(samplingManifest) :
new LocalizedSamplingStrategy());
break;
case CENTRAL:
builder.withSamplingStrategy(samplingManifest != null ?
new CentralizedSamplingStrategy(samplingManifest) :
new CentralizedSamplingStrategy());
break;
default:
}
// Trace ID Injection
if (agentConfiguration.isTraceIdInjection()) {
// TODO: Include the trace ID injection libraries in the agent JAR and use this reflective approach to
// only enable them if their corresponding logging libs are in the context classloader
List<SegmentListener> listeners = getTraceIdInjectorsReflectively(ClassLoader.getSystemClassLoader());
if (!listeners.isEmpty()) {
traceIdInjectionConfigured = true;
for (SegmentListener listener : listeners) {
builder.withSegmentListener(listener);
}
}
}
// Max stack trace length
if (agentConfiguration.getMaxStackTraceLength() >= 0) {
builder.withThrowableSerializationStrategy(
new DefaultThrowableSerializationStrategy(agentConfiguration.getMaxStackTraceLength()));
} else {
throw new InvalidAgentConfigException("Invalid max stack trace length given in X-Ray Agent " +
"configuration file: " + agentConfiguration.getMaxStackTraceLength());
}
// Streaming threshold
if (agentConfiguration.getStreamingThreshold() >= 0) {
builder.withStreamingStrategy(new DefaultStreamingStrategy(agentConfiguration.getStreamingThreshold()));
} else {
throw new InvalidAgentConfigException("Invalid streaming threshold given in X-Ray Agent " +
"configuration file: " + agentConfiguration.getStreamingThreshold());
}
// AWS Service handler manifest
if (agentConfiguration.getAwsServiceHandlerManifest() != null) {
int version = agentConfiguration.getAwsSdkVersion();
if (version != 1 && version != 2) {
throw new InvalidAgentConfigException("Invalid AWS SDK version given in X-Ray Agent configuration file: " + version);
} else {
this.awsSdkVersion = version;
try {
this.awsServiceHandlerManifest = new File(agentConfiguration.getAwsServiceHandlerManifest()).toURI().toURL();
} catch (MalformedURLException e) {
throw new InvalidAgentConfigException("Invalid AWS Service Handler Manifest location given in X-Ray Agent " +
"configuration file: " + agentConfiguration.getAwsServiceHandlerManifest(), e);
}
}
}
SegmentContextResolverChain segmentContextResolverChain = new SegmentContextResolverChain();
segmentContextResolverChain.addResolver(new LambdaSegmentContextResolver());
// Context resolution - use TransactionContext by default, or ThreadLocal if contextPropagation is disabled
if (agentConfiguration.isContextPropagation()) {
segmentContextResolverChain.addResolver(new XRayTransactionContextResolver());
} else {
segmentContextResolverChain.addResolver(new ThreadLocalSegmentContextResolver());
}
builder.withSegmentContextResolverChain(segmentContextResolverChain);
log.debug("Successfully configured the X-Ray Agent's recorder.");
AWSXRay.setGlobalRecorder(builder.build());
}
/**
* Attempts to enable trace ID injection via reflection. This can be called during runtime as opposed to agent
* startup in case required trace ID injection classes aren't available on the classpath during premain.
*
* @param recorder - the X-Ray Recorder to configure
*/
public void lazyLoadTraceIdInjection(AWSXRayRecorder recorder) {
// Fail fast if injection disabled or we've already tried to lazy load
if (!agentConfiguration.isTraceIdInjection() || traceIdInjectionConfigured) {
return;
}
traceIdInjectionConfigured = true;
// We must use the context class loader because the whole reason we're lazy loading the injection libraries
// is that they're only visible to the classloader used by the customer app
recorder.addAllSegmentListeners(getTraceIdInjectorsReflectively(Thread.currentThread().getContextClassLoader()));
}
private AgentConfiguration parseConfig(URL configFile) throws IOException {
Map<String, String> propertyMap = new HashMap<>();
JsonParser parser = factory.createParser(configFile);
parser.nextToken();
if (!parser.isExpectedStartObjectToken()) {
throw new InvalidAgentConfigException("X-Ray Agent configuration file is not valid JSON");
}
while (!parser.isClosed()) {
String field = parser.nextFieldName();
if (field == null) {
return new AgentConfiguration(propertyMap); // Hitting a null field implies end of JSON object
}
parser.nextToken();
propertyMap.put(field, parser.getValueAsString());
}
return new AgentConfiguration(propertyMap);
}
private List<SegmentListener> getTraceIdInjectorsReflectively(ClassLoader classLoader) {
final List<SegmentListener> listeners = new ArrayList<>();
final String prefix = agentConfiguration.getTraceIdInjectionPrefix();
log.debug("Prefix is: " + prefix);
for (String className : TRACE_ID_INJECTION_CLASSES) {
try {
Class<?> listenerClass = Class.forName(className, true, classLoader);
SegmentListener listener = (SegmentListener) listenerClass.getConstructor(String.class).newInstance(prefix);
listeners.add(listener);
log.debug("Enabled AWS X-Ray trace ID injection into logs using " + className);
} catch (InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException | ClassNotFoundException e) {
log.debug("Could not find trace ID injection class " + className + " with class loader " + classLoader.getClass().getSimpleName());
}
}
return listeners;
}
}
| 3,961 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/dispatcher/EventDispatcher.java | package com.amazonaws.xray.agent.runtime.dispatcher;
import com.amazonaws.xray.agent.runtime.handlers.XRayHandlerInterface;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import software.amazon.disco.agent.event.Event;
import java.util.HashMap;
import java.util.Map;
/**
* The dispatcher is the gateway between the listener and the handlers. It acts as the multiplexor
* that delegates events to a handler, based solely on its origin. The event dispatcher should be
* instantiated to represent the downstream or upstream dispatcher.
*/
public class EventDispatcher {
private static final Log log = LogFactory.getLog(EventDispatcher.class);
/**
* Map that holds a reference between the origin and its handler
*/
private Map<String, XRayHandlerInterface> originHandlerMap;
public EventDispatcher() {
originHandlerMap = new HashMap<>();
}
/**
* Add a handler for a given origin. This handler is executed when an event is dispatched to it.
* @param origin The event origin that corresponds to the handler
* @param handler The handler that is executed for the given event origin.
*/
public void addHandler(String origin, XRayHandlerInterface handler) {
originHandlerMap.put(origin, handler);
}
/**
* Helper method to acquire the appropriate handler given the event; the origin is extracted from
* this event to determine which handler to execute.
* @param event Incoming event to acquire the handler.
* @return The handler to execute, otherwise null if no handler exists for the event.
*/
private XRayHandlerInterface getHandler(Event event) {
String eventOrigin = event.getOrigin();
XRayHandlerInterface xrayHandler = originHandlerMap.get(eventOrigin);
if (xrayHandler == null && log.isDebugEnabled()) {
log.debug("Unable to retrieve a handler from event " + event.toString()
+ " and origin " + event.getOrigin());
}
return xrayHandler;
}
/**
* Dispatches the request event to its corresponding handler if one exists.
* If it doesn't, this method doesn't do anything.
* @param event The request event to dispatch to its underlying handler if one exists
*/
public void dispatchRequestEvent(Event event) {
XRayHandlerInterface xrayHandler = getHandler(event);
if (xrayHandler != null) {
xrayHandler.handleRequest(event);
}
}
/**
* Dispatches the response event to its corresponding handler if one exists.
* If it doesn't, this method doesn't do anything.
* @param event The response event to dispatch to its underlying handler if one exists
*/
public void dispatchResponseEvent(Event event) {
XRayHandlerInterface xrayHandler = getHandler(event);
if (xrayHandler != null) {
xrayHandler.handleResponse(event);
}
}
}
| 3,962 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/models/XRayTransactionContextResolver.java | package com.amazonaws.xray.agent.runtime.models;
import com.amazonaws.xray.contexts.SegmentContext;
import com.amazonaws.xray.contexts.SegmentContextResolver;
public class XRayTransactionContextResolver implements SegmentContextResolver {
@Override
public SegmentContext resolve() {
return new XRayTransactionContext();
}
} | 3,963 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/models/XRayTransactionContext.java | package com.amazonaws.xray.agent.runtime.models;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.contexts.SegmentContext;
import com.amazonaws.xray.entities.Entity;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.SubsegmentImpl;
import com.amazonaws.xray.exceptions.SegmentNotFoundException;
import com.amazonaws.xray.exceptions.SubsegmentNotFoundException;
import com.amazonaws.xray.listeners.SegmentListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.checkerframework.checker.nullness.qual.Nullable;
import software.amazon.disco.agent.concurrent.TransactionContext;
/**
* X-Ray-friendly context that utilizes the TransactionContext object to propagate across thread boundaries. This context
* is used by the global recorder to maintain segments and subsegments.
*/
public class XRayTransactionContext implements SegmentContext {
private static final String XRAY_ENTITY_KEY = "DiscoXRayEntity";
private static final Log log = LogFactory.getLog(XRayTransactionContext.class);
// Transaction Context approach.
@Nullable
public Entity getTraceEntity() {
return (Entity) TransactionContext.getMetadata(XRAY_ENTITY_KEY);
}
public void setTraceEntity(@Nullable Entity entity) {
if (entity != null && entity.getCreator() != null) {
for (SegmentListener l : entity.getCreator().getSegmentListeners()) {
if (l != null) {
l.onSetEntity((Entity) TransactionContext.getMetadata(XRAY_ENTITY_KEY), entity);
}
}
}
TransactionContext.putMetadata(XRAY_ENTITY_KEY, entity);
}
public void clearTraceEntity() {
Entity oldEntity = (Entity) TransactionContext.getMetadata(XRAY_ENTITY_KEY);
if (oldEntity != null && oldEntity.getCreator() != null) {
for (SegmentListener l : oldEntity.getCreator().getSegmentListeners()) {
if (l != null) {
l.onClearEntity(oldEntity);
}
}
}
TransactionContext.putMetadata(XRAY_ENTITY_KEY, null);
}
@Override
public Subsegment beginSubsegment(AWSXRayRecorder recorder, String name) {
Entity current = getTraceEntity();
if (null == current) {
recorder.getContextMissingStrategy().contextMissing("Failed to begin subsegment named '" + name + "': segment cannot be found.", SegmentNotFoundException.class);
return Subsegment.noOp(recorder);
}
if (log.isDebugEnabled()) {
log.debug("Beginning subsegment named: " + name);
}
Segment parentSegment = getTraceEntity().getParentSegment();
Subsegment subsegment = new SubsegmentImpl(recorder, name, parentSegment);
subsegment.setParent(current);
current.addSubsegment(subsegment);
setTraceEntity(subsegment);
return subsegment;
}
@Override
public void endSubsegment(AWSXRayRecorder recorder) {
Entity current = getTraceEntity();
if (current instanceof Subsegment) {
if (log.isDebugEnabled()) {
log.debug("Ending subsegment named: " + current.getName());
}
Subsegment currentSubsegment = (Subsegment) current;
if (currentSubsegment.end()) {
recorder.sendSegment(currentSubsegment.getParentSegment());
} else {
if (recorder.getStreamingStrategy().requiresStreaming(currentSubsegment.getParentSegment())) {
recorder.getStreamingStrategy().streamSome(currentSubsegment.getParentSegment(), recorder.getEmitter());
}
setTraceEntity(current.getParent());
}
} else {
recorder.getContextMissingStrategy().contextMissing("Failed to end subsegment: subsegment cannot be found.", SubsegmentNotFoundException.class);
}
}
}
| 3,964 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/models/XRayTransactionState.java | package com.amazonaws.xray.agent.runtime.models;
import com.blogspot.mydailyjava.weaklockfree.WeakConcurrentMap;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.sql.PreparedStatement;
/**
* Contains state information for each logical request/response transaction event.
*
* Events that are captured should capture the relevant information and store it here.
*/
public class XRayTransactionState {
private String host;
private String url;
private String userAgent;
private String clientIP;
private String method;
private String serviceType; // Type of AWS resource running application.
private String traceHeader;
private String origin;
private static String serviceName;
private static final WeakConcurrentMap<PreparedStatement, String> preparedStatementMap
= new WeakConcurrentMap.WithInlinedExpunction<>();
public XRayTransactionState withHost(String host) {
this.host = host;
return this;
}
public XRayTransactionState withUrl(String url) {
this.url = url;
return this;
}
public XRayTransactionState withUserAgent(String userAgent) {
this.userAgent = userAgent;
return this;
}
public XRayTransactionState withClientIP(String clientIP) {
this.clientIP = clientIP;
return this;
}
public XRayTransactionState withMethod(String method) {
this.method = method;
return this;
}
public XRayTransactionState withServiceType(String serviceType) {
this.serviceType = serviceType;
return this;
}
public XRayTransactionState withTraceheaderString(@Nullable String traceHeaderString) {
this.traceHeader = traceHeaderString;
return this;
}
public XRayTransactionState withOrigin(@Nullable String origin) {
this.origin = origin;
return this;
}
public String getHost() {
return this.host;
}
public String getURL() {
return this.url;
}
public String getUserAgent() {
return this.userAgent;
}
public String getClientIP() {
return this.clientIP;
}
public String getMethod() {
return this.method;
}
public String getServiceType() {
return this.serviceType;
}
@Nullable
public String getTraceHeader() {
return this.traceHeader;
}
@Nullable
public String getOrigin() {
return this.origin;
}
public static void setServiceName(String inServiceName) {
serviceName = inServiceName;
}
public static String getServiceName() {
return serviceName;
}
public static void putPreparedQuery(PreparedStatement ps, String query) {
preparedStatementMap.put(ps, query);
}
public static String getPreparedQuery(PreparedStatement ps) {
return preparedStatementMap.get(ps);
}
}
| 3,965 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/listeners/XRayListener.java | package com.amazonaws.xray.agent.runtime.listeners;
import com.amazonaws.xray.agent.runtime.dispatcher.EventDispatcher;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import software.amazon.disco.agent.event.Event;
import software.amazon.disco.agent.event.HttpServletNetworkRequestEvent;
import software.amazon.disco.agent.event.HttpServletNetworkResponseEvent;
import software.amazon.disco.agent.event.Listener;
import software.amazon.disco.agent.event.ServiceEvent;
import software.amazon.disco.agent.event.ServiceRequestEvent;
import software.amazon.disco.agent.event.ServiceResponseEvent;
public class XRayListener implements Listener {
private static final Log log = LogFactory.getLog(XRayListener.class);
private final EventDispatcher upstreamEventDispatcher;
private final EventDispatcher downstreamEventDispatcher;
public XRayListener(EventDispatcher upstreamEventDispatcher, EventDispatcher downstreamEventDispatcher) {
this.upstreamEventDispatcher = upstreamEventDispatcher;
this.downstreamEventDispatcher = downstreamEventDispatcher;
}
@Override
public int getPriority() {
return 0;
}
@Override
public void listen(Event event) {
try {
EventDispatcher dispatcher = isEventDownstream(event) ? downstreamEventDispatcher : upstreamEventDispatcher;
if (event instanceof ServiceRequestEvent || event instanceof HttpServletNetworkRequestEvent) {
dispatcher.dispatchRequestEvent(event);
} else if (event instanceof ServiceResponseEvent || event instanceof HttpServletNetworkResponseEvent) {
dispatcher.dispatchResponseEvent(event);
} else {
// Other events we don't care about so return.
return;
}
} catch (Exception e) {
// We dont want to propagate any exceptions back to the bus nor the application code, so we
// just log it and continue.
log.error("The X-Ray Agent had encountered an unexpected exception for the following event: "
+ event.toString(), e);
}
}
/**
* Use the downstream or upstream event dispatcher depending on the type of event.
*
* Upstream dispatchers are invoked as a result of an incoming request in a service. They generally run handlers
* that generate segments, populate them with request metadata, and end them.
*
* Downstream dispatchers usually deal with events relating to client-sided, send requests and run handlers
* that generate subsegments, populate them with metadata, and then end the subsegments.
*/
private boolean isEventDownstream(Event e) {
if (e instanceof ServiceEvent) {
ServiceEvent serviceEvent = (ServiceEvent) e;
return serviceEvent.getType() == ServiceEvent.Type.DOWNSTREAM;
}
return false;
}
}
| 3,966 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/listeners/XRayListenerFactory.java | package com.amazonaws.xray.agent.runtime.listeners;
import com.amazonaws.xray.agent.runtime.config.XRaySDKConfiguration;
import com.amazonaws.xray.agent.runtime.dispatcher.EventDispatcher;
import com.amazonaws.xray.agent.runtime.handlers.downstream.AWSHandler;
import com.amazonaws.xray.agent.runtime.handlers.downstream.AWSV2Handler;
import com.amazonaws.xray.agent.runtime.handlers.downstream.HttpClientHandler;
import com.amazonaws.xray.agent.runtime.handlers.downstream.SqlHandler;
import com.amazonaws.xray.agent.runtime.handlers.downstream.SqlPrepareHandler;
import com.amazonaws.xray.agent.runtime.handlers.upstream.ServletHandler;
import software.amazon.disco.agent.event.Listener;
import java.net.URL;
/**
* Factory class that produces an X-Ray listener with upstream and downstream dispatchers to intercept relevant
* events on the Disco event bus. It is important to keep this class minimal since we add different handlers
* to the listener based on the environment it's consumed in.
*/
public class XRayListenerFactory implements ListenerFactory {
private static final String AWS_ORIGIN = "AWSv1";
private static final String AWS_V2_ORIGIN = "AWSv2";
private static final String APACHE_HTTP_CLIENT_ORIGIN = "ApacheHttpClient";
private static final String HTTP_SERVLET_ORIGIN = "httpServlet";
private static final String SQL_ORIGIN = "SQL";
private static final String SQL_PREPARE_ORIGIN = "SqlPrepare";
private static URL manifest;
private static int configVersion;
/**
* Creates a Disco Event Bus listener with upstream and downstream event dispatchers that have handlers
* for each event type that the X-Ray Agent supports.
*
* @return An X-Ray Agent listener
*/
@Override
public Listener generateListener() {
manifest = XRaySDKConfiguration.getInstance().getAwsServiceHandlerManifest();
configVersion = XRaySDKConfiguration.getInstance().getAwsSdkVersion();
EventDispatcher upstreamEventDispatcher = new EventDispatcher();
if (XRaySDKConfiguration.getInstance().isTraceIncomingRequests()) {
upstreamEventDispatcher.addHandler(HTTP_SERVLET_ORIGIN, new ServletHandler());
}
EventDispatcher downstreamEventDispatcher = new EventDispatcher();
downstreamEventDispatcher.addHandler(APACHE_HTTP_CLIENT_ORIGIN, new HttpClientHandler());
downstreamEventDispatcher.addHandler(SQL_ORIGIN, new SqlHandler());
downstreamEventDispatcher.addHandler(SQL_PREPARE_ORIGIN, new SqlPrepareHandler());
if (configVersion == 1 && manifest != null) {
downstreamEventDispatcher.addHandler(AWS_ORIGIN, new AWSHandler(manifest));
} else {
downstreamEventDispatcher.addHandler(AWS_ORIGIN, new AWSHandler());
}
if (configVersion == 2 && manifest != null) {
downstreamEventDispatcher.addHandler(AWS_V2_ORIGIN, new AWSV2Handler(manifest));
} else {
downstreamEventDispatcher.addHandler(AWS_V2_ORIGIN, new AWSV2Handler());
}
return new XRayListener(upstreamEventDispatcher, downstreamEventDispatcher);
}
}
| 3,967 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/listeners/ListenerFactory.java | package com.amazonaws.xray.agent.runtime.listeners;
import software.amazon.disco.agent.event.Listener;
/**
* Factory interface that produces a listener that can be used by Disco Agents to intercept relevant
* events on the Disco event bus.
*/
public interface ListenerFactory {
/**
* Creates a Disco Event Bus listener but does not attach it to the event bus.
*
* @return the created Disco listener
*/
Listener generateListener();
}
| 3,968 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/handlers/XRayHandler.java | package com.amazonaws.xray.agent.runtime.handlers;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.agent.runtime.models.XRayTransactionState;
import com.amazonaws.xray.entities.Entity;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.entities.TraceID;
import com.amazonaws.xray.strategy.sampling.SamplingRequest;
import com.amazonaws.xray.strategy.sampling.SamplingResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.checkerframework.checker.nullness.qual.Nullable;
import software.amazon.disco.agent.concurrent.TransactionContext;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* Base class for an X-Ray handler which contains wrapper methods for managing entities with the X-Ray recorder to
* provide a layer of protection against the X-Ray SDK Dependency
*/
public abstract class XRayHandler implements XRayHandlerInterface {
private static final Log log = LogFactory.getLog(XRayHandler.class);
/**
* DiSCo TransactionContext key for XRay State data.
*/
private static final String XRAY_STATE = "DiSCoXRayState";
/**
* AWS key to get X-Ray map
*/
private static final String XRAY_AWS_KEY = "xray";
/**
* Auto instrumentation flag for the xray AWS map.
*/
private static final String AUTO_INSTRUMENTATION_KEY = "auto_instrumentation";
/**
* Trace Header key for X-Ray upstream propagation.
*/
public static final String HEADER_KEY = TraceHeader.HEADER_KEY;
/**
* Retrieve the current transaction state from the TransactionContext if it exists. Otherwise,
* create a new one, store it in the TransactionContext, and return it.
* @return the current transaction's transaction state. Create one if none exists.
*/
protected XRayTransactionState getTransactionState() {
XRayTransactionState transactionState = (XRayTransactionState) TransactionContext.getMetadata(XRAY_STATE);
if (transactionState == null) {
transactionState = new XRayTransactionState();
TransactionContext.putMetadata(XRAY_STATE, transactionState);
}
return transactionState;
}
/**
* Creates a segment using trace header information.
* @param segmentName - The segment name to name the segment.
* @param traceID - The segment's trace ID.
* @param parentID - The parent ID of this segment.
* @return the new segment
*/
protected Segment beginSegment(String segmentName, @Nullable TraceID traceID, @Nullable String parentID) {
Segment segment;
if (traceID == null || parentID == null) {
segment = AWSXRay.beginSegment(segmentName);
} else {
segment = AWSXRay.beginSegment(segmentName, traceID, parentID);
}
Map<String, Object> awsMap = segment.getAws();
if (awsMap == null) {
// If this is null, the global recorder wasn't properly initialized. Just ignore putting in the version
// altogether, log this, and continue along.
log.error("Unable to retrieve AWS map to set the auto instrumentation flag.");
return segment;
}
Map<String, Object> xrayMap = (Map<String, Object>) awsMap.get(XRAY_AWS_KEY);
if (xrayMap != null) {
Map<String, Object> agentMap = new HashMap<>(xrayMap);
agentMap.put(AUTO_INSTRUMENTATION_KEY, true);
segment.putAws(XRAY_AWS_KEY, Collections.unmodifiableMap(agentMap));
} else {
log.debug("Unable to retrieve X-Ray attribute map from segment.");
}
return segment;
}
protected AWSXRayRecorder getGlobalRecorder() {
return AWSXRay.getGlobalRecorder();
}
protected Segment beginSegment(String segmentName, TraceHeader traceHeader) {
TraceID traceId = traceHeader.getRootTraceId();
String parentId = traceHeader.getParentId();
return beginSegment(segmentName, traceId, parentId);
}
protected Segment getSegment() {
return AWSXRay.getCurrentSegment();
}
protected void endSegment() {
AWSXRay.endSegment();
}
protected Subsegment beginSubsegment(String subsegmentName) {
return AWSXRay.beginSubsegment(subsegmentName);
}
protected Subsegment getSubsegment() {
return AWSXRay.getCurrentSubsegment();
}
protected Optional<Subsegment> getSubsegmentOptional() {
return AWSXRay.getCurrentSubsegmentOptional();
}
protected void endSubsegment() {
AWSXRay.endSubsegment();
}
/**
* Calculate the sampling decision from the transaction state. The transaction state should contain
* all the URL, method, host, origin, and service name information.
* @param transactionState The current state of the X-Ray transaction. Includes the trace header from an upstream
* call if applicable.
* @return True if we should sample, false otherwise.
*/
protected boolean getSamplingDecision(XRayTransactionState transactionState) {
// If the trace header string is null, then this is the origin call.
TraceHeader traceHeader = TraceHeader.fromString(transactionState.getTraceHeader());
TraceHeader.SampleDecision sampleDecision = traceHeader.getSampled();
if (TraceHeader.SampleDecision.SAMPLED.equals(sampleDecision)) {
log.debug("Received SAMPLED decision from upstream X-Ray trace header");
return true;
} else if (TraceHeader.SampleDecision.NOT_SAMPLED.equals(sampleDecision)) {
log.debug("Received NOT SAMPLED decision from upstream X-Ray trace header");
return false;
}
// No sampling decision made on the upstream. So use the in-house rules.
SamplingRequest samplingRequest = new SamplingRequest(
XRayTransactionState.getServiceName(),
transactionState.getHost(),
transactionState.getURL(),
transactionState.getMethod(),
transactionState.getServiceType());
SamplingResponse samplingResponse = AWSXRay.getGlobalRecorder().getSamplingStrategy().shouldTrace(samplingRequest);
return samplingResponse.isSampled();
}
/**
* Builds a trace header object out of the input entity.
* Typically used for propagating trace information downstream.
* @param entity Either the segment or subsegment.
* Passing in a subsegment will get the information from the parent segment
* @return The trace header that represents the entity.
*/
protected TraceHeader buildTraceHeader(Entity entity) {
boolean isSampled;
TraceID traceID;
// Generate the trace header based on the segment itself.
if (entity instanceof Segment) {
Segment segment = (Segment) entity;
isSampled = segment.isSampled();
traceID = segment.getTraceId();
} else {
// Generate the trace header based on the parent of the subsegment.
Subsegment subsegment = (Subsegment) entity;
isSampled = subsegment.getParentSegment().isSampled();
traceID = subsegment.getParentSegment().getTraceId();
}
TraceHeader traceHeader = new TraceHeader(traceID,
isSampled ? entity.getId() : null,
isSampled ? TraceHeader.SampleDecision.SAMPLED : TraceHeader.SampleDecision.NOT_SAMPLED);
return traceHeader;
}
}
| 3,969 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/handlers/XRayHandlerInterface.java | package com.amazonaws.xray.agent.runtime.handlers;
import software.amazon.disco.agent.event.Event;
public interface XRayHandlerInterface {
/**
* Handle the incoming request event. The event should be type checked depending on the type of event
* the handler is processing. There isn't a common interface yet that relates request/responses in DiSCo,
* so type checking and handling should be done on a per-handler case.
* @param event The request event dispatched from the dispatcher.
*/
void handleRequest(Event event);
/**
* Handle the incoming response event. The event should be type checked depending on the type of event
* the handler is processing. There isn't a common interface yet that relates request/responses in DiSCo,
* so type checking and handling should be done on a per-handler case.
*
* Errors resulting from calls made within the interception is passed to the response event. These should be
* taken care of in this method.
* @param event The response event dispatched from the dispatcher.
*/
void handleResponse(Event event);
}
| 3,970 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/handlers/downstream/SqlPrepareHandler.java | package com.amazonaws.xray.agent.runtime.handlers.downstream;
import com.amazonaws.xray.agent.runtime.handlers.XRayHandler;
import com.amazonaws.xray.agent.runtime.models.XRayTransactionState;
import software.amazon.disco.agent.event.Event;
import software.amazon.disco.agent.event.ServiceDownstreamResponseEvent;
import java.sql.PreparedStatement;
/**
* This handler processes DiSCo events with origin "SqlPrepare." Such events are emitted when preparing
* a statement or call to a remote SQL server using the {@code connection.prepareStatement()} or
* {@code connection.prepareCall()} JDBC methods. We do NOT generate X-Ray entities here, we just store metadata
* for later use.
*/
public class SqlPrepareHandler extends XRayHandler {
/**
* No-op because we can only meaningfully record the metadata when we have a reference to the returned statement.
*
* @param event The request event dispatched from the dispatcher.
*/
@Override
public void handleRequest(Event event) {
}
/**
* Stores the captured query string in a static map for later use by the SQL execution handler.
*
* @param event The response event dispatched from the dispatcher.
*/
@Override
public void handleResponse(Event event) {
ServiceDownstreamResponseEvent responseEvent = (ServiceDownstreamResponseEvent) event;
if (responseEvent != null &&
responseEvent.getOperation() != null &&
responseEvent.getResponse() instanceof PreparedStatement)
{
XRayTransactionState
.putPreparedQuery((PreparedStatement) responseEvent.getResponse(), responseEvent.getOperation());
}
}
}
| 3,971 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/handlers/downstream/HttpClientHandler.java | package com.amazonaws.xray.agent.runtime.handlers.downstream;
import com.amazonaws.xray.agent.runtime.handlers.XRayHandler;
import com.amazonaws.xray.entities.Namespace;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.TraceHeader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import software.amazon.disco.agent.event.Event;
import software.amazon.disco.agent.event.HttpServiceDownstreamRequestEvent;
import software.amazon.disco.agent.event.HttpServiceDownstreamResponseEvent;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class HttpClientHandler extends XRayHandler {
private static final Log log = LogFactory.getLog(HttpClientHandler.class);
// Request Fields
private static final String URL_KEY = "url";
private static final String METHOD_KEY = "method";
private static final String HTTP_REQUEST_KEY = "request";
// Response Fields
private static final String STATUS_CODE_KEY = "status";
private static final String CONTENT_LENGTH_KEY = "content_length";
private static final String HTTP_RESPONSE_KEY = "response";
@Override
public void handleRequest(Event event) {
HttpServiceDownstreamRequestEvent requestEvent = (HttpServiceDownstreamRequestEvent) event;
URI uri = getUriFromEvent(requestEvent);
if (isWithinAWSCall() || isXRaySamplingCall(uri) || isXRayPluginCall(uri)) {
return;
}
String hostName = uri.getHost();
if (hostName == null) {
// If we fail to acquire the hostname, we will use the entire URL/service name instead.
// This is an indication that there's an issue with the request configuration so we
// use the entire URI so we can provide a subsegment with useful information.
hostName = requestEvent.getService();
}
Subsegment subsegment = beginSubsegment(hostName);
// Adds http metadata and stores the Trace Header into the request header.
if (subsegment != null) {
addRequestInformation(subsegment, requestEvent, uri);
}
}
/**
* Obtains the downstream call's Uri from the event. Fallsback to obtaining it from the
* HttpRequest object otherwise.
* @param requestEvent - The request event to get the Uri from
* @return The full URI of the downstream call.
*/
private URI getUriFromEvent(HttpServiceDownstreamRequestEvent requestEvent) {
URI uri;
try {
uri = new URI(requestEvent.getUri());
} catch (URISyntaxException e) {
log.error("HttpClientHandler: Unable to generate URI from request event service; using request object's URI: "
+ requestEvent.getService());
uri = null;
}
return uri;
}
private static void addRequestInformation(Subsegment subsegment, HttpServiceDownstreamRequestEvent requestEvent, URI uri) {
subsegment.setNamespace(Namespace.REMOTE.toString());
Segment parentSegment = subsegment.getParentSegment();
String url = uri.toString();
TraceHeader header = new TraceHeader(parentSegment.getTraceId(),
parentSegment.isSampled() ? subsegment.getId() : null,
parentSegment.isSampled() ? TraceHeader.SampleDecision.SAMPLED : TraceHeader.SampleDecision.NOT_SAMPLED);
requestEvent.replaceHeader(TraceHeader.HEADER_KEY, header.toString());
Map<String, Object> requestInformation = new HashMap<>();
requestInformation.put(URL_KEY, url);
requestInformation.put(METHOD_KEY, requestEvent.getMethod());
subsegment.putHttp(HTTP_REQUEST_KEY, requestInformation);
}
@Override
public void handleResponse(Event event) {
HttpServiceDownstreamResponseEvent responseEvent = (HttpServiceDownstreamResponseEvent) event;
// Check again if this is an X-Ray sampling call or within an AWS call.
// By this time, the request handler would've executed the same logic and didn't generate a subsegment.
HttpServiceDownstreamRequestEvent requestEvent = (HttpServiceDownstreamRequestEvent) responseEvent.getRequest();
URI uri = getUriFromEvent(requestEvent);
if (isWithinAWSCall() || isXRaySamplingCall(uri) || isXRayPluginCall(uri)) {
return;
}
Optional<Subsegment> subsegmentOptional = getSubsegmentOptional();
if (subsegmentOptional.isPresent()) {
addResponseInformation(subsegmentOptional.get(), responseEvent);
endSubsegment();
}
}
private static void addResponseInformation(Subsegment subsegment, HttpServiceDownstreamResponseEvent responseEvent) {
Map<String, Object> responseInformation = new HashMap<>();
// Add exceptions
if (responseEvent.getThrown() != null) {
Throwable exception = responseEvent.getThrown();
subsegment.addException(exception);
}
int responseCode = responseEvent.getStatusCode();
switch (responseCode/100) {
case 4:
subsegment.setError(true);
if (429 == responseCode) {
subsegment.setThrottle(true);
}
break;
case 5:
subsegment.setFault(true);
break;
}
if (responseCode >= 0) {
responseInformation.put(STATUS_CODE_KEY, responseCode);
}
long contentLength = responseEvent.getContentLength();
if (contentLength >= 0) {
// If content length is -1, then the information isn't provided in the web request.
responseInformation.put(CONTENT_LENGTH_KEY, contentLength);
}
if (responseInformation.size() > 0) {
subsegment.putHttp(HTTP_RESPONSE_KEY, responseInformation);
}
}
/** Check if the current call is within an AWS SDK call.
* We can validate this by seeing if the parent subsegment is an AWS one and is valid.
*
* @return true if we are currently processing an AWS SDK request
*/
private boolean isWithinAWSCall() {
Optional<Subsegment> subsegmentOptional = getSubsegmentOptional();
if (!subsegmentOptional.isPresent()) {
// If the subsegment doesn't exist, this must either be a vanilla http client call
// or an x-ray sample call
return false;
}
Subsegment currentSubsegment = subsegmentOptional.get();
String namespace = currentSubsegment.getNamespace() == null ? "" : currentSubsegment.getNamespace();
return namespace.equals(Namespace.AWS.toString()) && currentSubsegment.isInProgress();
}
/**
* Checks if the current call is an X-Ray sampling call
*
* @param uri URI of intercepted call
* @return true if this is a request made by X-Ray sampling
*/
private boolean isXRaySamplingCall(URI uri) {
String uriPath = uri.getPath();
return uriPath != null && (uriPath.equals("/GetSamplingRules") || uriPath.equals("/SamplingTargets"));
}
/**
* Checks if the current request is the one made by EKS plugin to Kubernetes endpoint
*
* @param uri URI of intercepted call
* @return true if this is a request made by EKS plugin
*/
private boolean isXRayPluginCall(URI uri) {
String uriPath = uri.getPath();
return uriPath != null && uriPath.equals("/api/v1/namespaces/amazon-cloudwatch/configmaps/cluster-info");
}
}
| 3,972 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/handlers/downstream/AWSV2Handler.java | package com.amazonaws.xray.agent.runtime.handlers.downstream;
import com.amazonaws.xray.agent.runtime.handlers.XRayHandler;
import com.amazonaws.xray.entities.EntityDataKeys;
import com.amazonaws.xray.entities.EntityHeaderKeys;
import com.amazonaws.xray.entities.Namespace;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.handlers.config.AWSOperationHandler;
import com.amazonaws.xray.handlers.config.AWSOperationHandlerManifest;
import com.amazonaws.xray.handlers.config.AWSServiceHandlerManifest;
import com.amazonaws.xray.utils.StringTransform;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import software.amazon.disco.agent.event.AwsServiceDownstreamRequestEvent;
import software.amazon.disco.agent.event.AwsServiceDownstreamResponseEvent;
import software.amazon.disco.agent.event.Event;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Much of the code is adopted from
* https://github.com/aws/aws-xray-sdk-java/blob/master/aws-xray-recorder-sdk-aws-sdk-v2/src/main/java/com/amazonaws/xray/interceptors/TracingInterceptor.java#L281
*
* The long term would be to expose APIs in the SDK package so that we can take bits of it to perform the
* instrumentation. Since this is an event-based architecture, we can't quite re-use the same beforeExecution
* calls.
*/
public class AWSV2Handler extends XRayHandler {
private static final Log log = LogFactory.getLog(AWSV2Handler.class);
private static final ObjectMapper mapper = new ObjectMapper()
.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
private static final URL DEFAULT_OPERATION_PARAMETER_WHITELIST = AWSV2Handler.class.getResource("/com/amazonaws/xray/interceptors/DefaultOperationParameterWhitelist.json");
// Response Fields
private static final String STATUS_CODE_KEY = "status";
private static final String CONTENT_LENGTH_KEY = "content_length";
private static final String HTTP_RESPONSE_KEY = "response";
private static AWSServiceHandlerManifest awsServiceHandlerManifest;
public AWSV2Handler() {
initInterceptorManifest(DEFAULT_OPERATION_PARAMETER_WHITELIST);
}
public AWSV2Handler(URL serviceHandlerManifest) {
initInterceptorManifest(serviceHandlerManifest);
}
@Override
public void handleRequest(Event event) {
AwsServiceDownstreamRequestEvent requestEvent = (AwsServiceDownstreamRequestEvent) event;
String serviceName = requestEvent.getService();
String operationName = requestEvent.getOperation();
String region = requestEvent.getRegion();
// Avoid throwing if name isn't present. HTTP interceptor will pick this up instead
if (serviceName == null) {
return;
}
// Begin subsegment
Subsegment subsegment = beginSubsegment(serviceName);
subsegment.setNamespace(Namespace.AWS.toString());
subsegment.putAws(EntityDataKeys.AWS.OPERATION_KEY, operationName);
subsegment.putAws(EntityDataKeys.AWS.REGION_KEY, region);
// Trace propagation
TraceHeader traceHeader = buildTraceHeader(subsegment);
requestEvent.replaceHeader(TraceHeader.HEADER_KEY, traceHeader.toString());
Map<String, Object> parameterMap = extractRequestParameters(requestEvent);
subsegment.putAllAws(parameterMap);
}
/**
* Extract the Request Parameters from the Aws Request Event. This is based on what's been whitelisted in
* the operations whitelist JSON file to retrieve specific fields so that we can fetch for example
* TableName, Count, etc from the Sdk request.
* @param requestEvent The request event to retrieve the the field values from.
* @return A mapping of the snake cased name of the field to the actual field value.
*/
private HashMap<String, Object> extractRequestParameters(AwsServiceDownstreamRequestEvent requestEvent) {
HashMap<String, Object> parameters = new HashMap<>();
AWSOperationHandler operationHandler = getOperationHandler(requestEvent.getService(), requestEvent.getOperation());
if (operationHandler == null) {
return parameters;
}
if (operationHandler.getRequestParameters() != null) {
operationHandler.getRequestParameters().forEach((parameterName) -> {
Optional<Object> parameterValue = (Optional) requestEvent.getValueForField(parameterName, Object.class);
parameterValue.ifPresent(o -> parameters.put(StringTransform.toSnakeCase(parameterName), o));
});
}
if (operationHandler.getRequestDescriptors() != null) {
operationHandler.getRequestDescriptors().forEach((key, descriptor) -> {
if (descriptor.isMap() && descriptor.shouldGetKeys()) {
Optional<Map> parameterValue = (Optional<Map>) requestEvent.getValueForField(key, Map.class);
if (parameterValue.isPresent()) {
String renameTo = descriptor.getRenameTo() != null ? descriptor.getRenameTo() : key;
parameters.put(StringTransform.toSnakeCase(renameTo), parameterValue.get().keySet());
}
} else if (descriptor.isList() && descriptor.shouldGetCount()) {
Optional<List> parameterValue = (Optional<List>)requestEvent.getValueForField(key, List.class);
if (parameterValue.isPresent()) {
String renameTo = descriptor.getRenameTo() != null ? descriptor.getRenameTo() : key;
parameters.put(StringTransform.toSnakeCase(renameTo), parameterValue.get().size());
}
}
});
}
return parameters;
}
/**
* Extract the Response Parameters from the Aws Response Event. This is based on what's been whitelisted in
* the operations whitelist JSON file to retrieve specific fields so that we can fetch for example
* TableName, Count, etc from the Sdk request.
* @param responseEvent The request event to retrieve the the field values from.
* @return A mapping of the snake cased name of the field to the actual field value.
*/
private HashMap<String, Object> extractResponseParameters(AwsServiceDownstreamResponseEvent responseEvent) {
// TODO Similar to extract Request Parameters. Need to refactor common functionality
HashMap<String, Object> parameters = new HashMap<>();
AWSOperationHandler operationHandler = getOperationHandler(responseEvent.getService(), responseEvent.getOperation());
if (operationHandler == null) {
return parameters;
}
if (operationHandler.getResponseParameters() != null) {
operationHandler.getResponseParameters().forEach((parameterName) -> {
Optional<Object> parameterValue = (Optional) responseEvent.getValueForField(parameterName, Object.class);
parameterValue.ifPresent(o -> parameters.put(StringTransform.toSnakeCase(parameterName), o));
});
}
if (operationHandler.getResponseDescriptors() != null) {
operationHandler.getResponseDescriptors().forEach((key, descriptor) -> {
if (descriptor.isMap() && descriptor.shouldGetKeys()) {
Optional<Map> parameterValue = (Optional<Map>) responseEvent.getValueForField(key, Map.class);
if (parameterValue.isPresent()) {
String renameTo = descriptor.getRenameTo() != null ? descriptor.getRenameTo() : key;
parameters.put(StringTransform.toSnakeCase(renameTo), parameterValue.get().keySet());
}
} else if (descriptor.isList() && descriptor.shouldGetCount()) {
Optional<List> parameterValue = (Optional<List>) responseEvent.getValueForField(key, List.class);
if (parameterValue.isPresent()) {
String renameTo = descriptor.getRenameTo() != null ? descriptor.getRenameTo() : key;
parameters.put(StringTransform.toSnakeCase(renameTo), parameterValue.get().size());
}
}
});
}
return parameters;
}
/**
* Set the cause in the subegment to remote if the throwable is an exception from the Sdk Exception object.
* @param subsegment The subsegment which contains throwables
* @param exception The SdkException that we want to set the cause to remote in the subsegment
*/
private void setRemoteForException(Subsegment subsegment, Throwable exception) {
subsegment.getCause().getExceptions().forEach((e) -> {
if (e.getThrowable() == exception) {
e.setRemote(true);
}
});
}
@Override
public void handleResponse(Event event) {
AwsServiceDownstreamResponseEvent responseEvent = (AwsServiceDownstreamResponseEvent) event;
Subsegment subsegment = getSubsegmentOptional().orElse(null);
if (subsegment == null) {
return;
}
Map<String, Object> responseInformation = new HashMap<>();
// Retrieve the response parameters such as the table name, table size, etc.
Map<String, Object> parameterMap = extractResponseParameters(responseEvent);
subsegment.putAllAws(parameterMap);
// Detect throwable for the downstream call.
Throwable exception = responseEvent.getThrown();
if (exception != null && exception.getMessage() != null) {
subsegment.addException(exception);
subsegment.getCause().setMessage(exception.getMessage());
setRemoteForException(subsegment, exception);
}
// Store retry count
subsegment.putAws(EntityDataKeys.AWS.RETRIES_KEY, responseEvent.getRetryCount());
// Get status code an add it to the response map.
// TODO unify this in the XRayHandler superclass.
int responseCode = responseEvent.getStatusCode();
switch (responseCode/100) {
case 4:
subsegment.setError(true);
subsegment.setFault(false);
if (429 == responseCode) {
subsegment.setThrottle(true);
}
break;
case 5:
subsegment.setError(false);
subsegment.setFault(true);
break;
}
if (responseCode >= 0) {
responseInformation.put(STATUS_CODE_KEY, responseCode);
}
// Obtain the content length from the header map and store it in the subsegment
Map<String, List<String>> headerMap = responseEvent.getHeaderMap();
List<String> contentLengthList = headerMap.get(EntityHeaderKeys.HTTP.CONTENT_LENGTH_HEADER);
if (contentLengthList != null && contentLengthList.size() > 0) {
long contentLength = Long.parseLong(contentLengthList.get(0));
responseInformation.put(CONTENT_LENGTH_KEY, contentLength);
}
if (responseInformation.size() > 0) {
subsegment.putHttp(HTTP_RESPONSE_KEY, responseInformation);
}
// Store request ID
String requestId = responseEvent.getRequestId();
if (requestId != null) {
subsegment.putAws(EntityDataKeys.AWS.REQUEST_ID_KEY, requestId);
}
// Store extended ID
String extendedRequestId = extractExtendedRequestIdFromHeaderMap(responseEvent.getHeaderMap());
if (extendedRequestId != null) {
subsegment.putAws(EntityDataKeys.AWS.EXTENDED_REQUEST_ID_KEY, extendedRequestId);
}
endSubsegment();
}
/**
* Extracts the extended Request Id from the given header map. This header map should generally
* be retrieved from the response events.
* @param headers The header map that may contain the extended request Id
* @return The request Id if it exists, null otherwise.
*/
private String extractExtendedRequestIdFromHeaderMap(Map<String, List<String>> headers) {
return headers.containsKey(EntityHeaderKeys.AWS.EXTENDED_REQUEST_ID_HEADER) ?
headers.get(EntityHeaderKeys.AWS.EXTENDED_REQUEST_ID_HEADER).get(0) : null;
}
/**
* Retrieve the operation handler from internal whitelist
* @param serviceName The service name that we are intercepting
* @param operationName The operation name of downstream call we are making
* @return The operation handler that will help us obtain field values to gather.
*/
private AWSOperationHandler getOperationHandler(String serviceName, String operationName) {
if (awsServiceHandlerManifest == null) {
return null;
}
AWSOperationHandlerManifest operationManifest = awsServiceHandlerManifest.getOperationHandlerManifest(serviceName);
if (operationManifest == null) {
return null;
}
return operationManifest.getOperationHandler(operationName);
}
/**
* Initialize the interceptor manifest by reading the default whitelisted JSON and constructing the handler
* manifest from this JSON
* @param parameterWhitelist The URL path of the parameter whitelist JSON.
*/
private void initInterceptorManifest(URL parameterWhitelist) {
if (parameterWhitelist != null) {
try {
awsServiceHandlerManifest = mapper.readValue(parameterWhitelist, AWSServiceHandlerManifest.class);
return;
} catch (IOException e) {
log.error(
"Unable to parse operation parameter whitelist at " + parameterWhitelist.getPath() +
". Falling back to default operation parameter whitelist at " + DEFAULT_OPERATION_PARAMETER_WHITELIST.getPath() + ".",
e
);
}
}
try {
awsServiceHandlerManifest = mapper.readValue(DEFAULT_OPERATION_PARAMETER_WHITELIST, AWSServiceHandlerManifest.class);
} catch (IOException e) {
log.error(
"Unable to parse default operation parameter whitelist at " + DEFAULT_OPERATION_PARAMETER_WHITELIST.getPath() +
". This will affect this handler's ability to capture AWS operation parameter information.",
e
);
}
}
}
| 3,973 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/handlers/downstream/AWSHandler.java | package com.amazonaws.xray.agent.runtime.handlers.downstream;
import com.amazonaws.Request;
import com.amazonaws.Response;
import com.amazonaws.xray.agent.runtime.handlers.XRayHandler;
import com.amazonaws.xray.handlers.TracingHandler;
import software.amazon.disco.agent.event.Event;
import software.amazon.disco.agent.event.ServiceRequestEvent;
import software.amazon.disco.agent.event.ServiceResponseEvent;
import java.net.URL;
/**
* The AWS handler generates a subsegment from a given AWS downstream service event.
* Due to a limitation in the AWS SDK V1 interceptor, S3 is currently not supported.
*/
public class AWSHandler extends XRayHandler {
private TracingHandler tracingHandler;
public AWSHandler() {
// We internally re-use our tracing handler from our AWS SDK V1 instrumentor to do all the X-Ray handling.
// The tracing handler's internal call to beforeExecution doesn't need to be done because this agent
// uses its own context for propagating segments using the TransactionContext.
tracingHandler = new TracingHandler();
}
public AWSHandler(URL serviceHandlerManifest) {
tracingHandler = new TracingHandler(serviceHandlerManifest);
}
@Override
public void handleRequest(Event event) {
ServiceRequestEvent requestEvent = (ServiceRequestEvent) event;
Request awsRequest = (Request) requestEvent.getRequest();
// Avoid throwing if we can't get the service name because of an old version of AWS SDK
// HTTP handler should pick it up instead.
if (awsRequest.getServiceName() == null) {
return;
}
tracingHandler.beforeRequest(awsRequest);
}
@Override
public void handleResponse(Event event) {
ServiceResponseEvent responseEvent = (ServiceResponseEvent) event;
Request awsReq = (Request) responseEvent.getRequest().getRequest();
Response awsResp = (Response) responseEvent.getResponse();
if (responseEvent.getThrown() == null) {
tracingHandler.afterResponse(awsReq, awsResp);
} else {
Throwable exception = responseEvent.getThrown();
tracingHandler.afterError(awsReq, awsResp, (Exception) exception);
}
}
}
| 3,974 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/handlers/downstream/SqlHandler.java | package com.amazonaws.xray.agent.runtime.handlers.downstream;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.agent.runtime.config.XRaySDKConfiguration;
import com.amazonaws.xray.agent.runtime.handlers.XRayHandler;
import com.amazonaws.xray.agent.runtime.models.XRayTransactionState;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.sql.SqlSubsegments;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import software.amazon.disco.agent.concurrent.TransactionContext;
import software.amazon.disco.agent.event.Event;
import software.amazon.disco.agent.event.ServiceDownstreamRequestEvent;
import software.amazon.disco.agent.event.ServiceDownstreamResponseEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Creates fully populated subsegments to represent downstream SQL queries.
*/
public class SqlHandler extends XRayHandler {
private static final Log log = LogFactory.getLog(SqlHandler.class);
// Visible for testing
static final String SQL_SUBSEGMENT_COUNT_KEY = "XRaySQLSubsegmentCount";
/**
* Uses the JDBC Statement from the Disco event to retrieve metadata about this query. Begins a subsegment
* using that metadata.
*
* @param event The request event dispatched from the dispatcher.
*/
@Override
public void handleRequest(Event event) {
// If a parent SQL transaction is already in progress, we return to avoid an infinite loop. This is because
// in order to populate a SQL subsegment, we make several calls to the JDBC Driver's DatabaseMetaData object.
// For example, if a driver's implementation of DatabaseMetaData.getUserName() uses executeQuery("SELECT USER")
// to get the DB user, executeQuery would be intercepted by the Disco JDBC plugin, trigger this handler to
// create subegment, and we'd call getUserName to populate that subsegment and so on.
if (incrementSqlTransactionCount() > 1) {
return;
}
ServiceDownstreamRequestEvent requestEvent = (ServiceDownstreamRequestEvent) event;
Statement statement = (Statement) requestEvent.getRequest();
String queryString = requestEvent.getOperation();
boolean recordSql = XRaySDKConfiguration.getInstance().shouldCollectSqlQueries();
final Connection connection;
try {
connection = statement.getConnection();
} catch (SQLException e) {
log.debug("Encountered exception when creating subsegment for query of "
+ requestEvent.getService() + ", starting blank subsegment", e);
AWSXRay.beginSubsegment(SqlSubsegments.DEFAULT_DATABASE_NAME);
return;
}
// If the query string wasn't provided by current DiSCo event, check the preparedMap cache
if (queryString == null && statement instanceof PreparedStatement) {
queryString = XRayTransactionState.getPreparedQuery((PreparedStatement) statement);
}
// If user opted-in to record their Queries, include them in the subsegment
SqlSubsegments.forQuery(connection, recordSql ? queryString : null);
}
/**
* Closes the subsegment representing this SQL query, including the exception if one was raised.
*
* @param event The response event dispatched from the dispatcher.
*/
@Override
public void handleResponse(Event event) {
// If this SQL request is being ignored, we should also ignore the response
if (decrementSqlTransactionCount() > 0) {
return;
}
Subsegment subsegment = getSubsegment();
ServiceDownstreamResponseEvent responseEvent = (ServiceDownstreamResponseEvent) event;
Throwable thrown = responseEvent.getThrown();
if (thrown != null) {
subsegment.addException(thrown);
}
endSubsegment();
}
// Visible for testing
synchronized int getSqlTransactionCount() {
Integer count = (Integer) TransactionContext.getMetadata(SQL_SUBSEGMENT_COUNT_KEY);
if (count == null) {
count = 0;
setSqlTransactionCount(count);
}
return count;
}
private synchronized int incrementSqlTransactionCount() {
int count = getSqlTransactionCount() + 1;
TransactionContext.putMetadata(SQL_SUBSEGMENT_COUNT_KEY, count);
return count;
}
private synchronized int decrementSqlTransactionCount() {
int count = getSqlTransactionCount() - 1;
TransactionContext.putMetadata(SQL_SUBSEGMENT_COUNT_KEY, count);
return count;
}
// Visible for testing
synchronized void setSqlTransactionCount(int val) {
TransactionContext.putMetadata(SQL_SUBSEGMENT_COUNT_KEY, val);
}
}
| 3,975 |
0 | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/handlers | Create_ds/aws-xray-java-agent/aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/handlers/upstream/ServletHandler.java | package com.amazonaws.xray.agent.runtime.handlers.upstream;
import com.amazonaws.xray.agent.runtime.config.XRaySDKConfiguration;
import com.amazonaws.xray.agent.runtime.handlers.XRayHandler;
import com.amazonaws.xray.agent.runtime.models.XRayTransactionState;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.TraceHeader;
import software.amazon.disco.agent.event.Event;
import software.amazon.disco.agent.event.HttpNetworkProtocolRequestEvent;
import software.amazon.disco.agent.event.HttpServletNetworkRequestEvent;
import software.amazon.disco.agent.event.HttpServletNetworkResponseEvent;
import java.util.HashMap;
import java.util.Map;
/**
* This handler handles an HttpEvent usually retrieved as a result of servlet interception and generates a segment.
* It populates this segment with HTTP metadata.
*/
public class ServletHandler extends XRayHandler {
private static final String URL_KEY = "url";
private static final String METHOD_KEY = "method";
private static final String CLIENT_IP_KEY = "client_ip";
private static final String USER_AGENT_KEY = "user_agent";
private static final String FORWARDED_FOR_KEY_LOWER = "x-forwarded-for";
private static final String FORWARDED_FOR_KEY_UPPER = "X-Forwarded-For";
private static final String FORWARDED_FOR_ATTRIB = "x_forwarded_for";
private static final String RESPONSE_KEY = "response";
private static final String HTTP_REQUEST_KEY = "request";
private static final String STATUS_KEY = "status";
@Override
public void handleRequest(Event event) {
HttpServletNetworkRequestEvent requestEvent = (HttpServletNetworkRequestEvent) event;
// For Spring Boot apps, the trace ID injection libraries will not be visible on classpath until after startup,
// so we must try to lazy load them as early as possible
XRaySDKConfiguration.getInstance().lazyLoadTraceIdInjection(getGlobalRecorder());
// HttpEvents are seen as servlet invocations, so in every request, we mark that we are serving an Http request
// In X-Ray's context, this means that if we receive a activity event, to start generating a segment.
XRayTransactionState transactionState = getTransactionState();
addRequestDataToTransactionState(requestEvent, transactionState);
boolean ipForwarded = addClientIPToTransactionState(requestEvent, transactionState);
// TODO Fix request event bug so that getHeaderData is lower cased. This needs to be case insensitive
// See: https://github.com/awslabs/disco/issues/14
String headerData = requestEvent.getHeaderData(HEADER_KEY.toLowerCase());
if (headerData == null) {
headerData = requestEvent.getHeaderData(HEADER_KEY);
}
transactionState.withTraceheaderString(headerData);
TraceHeader traceHeader = TraceHeader.fromString(transactionState.getTraceHeader());
Segment segment = beginSegment(XRayTransactionState.getServiceName(), traceHeader);
// Obtain sampling decision
boolean shouldSample = getSamplingDecision(transactionState);
segment.setSampled(shouldSample);
// Add HTTP Information
Map<String, Object> requestAttributes = new HashMap<>();
requestAttributes.put(URL_KEY, transactionState.getURL());
requestAttributes.put(USER_AGENT_KEY, transactionState.getUserAgent());
requestAttributes.put(METHOD_KEY, transactionState.getMethod());
requestAttributes.put(CLIENT_IP_KEY, transactionState.getClientIP());
if (ipForwarded) requestAttributes.put(FORWARDED_FOR_ATTRIB, true);
segment.putHttp(HTTP_REQUEST_KEY, requestAttributes);
}
@Override
public void handleResponse(Event event) {
HttpServletNetworkResponseEvent responseEvent = (HttpServletNetworkResponseEvent) event;
Segment currentSegment = getSegment();
// No need to log since a Context Missing Error will already be recorded
if (currentSegment == null) {
return;
}
// Add the status code
// Obtain the status code of the underlying http response. If it failed, it's a fault.
Map<String, Object> responseAttributes = new HashMap<>();
int statusCode = responseEvent.getStatusCode();
// Check if the status code was a fault.
switch (statusCode / 100) {
case 2:
// Server OK
break;
case 4:
// Exception
currentSegment.setError(true);
if (statusCode == 429) {
currentSegment.setThrottle(true);
}
break;
case 5:
// Fault
currentSegment.setFault(true);
break;
}
responseAttributes.put(STATUS_KEY, statusCode);
currentSegment.putHttp(RESPONSE_KEY, responseAttributes);
endSegment();
}
/**
* Helper method to put all the relevant Http information from the request event to our transaction state.
*
* @param requestEvent The HttpNetworkProtocolRequestEvent that was captured from the event bus.
* @param transactionState The current XRay transactional state
*/
private void addRequestDataToTransactionState(HttpNetworkProtocolRequestEvent requestEvent, XRayTransactionState transactionState) {
transactionState.withHost(requestEvent.getHost())
.withMethod(requestEvent.getMethod())
.withUrl(requestEvent.getURL())
.withUserAgent(requestEvent.getUserAgent())
.withTraceheaderString(requestEvent.getHeaderData(HEADER_KEY));
}
private boolean addClientIPToTransactionState(HttpNetworkProtocolRequestEvent requestEvent, XRayTransactionState transactionState) {
String clientIP = requestEvent.getHeaderData(FORWARDED_FOR_KEY_UPPER);
boolean forwarded = true;
if (clientIP == null || clientIP.isEmpty()) {
clientIP = requestEvent.getHeaderData(FORWARDED_FOR_KEY_LOWER);
}
if (clientIP == null || clientIP.isEmpty()) {
clientIP = requestEvent.getRemoteIPAddress();
forwarded = false;
}
transactionState.withClientIP(clientIP);
return forwarded;
}
}
| 3,976 |
0 | Create_ds/dgs-examples-java-2.7/src/test/java/com/example | Create_ds/dgs-examples-java-2.7/src/test/java/com/example/demo/ReviewSubscriptionIntegrationTest.java | package com.example.demo;
import com.example.demo.generated.client.AddReviewGraphQLQuery;
import com.example.demo.generated.client.AddReviewProjectionRoot;
import com.example.demo.generated.client.ReviewAddedGraphQLQuery;
import com.example.demo.generated.client.ReviewAddedProjectionRoot;
import com.example.demo.generated.types.SubmittedReview;
import com.netflix.graphql.dgs.client.MonoGraphQLClient;
import com.netflix.graphql.dgs.client.WebSocketGraphQLClient;
import com.netflix.graphql.dgs.client.codegen.GraphQLQueryRequest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
import java.time.Duration;
import java.util.Collections;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ReviewSubscriptionIntegrationTest {
@LocalServerPort
private Integer port;
private WebSocketGraphQLClient webSocketGraphQLClient;
private MonoGraphQLClient graphQLClient;
@BeforeEach
public void setup() {
webSocketGraphQLClient = new WebSocketGraphQLClient("ws://localhost:" + port + "/subscriptions", new ReactorNettyWebSocketClient());
graphQLClient = MonoGraphQLClient.createWithWebClient(WebClient.create(("http://localhost:" + port + "/graphql")));
}
@Test
public void testWebSocketSubscription() {
GraphQLQueryRequest subscriptionRequest = new GraphQLQueryRequest(
ReviewAddedGraphQLQuery.newRequest().showId(1).build(),
new ReviewAddedProjectionRoot<>().starScore()
);
GraphQLQueryRequest addReviewMutation1 = new GraphQLQueryRequest(
AddReviewGraphQLQuery.newRequest().review(SubmittedReview.newBuilder().showId(1).starScore(5).username("DGS User").build()).build(),
new AddReviewProjectionRoot<>().starScore()
);
GraphQLQueryRequest addReviewMutation2 = new GraphQLQueryRequest(
AddReviewGraphQLQuery.newRequest().review(SubmittedReview.newBuilder().showId(1).starScore(3).username("DGS User").build()).build(),
new AddReviewProjectionRoot<>().starScore()
);
Flux<Integer> starScore = webSocketGraphQLClient.reactiveExecuteQuery(subscriptionRequest.serialize(), Collections.emptyMap()).map(r -> r.extractValue("reviewAdded.starScore"));
StepVerifier.create(starScore)
.thenAwait(Duration.ofSeconds(1))
.then(() -> {
graphQLClient.reactiveExecuteQuery(addReviewMutation1.serialize(), Collections.emptyMap()).block();
})
.then(() ->
graphQLClient.reactiveExecuteQuery(addReviewMutation2.serialize(), Collections.emptyMap()).block())
.expectNext(5)
.expectNext(3)
.thenCancel()
.verify();
}
}
| 3,977 |
0 | Create_ds/dgs-examples-java-2.7/src/test/java/com/example | Create_ds/dgs-examples-java-2.7/src/test/java/com/example/demo/ArtworkUploadDataFetcherTest.java | package com.example.demo;
import com.example.demo.generated.types.Image;
import com.jayway.jsonpath.TypeRef;
import com.netflix.graphql.dgs.DgsQueryExecutor;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockMultipartFile;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
@SpringBootTest
class ArtworkUploadDataFetcherTest {
@Autowired
DgsQueryExecutor dgsQueryExecutor;
@Test
void addArtwork() {
int showId = new Random().nextInt();
Map<String, Object> map = new HashMap<String, Object>() {{
put("showId", showId);
put("upload", new MockMultipartFile("test", "test.file", "text/plain", "test".getBytes()));
}};
String mutation = "mutation addArtwork($showId:Int!, $upload:Upload!) { addArtwork(showId:$showId, upload:$upload) {url} }";
List<Image> result = dgsQueryExecutor.executeAndExtractJsonPathAsObject(
mutation,
"data.addArtwork",
map,
new TypeRef<List<Image>>() {
}
);
assertThat(result.size()).isNotZero();
assertThat(result.get(0).getUrl()).contains(String.valueOf(showId));
}
} | 3,978 |
0 | Create_ds/dgs-examples-java-2.7/src/test/java/com/example | Create_ds/dgs-examples-java-2.7/src/test/java/com/example/demo/SecurityExampleFetchersTest.java | package com.example.demo;
import com.netflix.graphql.dgs.DgsQueryExecutor;
import com.netflix.graphql.dgs.exceptions.QueryException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithMockUser;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
@SpringBootTest
class SecurityExampleFetchersTest {
@Autowired
DgsQueryExecutor dgsQueryExecutor;
@Test
void secureNone() {
String result = dgsQueryExecutor.executeAndExtractJsonPathAsObject(
" { secureNone }",
"data.secureNone",
String.class);
assertThat(result).isEqualTo("Hello to everyone");
}
@Test
@WithMockUser(username = "user", password = "user")
void secureUserWithUser() {
String result = dgsQueryExecutor.executeAndExtractJsonPathAsObject(
" { secureUser }",
"data.secureUser",
String.class
);
assertThat(result).isEqualTo("Hello to users or admins");
}
@Test
@WithMockUser(username = "admin", password = "admin", roles = {"ADMIN"})
void secureUserWithAdmin() {
String result = dgsQueryExecutor.executeAndExtractJsonPathAsObject(
" { secureUser }",
"data.secureUser",
String.class
);
assertThat(result).isEqualTo("Hello to users or admins");
}
@Test
void secureUserWithNone() {
assertThrows(QueryException.class, () -> {
dgsQueryExecutor.executeAndExtractJsonPathAsObject(
" { secureUser }",
"data.secureUser",
String.class
);
});
}
@Test
@WithMockUser(username = "admin", password = "admin", roles = {"ADMIN"})
void secureAdminWithAdmin() {
String result = dgsQueryExecutor.executeAndExtractJsonPathAsObject(
" { secureAdmin }",
"data.secureAdmin",
String.class
);
assertThat(result).isEqualTo("Hello to admins only");
}
@Test
@WithMockUser(username = "user", password = "user")
void secureAdminWithUser() {
assertThrows(QueryException.class, () -> {
dgsQueryExecutor.executeAndExtractJsonPathAsObject(
" { secureAdmin }",
"data.secureAdmin",
String.class
);
});
}
@Test
void secureAdminWithNone() {
assertThrows(QueryException.class, () -> {
dgsQueryExecutor.executeAndExtractJsonPathAsObject(
" { secureAdmin }",
"data.secureAdmin",
String.class
);
});
}
}
| 3,979 |
0 | Create_ds/dgs-examples-java-2.7/src/test/java/com/example | Create_ds/dgs-examples-java-2.7/src/test/java/com/example/demo/ReviewSubscriptionTest.java | package com.example.demo;
import com.example.demo.datafetchers.ReviewsDataFetcher;
import com.example.demo.generated.client.AddReviewGraphQLQuery;
import com.example.demo.generated.client.AddReviewProjectionRoot;
import com.example.demo.generated.types.Review;
import com.example.demo.generated.types.SubmittedReview;
import com.example.demo.scalars.DateTimeScalar;
import com.example.demo.services.DefaultReviewsService;
import com.example.demo.services.ShowsService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.graphql.dgs.DgsQueryExecutor;
import com.netflix.graphql.dgs.autoconfig.DgsAutoConfiguration;
import com.netflix.graphql.dgs.client.codegen.GraphQLQueryRequest;
import graphql.ExecutionResult;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
/**
* Test the review added subscription.
* The subscription query returns a Publisher<ExecutionResult>.
* Each time a review is added, a new ExecutionResult is given to subscriber.
* Normally, this publisher is consumed by the Websocket/SSE subscription handler and you don't deal with this code directly, but for testing purposes it's useful to use the stream directly.
*/
@SpringBootTest(classes = {DefaultReviewsService.class, ReviewsDataFetcher.class, DgsAutoConfiguration.class, DateTimeScalar.class})
public class ReviewSubscriptionTest {
@Autowired
DgsQueryExecutor dgsQueryExecutor;
@MockBean
ShowsService showsService;
@Test
void reviewSubscription() {
ExecutionResult executionResult = dgsQueryExecutor.execute("subscription { reviewAdded(showId: 1) {starScore} }");
Publisher<ExecutionResult> reviewPublisher = executionResult.getData();
List<Review> reviews = new CopyOnWriteArrayList<>();
reviewPublisher.subscribe(new Subscriber<ExecutionResult>() {
@Override
public void onSubscribe(Subscription s) {
s.request(2);
}
@Override
public void onNext(ExecutionResult executionResult) {
if (executionResult.getErrors().size() > 0) {
System.out.println(executionResult.getErrors());
}
Map<String, Object> review = executionResult.getData();
reviews.add(new ObjectMapper().convertValue(review.get("reviewAdded"), Review.class));
}
@Override
public void onError(Throwable t) {
}
@Override
public void onComplete() {
}
});
addReview();
addReview();
assertThat(reviews.size()).isEqualTo(2);
}
private void addReview() {
GraphQLQueryRequest graphQLQueryRequest = new GraphQLQueryRequest(
AddReviewGraphQLQuery.newRequest()
.review(
SubmittedReview.newBuilder()
.showId(1)
.username("testuser")
.starScore(5).build())
.build(),
new AddReviewProjectionRoot<>()
.username()
.starScore());
dgsQueryExecutor.execute(graphQLQueryRequest.serialize());
}
}
| 3,980 |
0 | Create_ds/dgs-examples-java-2.7/src/test/java/com/example | Create_ds/dgs-examples-java-2.7/src/test/java/com/example/demo/ShowsDatafetcherTest.java | package com.example.demo;
import com.example.demo.datafetchers.ReviewsDataFetcher;
import com.example.demo.datafetchers.ShowsDatafetcher;
import com.example.demo.dataloaders.ReviewsDataLoader;
import com.example.demo.dataloaders.ReviewsDataLoaderWithContext;
import com.example.demo.generated.client.*;
import com.example.demo.generated.types.Review;
import com.example.demo.generated.types.Show;
import com.example.demo.generated.types.SubmittedReview;
import com.example.demo.scalars.DateTimeScalar;
import com.example.demo.services.DefaultReviewsService;
import com.example.demo.services.ShowsService;
import com.jayway.jsonpath.TypeRef;
import com.netflix.graphql.dgs.DgsQueryExecutor;
import com.netflix.graphql.dgs.autoconfig.DgsAutoConfiguration;
import com.netflix.graphql.dgs.client.codegen.GraphQLQueryRequest;
import graphql.ExecutionResult;
import org.assertj.core.util.Maps;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import java.time.OffsetDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
@SpringBootTest(classes = {DgsAutoConfiguration.class, ReviewsDataLoaderWithContext.class, ShowsDatafetcher.class, ReviewsDataFetcher.class, ReviewsDataLoader.class, DateTimeScalar.class})
class ShowsDatafetcherTest {
@Autowired
DgsQueryExecutor dgsQueryExecutor;
@MockBean
ShowsService showsService;
@MockBean
DefaultReviewsService reviewsService;
@BeforeEach
public void before() {
Mockito.when(showsService.shows())
.thenAnswer(invocation -> Collections.singletonList(Show.newBuilder().id(1).title("mock title").releaseYear(2020).build()));
Mockito.when(reviewsService.reviewsForShows(Collections.singletonList(1)))
.thenAnswer(invocation ->
Maps.newHashMap(1, Arrays.asList(
Review.newBuilder().username("DGS User").starScore(5).submittedDate(OffsetDateTime.now()).build(),
Review.newBuilder().username("DGS User 2").starScore(3).submittedDate(OffsetDateTime.now()).build())
));
}
@Test
void shows() {
List<String> titles = dgsQueryExecutor.executeAndExtractJsonPath(
" { shows { title releaseYear }}",
"data.shows[*].title");
assertThat(titles).contains("mock title");
}
@Test
void showsWithException() {
Mockito.when(showsService.shows()).thenThrow(new RuntimeException("nothing to see here"));
ExecutionResult result = dgsQueryExecutor.execute(
" { shows { title releaseYear }}");
assertThat(result.getErrors()).isNotEmpty();
assertThat(result.getErrors().get(0).getMessage()).isEqualTo("java.lang.RuntimeException: nothing to see here");
}
@Test
void showsWithQueryApi() {
GraphQLQueryRequest graphQLQueryRequest = new GraphQLQueryRequest(ShowsGraphQLQuery.newRequest().titleFilter("").build(), new ShowsProjectionRoot<>().title());
List<String> titles = dgsQueryExecutor.executeAndExtractJsonPath(graphQLQueryRequest.serialize(), "data.shows[*].title");
assertThat(titles).contains("mock title");
}
@Test
void showWithReviews() {
GraphQLQueryRequest graphQLQueryRequest = new GraphQLQueryRequest(ShowsGraphQLQuery.newRequest().titleFilter("").build(),
new ShowsProjectionRoot<>()
.title()
.reviews()
.username()
.starScore());
List<Show> shows = dgsQueryExecutor.executeAndExtractJsonPathAsObject(
graphQLQueryRequest.serialize(),
"data.shows[*]",
new TypeRef<List<Show>>() {
});
assertThat(shows.size()).isEqualTo(1);
assertThat(shows.get(0).getReviews().size()).isEqualTo(2);
}
@Test
void addReviewMutation() {
GraphQLQueryRequest graphQLQueryRequest = new GraphQLQueryRequest(
AddReviewGraphQLQuery.newRequest()
.review(SubmittedReview.newBuilder()
.showId(1)
.username("testuser")
.starScore(5).build())
.build(),
new AddReviewProjectionRoot<>().username().starScore());
ExecutionResult executionResult = dgsQueryExecutor.execute(graphQLQueryRequest.serialize());
assertThat(executionResult.getErrors()).isEmpty();
verify(reviewsService).reviewsForShow(1);
}
@Test
void addReviewsMutation() {
List<SubmittedReview> reviews = Collections.singletonList(
SubmittedReview.newBuilder().showId(1).username("testuser1").starScore(5).build());
GraphQLQueryRequest graphQLQueryRequest = new GraphQLQueryRequest(
AddReviewsGraphQLQuery.newRequest()
.reviews(reviews)
.build(),
new AddReviewsProjectionRoot<>().username().starScore());
ExecutionResult executionResult = dgsQueryExecutor.execute(graphQLQueryRequest.serialize());
assertThat(executionResult.getErrors()).isEmpty();
verify(reviewsService).reviewsForShows(Collections.singletonList(1));
}
} | 3,981 |
0 | Create_ds/dgs-examples-java-2.7/src/main/java/com/example | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo/DemoApplication.java | package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
/**
* Below is an example of using a PreparsedDocumentProvider.
* Uncomment to enable
*/
// @Configuration
// static class PreparsedDocumentProviderConfig {
//
// private final Cache<String, PreparsedDocumentEntry> cache = Caffeine.newBuilder().maximumSize(250)
// .expireAfterAccess(5, TimeUnit.MINUTES).recordStats().build();
//
//
// @Bean
// public PreparsedDocumentProvider preparsedDocumentProvider() {
// return (executionInput, parseAndValidateFunction) -> {
// Function<String, PreparsedDocumentEntry> mapCompute = key -> parseAndValidateFunction.apply(executionInput);
// return cache.get(executionInput.getQuery(), mapCompute);
// };
// }
// }
}
| 3,982 |
0 | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo/directives/UppercaseDirective.java | package com.example.demo.directives;
import com.netflix.graphql.dgs.DgsDirective;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetcherFactories;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.GraphQLFieldsContainer;
import graphql.schema.idl.SchemaDirectiveWiring;
import graphql.schema.idl.SchemaDirectiveWiringEnvironment;
@DgsDirective(name = "uppercase")
public class UppercaseDirective implements SchemaDirectiveWiring {
@Override
public GraphQLFieldDefinition onField(SchemaDirectiveWiringEnvironment<GraphQLFieldDefinition> env) {
GraphQLFieldsContainer fieldsContainer = env.getFieldsContainer();
GraphQLFieldDefinition fieldDefinition = env.getFieldDefinition();
DataFetcher<?> originalDataFetcher = env.getCodeRegistry().getDataFetcher(fieldsContainer, fieldDefinition);
DataFetcher<?> dataFetcher = DataFetcherFactories.wrapDataFetcher(
originalDataFetcher,
(dataFetchingEnvironment, value) -> {
if (value instanceof String) {
return ((String) value).toUpperCase();
}
return value;
}
);
env.getCodeRegistry().dataFetcher(fieldsContainer, fieldDefinition, dataFetcher);
return fieldDefinition;
}
}
| 3,983 |
0 | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo/config/SecurityConfig.java | package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.DefaultSecurityFilterChain;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig {
@Bean
DefaultSecurityFilterChain springWebFilterChain(HttpSecurity http) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable)
.authorizeRequests(requests -> requests
.anyRequest().permitAll()
)
.httpBasic(withDefaults())
.build();
}
@Bean
public static InMemoryUserDetailsManager userDetailsService() {
User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
UserDetails user = userBuilder.username("user").password("user").roles("USER").build();
UserDetails admin = userBuilder.username("admin").password("admin").roles("USER", "ADMIN").build();
return new InMemoryUserDetailsManager(user, admin);
}
}
| 3,984 |
0 | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo/config/MetricsConfig.java | package com.example.demo.config;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.logging.LoggingMeterRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MetricsConfig {
@Bean
public MeterRegistry loggingMeterRegistry() {
return new LoggingMeterRegistry();
}
}
| 3,985 |
0 | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo/scalars/DateTimeScalar.java | package com.example.demo.scalars;
import com.netflix.graphql.dgs.DgsComponent;
import com.netflix.graphql.dgs.DgsRuntimeWiring;
import graphql.scalars.ExtendedScalars;
import graphql.schema.idl.RuntimeWiring;
/**
* graphql-java provides optional scalars in the graphql-java-extended-scalars library.
* We can wire a scalar from this library by adding the scalar to the RuntimeWiring.
*/
@DgsComponent
public class DateTimeScalar {
@DgsRuntimeWiring
public RuntimeWiring.Builder addScalar(RuntimeWiring.Builder builder) {
return builder.scalar(ExtendedScalars.DateTime);
}
}
| 3,986 |
0 | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo/dataloaders/ReviewsDataLoader.java | package com.example.demo.dataloaders;
import com.example.demo.generated.types.Review;
import com.example.demo.services.DefaultReviewsService;
import com.netflix.graphql.dgs.DgsDataLoader;
import org.dataloader.MappedBatchLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
@DgsDataLoader(name = "reviews")
public class ReviewsDataLoader implements MappedBatchLoader<Integer, List<Review>> {
private final DefaultReviewsService reviewsService;
public ReviewsDataLoader(DefaultReviewsService reviewsService) {
this.reviewsService = reviewsService;
}
/**
* This method will be called once, even if multiple datafetchers use the load() method on the DataLoader.
* This way reviews can be loaded for all the Shows in a single call instead of per individual Show.
*/
@Override
public CompletionStage<Map<Integer, List<Review>>> load(Set<Integer> keys) {
return CompletableFuture.supplyAsync(() -> reviewsService.reviewsForShows(new ArrayList<>(keys)));
}
}
| 3,987 |
0 | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo/dataloaders/ReviewsDataLoaderWithContext.java | package com.example.demo.dataloaders;
import com.example.demo.generated.types.Review;
import com.example.demo.services.DefaultReviewsService;
import com.netflix.graphql.dgs.DgsDataLoader;
import org.dataloader.BatchLoaderEnvironment;
import org.dataloader.MappedBatchLoader;
import org.dataloader.MappedBatchLoaderWithContext;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
@DgsDataLoader(name = "reviewsWithContext")
public class ReviewsDataLoaderWithContext implements MappedBatchLoaderWithContext<Integer, List<Review>> {
private final DefaultReviewsService reviewsService;
@Autowired
public ReviewsDataLoaderWithContext(DefaultReviewsService reviewsService) {
this.reviewsService = reviewsService;
}
@Override
public CompletionStage<Map<Integer, List<Review>>> load(Set<Integer> keys, BatchLoaderEnvironment environment) {
return CompletableFuture.supplyAsync(() -> reviewsService.reviewsForShows(new ArrayList<>(keys)));
}
}
| 3,988 |
0 | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo/instrumentation/ExampleTracingInstrumentation.java | package com.example.demo.instrumentation;
import graphql.ExecutionResult;
import graphql.execution.instrumentation.InstrumentationContext;
import graphql.execution.instrumentation.InstrumentationState;
import graphql.execution.instrumentation.SimpleInstrumentation;
import graphql.execution.instrumentation.parameters.InstrumentationExecutionParameters;
import graphql.execution.instrumentation.parameters.InstrumentationFieldFetchParameters;
import graphql.schema.DataFetcher;
import graphql.schema.GraphQLNonNull;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLOutputType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.concurrent.CompletableFuture;
@Component
public class ExampleTracingInstrumentation extends SimpleInstrumentation {
private final static Logger LOGGER = LoggerFactory.getLogger(ExampleTracingInstrumentation.class);
@Override
public InstrumentationState createState() {
return new TracingState();
}
@Override
public InstrumentationContext<ExecutionResult> beginExecution(InstrumentationExecutionParameters parameters) {
TracingState tracingState = parameters.getInstrumentationState();
tracingState.startTime = System.currentTimeMillis();
return super.beginExecution(parameters);
}
@Override
public DataFetcher<?> instrumentDataFetcher(DataFetcher<?> dataFetcher, InstrumentationFieldFetchParameters parameters) {
// We only care about user code
if(parameters.isTrivialDataFetcher()) {
return dataFetcher;
}
return environment -> {
long startTime = System.currentTimeMillis();
Object result = dataFetcher.get(environment);
if(result instanceof CompletableFuture) {
((CompletableFuture<?>) result).whenComplete((r, ex) -> {
long totalTime = System.currentTimeMillis() - startTime;
LOGGER.info("Async datafetcher {} took {}ms", findDatafetcherTag(parameters), totalTime);
});
} else {
long totalTime = System.currentTimeMillis() - startTime;
LOGGER.info("Datafetcher {} took {}ms", findDatafetcherTag(parameters), totalTime);
}
return result;
};
}
@Override
public CompletableFuture<ExecutionResult> instrumentExecutionResult(ExecutionResult executionResult, InstrumentationExecutionParameters parameters) {
TracingState tracingState = parameters.getInstrumentationState();
long totalTime = System.currentTimeMillis() - tracingState.startTime;
LOGGER.info("Total execution time: {}ms", totalTime);
return super.instrumentExecutionResult(executionResult, parameters);
}
private String findDatafetcherTag(InstrumentationFieldFetchParameters parameters) {
GraphQLOutputType type = parameters.getExecutionStepInfo().getParent().getType();
GraphQLObjectType parent;
if (type instanceof GraphQLNonNull) {
parent = (GraphQLObjectType) ((GraphQLNonNull) type).getWrappedType();
} else {
parent = (GraphQLObjectType) type;
}
return parent.getName() + "." + parameters.getExecutionStepInfo().getPath().getSegmentName();
}
static class TracingState implements InstrumentationState {
long startTime;
}
}
| 3,989 |
0 | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo/datafetchers/ArtworkUploadDataFetcher.java | package com.example.demo.datafetchers;
import com.example.demo.generated.types.Image;
import com.netflix.graphql.dgs.DgsComponent;
import com.netflix.graphql.dgs.DgsMutation;
import com.netflix.graphql.dgs.InputArgument;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@DgsComponent
public class ArtworkUploadDataFetcher {
@DgsMutation
public List<Image> addArtwork(@InputArgument Integer showId, @InputArgument MultipartFile upload) throws IOException {
Path uploadDir = Paths.get("uploaded-images");
if (!Files.exists(uploadDir)) {
Files.createDirectories(uploadDir);
}
Path newFile = uploadDir.resolve("show-" + showId + "-" + UUID.randomUUID() + upload.getOriginalFilename().substring(upload.getOriginalFilename().lastIndexOf(".")));
try (OutputStream outputStream = Files.newOutputStream(newFile)) {
outputStream.write(upload.getBytes());
}
return Files.list(uploadDir)
.filter(f -> f.getFileName().toString().startsWith("show-" + showId))
.map(f -> f.getFileName().toString())
.map(fileName -> Image.newBuilder().url(fileName).build()).collect(Collectors.toList());
}
}
| 3,990 |
0 | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo/datafetchers/ReviewsDataFetcher.java | package com.example.demo.datafetchers;
import com.example.demo.dataloaders.ReviewsDataLoader;
import com.example.demo.dataloaders.ReviewsDataLoaderWithContext;
import com.example.demo.generated.DgsConstants;
import com.example.demo.generated.types.Review;
import com.example.demo.generated.types.Show;
import com.example.demo.generated.types.SubmittedReview;
import com.example.demo.services.DefaultReviewsService;
import com.netflix.graphql.dgs.*;
import org.dataloader.BatchLoaderEnvironment;
import org.dataloader.DataLoader;
import org.reactivestreams.Publisher;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
@DgsComponent
public class ReviewsDataFetcher {
private final DefaultReviewsService reviewsService;
public ReviewsDataFetcher(DefaultReviewsService reviewsService) {
this.reviewsService = reviewsService;
}
/**
* This datafetcher will be called to resolve the "reviews" field on a Show.
* It's invoked for each individual Show, so if we would load 10 shows, this method gets called 10 times.
* To avoid the N+1 problem this datafetcher uses a DataLoader.
* Although the DataLoader is called for each individual show ID, it will batch up the actual loading to a single method call to the "load" method in the ReviewsDataLoader.
* For this to work correctly, the datafetcher needs to return a CompletableFuture.
*/
@DgsData(parentType = DgsConstants.SHOW.TYPE_NAME, field = DgsConstants.SHOW.Reviews)
public CompletableFuture<List<Review>> reviews(DgsDataFetchingEnvironment dfe) {
//Instead of loading a DataLoader by name, we can use the DgsDataFetchingEnvironment and pass in the DataLoader classname.
DataLoader<Integer, List<Review>> reviewsDataLoader = dfe.getDataLoader(ReviewsDataLoaderWithContext.class);
//Because the reviews field is on Show, the getSource() method will return the Show instance.
Show show = dfe.getSource();
//Load the reviews from the DataLoader. This call is async and will be batched by the DataLoader mechanism.
return reviewsDataLoader.load(show.getId());
}
@DgsMutation
public List<Review> addReview(@InputArgument SubmittedReview review) {
reviewsService.saveReview(review);
List<Review> reviews = reviewsService.reviewsForShow(review.getShowId());
return Optional.ofNullable(reviews).orElse(Collections.emptyList());
}
@DgsMutation
public List<Review> addReviews(@InputArgument(value = "reviews", collectionType = SubmittedReview.class) List<SubmittedReview> reviewsInput) {
reviewsService.saveReviews(reviewsInput);
List<Integer> showIds = reviewsInput.stream().map(SubmittedReview::getShowId).collect(Collectors.toList());
Map<Integer, List<Review>> reviews = reviewsService.reviewsForShows(showIds);
return reviews.values().stream().flatMap(List::stream).collect(Collectors.toList());
}
@DgsSubscription
public Publisher<Review> reviewAdded(@InputArgument Integer showId) {
return reviewsService.getReviewsPublisher();
}
}
| 3,991 |
0 | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo/datafetchers/ShowsDatafetcher.java | package com.example.demo.datafetchers;
import com.example.demo.generated.types.Show;
import com.example.demo.services.ShowsService;
import com.netflix.graphql.dgs.DgsComponent;
import com.netflix.graphql.dgs.DgsQuery;
import com.netflix.graphql.dgs.InputArgument;
import java.util.List;
import java.util.stream.Collectors;
@DgsComponent
public class ShowsDatafetcher {
private final ShowsService showsService;
public ShowsDatafetcher(ShowsService showsService) {
this.showsService = showsService;
}
/**
* This datafetcher resolves the shows field on Query.
* It uses an @InputArgument to get the titleFilter from the Query if one is defined.
*/
@DgsQuery
public List<Show> shows(@InputArgument("titleFilter") String titleFilter) {
if (titleFilter == null) {
return showsService.shows();
}
return showsService.shows().stream().filter(s -> s.getTitle().contains(titleFilter)).collect(Collectors.toList());
}
}
| 3,992 |
0 | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo/datafetchers/SecurityExampleFetchers.java | package com.example.demo.datafetchers;
import com.netflix.graphql.dgs.DgsComponent;
import com.netflix.graphql.dgs.DgsQuery;
import org.springframework.security.access.annotation.Secured;
@DgsComponent
public class SecurityExampleFetchers {
@DgsQuery
public String secureNone() {
return "Hello to everyone";
}
@DgsQuery
@Secured({"ROLE_USER", "ROLE_ADMIN"})
public String secureUser() {
return "Hello to users or admins";
}
@DgsQuery
@Secured({"ROLE_ADMIN"})
public String secureAdmin() {
return "Hello to admins only";
}
}
| 3,993 |
0 | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo/services/ShowsServiceImpl.java | package com.example.demo.services;
import com.example.demo.generated.types.Show;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
@Service
public class ShowsServiceImpl implements ShowsService {
@Override
public List<Show> shows() {
return Arrays.asList(
Show.newBuilder().id(1).title("Stranger Things").releaseYear(2016).build(),
Show.newBuilder().id(2).title("Ozark").releaseYear(2017).build(),
Show.newBuilder().id(3).title("The Crown").releaseYear(2016).build(),
Show.newBuilder().id(4).title("Dead to Me").releaseYear(2019).build(),
Show.newBuilder().id(5).title("Orange is the New Black").releaseYear(2013).build()
);
}
}
| 3,994 |
0 | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo/services/ReviewsService.java | package com.example.demo.services;
public interface ReviewsService {
}
| 3,995 |
0 | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo/services/ShowsService.java | package com.example.demo.services;
import com.example.demo.generated.types.Show;
import java.util.List;
public interface ShowsService {
List<Show> shows();
}
| 3,996 |
0 | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo | Create_ds/dgs-examples-java-2.7/src/main/java/com/example/demo/services/DefaultReviewsService.java | package com.example.demo.services;
import com.example.demo.generated.types.Review;
import com.example.demo.generated.types.SubmittedReview;
import net.datafaker.Faker;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import reactor.core.publisher.ConnectableFlux;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* This service emulates a data store.
* For convenience in the demo we just generate Reviews in memory, but imagine this would be backed by for example a database.
* If this was indeed backed by a database, it would be very important to avoid the N+1 problem, which means we need to use a DataLoader to call this class.
*/
@Service
public class DefaultReviewsService implements ReviewsService {
private final static Logger logger = LoggerFactory.getLogger(DefaultReviewsService.class);
private final ShowsService showsService;
private final Map<Integer, List<Review>> reviews = new ConcurrentHashMap<>();
private FluxSink<Review> reviewsStream;
private ConnectableFlux<Review> reviewsPublisher;
public DefaultReviewsService(ShowsService showsService) {
this.showsService = showsService;
}
@PostConstruct
private void createReviews() {
Faker faker = new Faker();
//For each show we generate a random set of reviews.
showsService.shows().forEach(show -> {
List<Review> generatedReviews = IntStream.range(0, faker.number().numberBetween(1, 20)).mapToObj(number -> {
LocalDateTime date = faker.date().past(300, TimeUnit.DAYS).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
return Review.newBuilder().submittedDate(OffsetDateTime.of(date, ZoneOffset.UTC)).username(faker.name().username()).starScore(faker.number().numberBetween(0, 6)).build();
}).collect(Collectors.toList());
reviews.put(show.getId(), generatedReviews);
});
Flux<Review> publisher = Flux.create(emitter -> {
reviewsStream = emitter;
});
reviewsPublisher = publisher.publish();
reviewsPublisher.connect();
}
/**
* Hopefully nobody calls this for multiple shows within a single query, that would indicate the N+1 problem!
*/
public List<Review> reviewsForShow(Integer showId) {
return reviews.get(showId);
}
/**
* This is the method we want to call when loading reviews for multiple shows.
* If this code was backed by a relational database, it would select reviews for all requested shows in a single SQL query.
*/
public Map<Integer, List<Review>> reviewsForShows(List<Integer> showIds) {
logger.info("Loading reviews for shows {}", showIds.stream().map(String::valueOf).collect(Collectors.joining(", ")));
return reviews
.entrySet()
.stream()
.filter(entry -> showIds.contains(entry.getKey())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
public void saveReview(SubmittedReview reviewInput) {
List<Review> reviewsForShow = reviews.computeIfAbsent(reviewInput.getShowId(), (key) -> new ArrayList<>());
Review review = Review.newBuilder()
.username(reviewInput.getUsername())
.starScore(reviewInput.getStarScore())
.submittedDate(OffsetDateTime.now()).build();
reviewsForShow.add(review);
reviewsStream.next(review);
logger.info("Review added {}", review);
}
public void saveReviews(List<SubmittedReview> reviewsInput) {
reviewsInput.forEach(reviewInput -> {
List<Review> reviewsForShow = reviews.computeIfAbsent(reviewInput.getShowId(), (key) -> new ArrayList<>());
Review review = Review.newBuilder()
.username(reviewInput.getUsername())
.starScore(reviewInput.getStarScore())
.submittedDate(OffsetDateTime.now()).build();
reviewsForShow.add(review);
reviewsStream.next(review);
logger.info("Review added {}", review);
});
}
public Publisher<Review> getReviewsPublisher() {
return reviewsPublisher;
}
}
| 3,997 |
0 | Create_ds/RealityMaterialExplorer/RealityMaterialExplorer/Upload/unityLibrary/src/main/java/com/unity | Create_ds/RealityMaterialExplorer/RealityMaterialExplorer/Upload/unityLibrary/src/main/java/com/unity/oculus/OculusUnity.java | package com.unity.oculus;
import android.app.Activity;
import android.view.Surface;
import android.view.SurfaceView;
import android.util.Log;
import android.view.ViewGroup;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Build;
import java.util.Locale;
import com.unity3d.player.UnityPlayer;
public class OculusUnity
{
UnityPlayer player;
Activity activity;
SurfaceView glView;
public void initOculus()
{
Log.d("Unity", "initOculus Java!");
activity = UnityPlayer.currentActivity;
activity.runOnUiThread(() -> {
ViewGroup vg = activity.findViewById(android.R.id.content);
player = null;
for (int i = 0; i < vg.getChildCount(); ++i) {
if (vg.getChildAt(i) instanceof UnityPlayer) {
player = (UnityPlayer) vg.getChildAt(i);
break;
}
}
if (player == null) {
Log.e("Unity", "Failed to find UnityPlayer view!");
return;
}
glView = null;
for (int i = 0; i < player.getChildCount(); ++i)
{
if (player.getChildAt(0) instanceof SurfaceView)
{
glView = (SurfaceView)player.getChildAt(0);
}
}
if (glView == null) {
Log.e("Unity", "Failed to find GlView!");
}
Log.d("Unity", "Oculus UI thread done.");
initComplete(glView.getHolder().getSurface());
});
}
public void pauseOculus()
{
}
public void resumeOculus()
{
}
public void destroyOculus()
{
}
private native void initComplete(Surface glView);
public static void loadLibrary(String name) {
Log.d("Unity", "loading library " + name);
java.lang.System.loadLibrary(name);
}
public static boolean getLowOverheadMode() {
boolean ret = false;
try
{
Activity activity = UnityPlayer.currentActivity;
ApplicationInfo appInfo = activity.getPackageManager().getApplicationInfo(activity.getPackageName(), PackageManager.GET_META_DATA);
Bundle bundle = appInfo.metaData;
ret = bundle.getBoolean("com.unity.xr.oculus.LowOverheadMode");
}
catch (Exception e)
{
Log.d("Unity", "Oculus XR Plugin init error");
}
return ret;
}
public static boolean getIsOnOculusHardware() {
String manufacturer = android.os.Build.MANUFACTURER;
return manufacturer.toLowerCase(Locale.ENGLISH).contains("oculus");
}
}
| 3,998 |
0 | Create_ds/RealityMaterialExplorer/RealityMaterialExplorer/Upload/unityLibrary/src/main/java/com/unity3d | Create_ds/RealityMaterialExplorer/RealityMaterialExplorer/Upload/unityLibrary/src/main/java/com/unity3d/player/UnityPlayerActivity.java | // GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN
package com.unity3d.player;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.os.Process;
public class UnityPlayerActivity extends Activity implements IUnityPlayerLifecycleEvents
{
protected UnityPlayer mUnityPlayer; // don't change the name of this variable; referenced from native code
// Override this in your custom UnityPlayerActivity to tweak the command line arguments passed to the Unity Android Player
// The command line arguments are passed as a string, separated by spaces
// UnityPlayerActivity calls this from 'onCreate'
// Supported: -force-gles20, -force-gles30, -force-gles31, -force-gles31aep, -force-gles32, -force-gles, -force-vulkan
// See https://docs.unity3d.com/Manual/CommandLineArguments.html
// @param cmdLine the current command line arguments, may be null
// @return the modified command line string or null
protected String updateUnityCommandLineArguments(String cmdLine)
{
return cmdLine;
}
// Setup activity layout
@Override protected void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
String cmdLine = updateUnityCommandLineArguments(getIntent().getStringExtra("unity"));
getIntent().putExtra("unity", cmdLine);
mUnityPlayer = new UnityPlayer(this, this);
setContentView(mUnityPlayer);
mUnityPlayer.requestFocus();
}
// When Unity player unloaded move task to background
@Override public void onUnityPlayerUnloaded() {
moveTaskToBack(true);
}
// When Unity player quited kill process
@Override public void onUnityPlayerQuitted() {
Process.killProcess(Process.myPid());
}
@Override protected void onNewIntent(Intent intent)
{
// To support deep linking, we need to make sure that the client can get access to
// the last sent intent. The clients access this through a JNI api that allows them
// to get the intent set on launch. To update that after launch we have to manually
// replace the intent with the one caught here.
setIntent(intent);
mUnityPlayer.newIntent(intent);
}
// Quit Unity
@Override protected void onDestroy ()
{
mUnityPlayer.destroy();
super.onDestroy();
}
// Pause Unity
@Override protected void onPause()
{
super.onPause();
mUnityPlayer.pause();
}
// Resume Unity
@Override protected void onResume()
{
super.onResume();
mUnityPlayer.resume();
}
// Low Memory Unity
@Override public void onLowMemory()
{
super.onLowMemory();
mUnityPlayer.lowMemory();
}
// Trim Memory Unity
@Override public void onTrimMemory(int level)
{
super.onTrimMemory(level);
if (level == TRIM_MEMORY_RUNNING_CRITICAL)
{
mUnityPlayer.lowMemory();
}
}
// This ensures the layout will be correct.
@Override public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
mUnityPlayer.configurationChanged(newConfig);
}
// Notify Unity of the focus change.
@Override public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
mUnityPlayer.windowFocusChanged(hasFocus);
}
// For some reason the multiple keyevent type is not supported by the ndk.
// Force event injection by overriding dispatchKeyEvent().
@Override public boolean dispatchKeyEvent(KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_MULTIPLE)
return mUnityPlayer.injectEvent(event);
return super.dispatchKeyEvent(event);
}
// Pass any events not handled by (unfocused) views straight to UnityPlayer
@Override public boolean onKeyUp(int keyCode, KeyEvent event) { return mUnityPlayer.injectEvent(event); }
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { return mUnityPlayer.injectEvent(event); }
@Override public boolean onTouchEvent(MotionEvent event) { return mUnityPlayer.injectEvent(event); }
/*API12*/ public boolean onGenericMotionEvent(MotionEvent event) { return mUnityPlayer.injectEvent(event); }
}
| 3,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.