Skip to content
This repository was archived by the owner on Dec 19, 2023. It is now read-only.

Commit 93b52ae

Browse files
committed
Sonar fixes
1 parent e208f75 commit 93b52ae

File tree

10 files changed

+95
-177
lines changed

10 files changed

+95
-177
lines changed

example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/SimpleListConnection.java

Lines changed: 21 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
import com.oembedler.moon.graphql.engine.relay.ConnectionObjectType;
44
import com.oembedler.moon.graphql.engine.relay.EdgeObjectType;
55
import com.oembedler.moon.graphql.engine.relay.PageInfoObjectType;
6-
import graphql.relay.ConnectionCursor;
7-
import graphql.relay.DefaultConnectionCursor;
86
import graphql.schema.DataFetchingEnvironment;
97
import java.nio.charset.StandardCharsets;
108
import java.util.ArrayList;
@@ -14,42 +12,38 @@
1412
/**
1513
* @author <a href="mailto:java.lang.RuntimeException@gmail.com">oEmbedler Inc.</a>
1614
*/
17-
public class SimpleListConnection {
15+
public abstract class SimpleListConnection<T> {
1816

1917
private static final String DUMMY_CURSOR_PREFIX = "simple-cursor";
20-
private final List<?> data;
18+
private final List<T> data;
2119

22-
public SimpleListConnection(List<?> data) {
20+
protected SimpleListConnection(List<T> data) {
2321
this.data = data;
2422
}
2523

26-
public <E extends EdgeObjectType> E createEdgeObject() {
27-
return (E) new EdgeObjectType();
28-
}
24+
public abstract <E extends EdgeObjectType<T>> E createEdgeObject();
2925

30-
public <E extends ConnectionObjectType> E createConnectionObject() {
31-
return (E) new ConnectionObjectType();
32-
}
26+
public abstract <C extends ConnectionObjectType<? extends EdgeObjectType<T>, ? extends PageInfoObjectType>> C createConnectionObject();
3327

34-
private List<EdgeObjectType> buildEdges() {
35-
List<EdgeObjectType> edges = new ArrayList<>();
28+
private List<EdgeObjectType<T>> buildEdges() {
29+
List<EdgeObjectType<T>> edges = new ArrayList<>();
3630
int ix = 0;
37-
for (Object object : data) {
38-
EdgeObjectType edge = createEdgeObject();
31+
for (T object : data) {
32+
EdgeObjectType<T> edge = createEdgeObject();
3933
edge.setNode(object);
4034
edge.setCursor(createCursor(ix++));
4135
edges.add(edge);
4236
}
4337
return edges;
4438
}
4539

46-
public <C extends ConnectionObjectType> C get(DataFetchingEnvironment environment) {
47-
48-
List<EdgeObjectType> edges = buildEdges();
40+
public <C extends ConnectionObjectType<? extends EdgeObjectType<T>, ? extends PageInfoObjectType>> C get(
41+
DataFetchingEnvironment environment) {
42+
List<EdgeObjectType<T>> edges = buildEdges();
4943

50-
int afterOffset = getOffsetFromCursor(environment.<String>getArgument("after"), -1);
44+
int afterOffset = getOffsetFromCursor(environment.getArgument("after"), -1);
5145
int begin = Math.max(afterOffset, -1) + 1;
52-
int beforeOffset = getOffsetFromCursor(environment.<String>getArgument("before"), edges.size());
46+
int beforeOffset = getOffsetFromCursor(environment.getArgument("before"), edges.size());
5347
int end = Math.min(beforeOffset, edges.size());
5448

5549
edges = edges.subList(begin, end);
@@ -74,34 +68,30 @@ public <C extends ConnectionObjectType> C get(DataFetchingEnvironment environmen
7468
return emptyConnection();
7569
}
7670

77-
EdgeObjectType firstEdge = edges.get(0);
78-
EdgeObjectType lastEdge = edges.get(edges.size() - 1);
71+
EdgeObjectType<T> firstEdge = edges.get(0);
72+
EdgeObjectType<T> lastEdge = edges.get(edges.size() - 1);
7973

8074
PageInfoObjectType pageInfo = new PageInfoObjectType();
8175
pageInfo.setStartCursor(firstEdge.getCursor());
8276
pageInfo.setEndCursor(lastEdge.getCursor());
8377
pageInfo.setHasPreviousPage(!firstEdge.getCursor().equals(firstPresliceCursor));
8478
pageInfo.setHasNextPage(!lastEdge.getCursor().equals(lastPresliceCursor));
8579

86-
ConnectionObjectType connection = createConnectionObject();
80+
ConnectionObjectType<EdgeObjectType<T>, PageInfoObjectType> connection = createConnectionObject();
8781
connection.setEdges(edges);
8882
connection.setPageInfo(pageInfo);
8983

84+
//noinspection unchecked
9085
return (C) connection;
9186
}
9287

93-
private <E extends ConnectionObjectType> E emptyConnection() {
94-
ConnectionObjectType connection = createConnectionObject();
88+
private <E extends ConnectionObjectType<? extends EdgeObjectType<T>, ? extends PageInfoObjectType>> E emptyConnection() {
89+
ConnectionObjectType<EdgeObjectType<T>, PageInfoObjectType> connection = createConnectionObject();
9590
connection.setPageInfo(new PageInfoObjectType());
91+
//noinspection unchecked
9692
return (E) connection;
9793
}
9894

99-
public ConnectionCursor cursorForObjectInConnection(Object object) {
100-
int index = data.indexOf(object);
101-
String cursor = createCursor(index);
102-
return new DefaultConnectionCursor(cursor);
103-
}
104-
10595
private int getOffsetFromCursor(String cursor, int defaultValue) {
10696
if (cursor == null) {
10797
return defaultValue;
Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,28 @@
11
package graphql.kickstart.spring.web.boot.sample;
22

3-
import com.oembedler.moon.graphql.engine.relay.ConnectionObjectType;
4-
import com.oembedler.moon.graphql.engine.relay.EdgeObjectType;
53
import graphql.kickstart.spring.web.boot.sample.schema.objecttype.TodoObjectType;
4+
import graphql.kickstart.spring.web.boot.sample.schema.objecttype.TodoObjectType.TodoConnectionObjectType;
5+
import graphql.kickstart.spring.web.boot.sample.schema.objecttype.TodoObjectType.TodoEdgeObjectType;
66
import java.util.List;
77

88
/**
99
* @author <a href="mailto:java.lang.RuntimeException@gmail.com">oEmbedler Inc.</a>
1010
*/
11-
public class TodoSimpleListConnection extends SimpleListConnection {
11+
@SuppressWarnings("unchecked")
12+
public class TodoSimpleListConnection extends SimpleListConnection<TodoObjectType> {
1213

13-
public TodoSimpleListConnection(List<?> data) {
14+
public TodoSimpleListConnection(List<TodoObjectType> data) {
1415
super(data);
1516
}
1617

1718
@Override
18-
public <T extends EdgeObjectType> T createEdgeObject() {
19-
return (T) new TodoObjectType.TodoEdgeObjectType();
19+
public TodoEdgeObjectType createEdgeObject() {
20+
return new TodoObjectType.TodoEdgeObjectType();
2021
}
2122

2223
@Override
23-
public <T extends ConnectionObjectType> T createConnectionObject() {
24-
return (T) new TodoObjectType.TodoConnectionObjectType();
24+
public TodoConnectionObjectType createConnectionObject() {
25+
return new TodoObjectType.TodoConnectionObjectType();
2526
}
2627

2728
}

graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/ReflectiveGraphQLErrorFactory.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,10 @@ public Optional<Class<? extends Throwable>> mostConcrete(Throwable t) {
3636
@Override
3737
public Collection<GraphQLError> create(Throwable t, ErrorContext errorContext) {
3838
try {
39-
method.setAccessible(true);
4039
if (singularReturnType) {
4140
return singletonList((GraphQLError) invoke(t, errorContext));
4241
}
42+
//noinspection unchecked
4343
return (Collection<GraphQLError>) invoke(t, errorContext);
4444
} catch (IllegalAccessException | InvocationTargetException e) {
4545
log.error("Cannot create GraphQLError from throwable {}", t.getClass().getSimpleName(), e);

graphql-spring-boot-test/build.gradle

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ dependencies {
2121
implementation("org.springframework.boot:spring-boot-starter-test")
2222
implementation("com.fasterxml.jackson.core:jackson-databind")
2323
implementation("com.jayway.jsonpath:json-path")
24+
implementation 'org.awaitility:awaitility:4.0.3'
2425
compileOnly("com.graphql-java:graphql-java:$LIB_GRAPHQL_JAVA_VER")
2526
compileOnly("com.graphql-java-kickstart:graphql-java-servlet:$LIB_GRAPHQL_SERVLET_VER")
2627
testImplementation("org.springframework.boot:spring-boot-starter-web")

graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestSubscription.java

Lines changed: 45 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.graphql.spring.boot.test;
22

33
import static org.assertj.core.api.Assertions.assertThat;
4+
import static org.awaitility.Awaitility.await;
45
import static org.junit.jupiter.api.Assertions.fail;
56

67
import com.fasterxml.jackson.core.JsonProcessingException;
@@ -18,6 +19,7 @@
1819
import java.util.Map;
1920
import java.util.Optional;
2021
import java.util.Queue;
22+
import java.util.concurrent.TimeUnit;
2123
import java.util.concurrent.atomic.AtomicInteger;
2224
import java.util.function.Predicate;
2325
import javax.websocket.ClientEndpointConfig;
@@ -49,7 +51,6 @@ public class GraphQLTestSubscription {
4951

5052
private static final WebSocketContainer WEB_SOCKET_CONTAINER = ContainerProvider
5153
.getWebSocketContainer();
52-
private static final int SLEEP_INTERVAL_MS = 100;
5354
private static final int ACKNOWLEDGEMENT_AND_CONNECTION_TIMEOUT = 60000;
5455
private static final AtomicInteger ID_COUNTER = new AtomicInteger(1);
5556
private static final UriBuilderFactory URI_BUILDER_FACTORY = new DefaultUriBuilderFactory();
@@ -298,18 +299,11 @@ public List<GraphQLResponse> awaitAndGetNextResponses(
298299
if (isStopped()) {
299300
fail("Subscription already stopped. Forgot to call reset after test case?");
300301
}
301-
int elapsedTime = 0;
302-
while (
303-
((state.getResponses().size() < numExpectedResponses) || numExpectedResponses <= 0)
304-
&& elapsedTime < timeout
305-
) {
306-
try {
307-
Thread.sleep(SLEEP_INTERVAL_MS);
308-
elapsedTime += SLEEP_INTERVAL_MS;
309-
} catch (InterruptedException e) {
310-
fail("Test execution error - Thread.sleep failed.", e);
311-
}
312-
}
302+
303+
await()
304+
.atMost(timeout, TimeUnit.MILLISECONDS)
305+
.until(() -> hasReachedExpectedResponses(numExpectedResponses));
306+
313307
if (stopAfter) {
314308
stop();
315309
}
@@ -340,6 +334,10 @@ public List<GraphQLResponse> awaitAndGetNextResponses(
340334
}
341335
}
342336

337+
private boolean hasReachedExpectedResponses(int numExpectedResponses) {
338+
return (state.getResponses().size() < numExpectedResponses) || numExpectedResponses <= 0;
339+
}
340+
343341
/**
344342
* Waits a specified amount of time and asserts that no responses were received during that time.
345343
*
@@ -420,29 +418,20 @@ private void sendMessage(final Object message) {
420418
}
421419

422420
private void awaitAcknowledgement() {
423-
await(GraphQLTestSubscription::isAcknowledged,
421+
awaitAcknowledgementOrConnection(GraphQLTestSubscription::isAcknowledged,
424422
"Connection was not acknowledged by the GraphQL server.");
425423
}
426424

427425
private void awaitStop() {
428-
await(GraphQLTestSubscription::isStopped, "Connection was not stopped in time.");
426+
awaitAcknowledgementOrConnection(GraphQLTestSubscription::isStopped,
427+
"Connection was not stopped in time.");
429428
}
430429

431-
private void await(final Predicate<GraphQLTestSubscription> condition,
430+
private void awaitAcknowledgementOrConnection(final Predicate<GraphQLTestSubscription> condition,
432431
final String timeoutDescription) {
433-
int elapsedTime = 0;
434-
while (!condition.test(this) && elapsedTime < ACKNOWLEDGEMENT_AND_CONNECTION_TIMEOUT) {
435-
try {
436-
Thread.sleep(SLEEP_INTERVAL_MS);
437-
elapsedTime += SLEEP_INTERVAL_MS;
438-
} catch (InterruptedException e) {
439-
fail("Test execution error - Thread.sleep failed.", e);
440-
}
441-
}
442-
443-
if (!condition.test(this)) {
444-
fail("Timeout: " + timeoutDescription);
445-
}
432+
await(timeoutDescription)
433+
.atMost(ACKNOWLEDGEMENT_AND_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
434+
.until(() -> condition.test(this));
446435
}
447436

448437
@RequiredArgsConstructor
@@ -460,28 +449,34 @@ public void onMessage(final String message) {
460449
assertThat(typeNode).as("GraphQL messages should have a type field.").isNotNull();
461450
assertThat(typeNode.isNull()).as("GraphQL messages type should not be null.").isFalse();
462451
final String type = typeNode.asText();
463-
if (type.equals("complete")) {
464-
state.setCompleted(true);
465-
log.debug("Subscription completed.");
466-
} else if (type.equals("connection_ack")) {
467-
state.setAcknowledged(true);
468-
log.debug("WebSocket connection acknowledged by the GraphQL Server.");
469-
} else if (type.equals("data") || type.equals("error")) {
470-
final JsonNode payload = jsonNode.get(PAYLOAD);
471-
assertThat(payload).as("Data/error messages must have a payload.").isNotNull();
472-
final String payloadString = objectMapper.writeValueAsString(payload);
473-
final GraphQLResponse graphQLResponse = new GraphQLResponse(
474-
ResponseEntity.ok(payloadString),
475-
objectMapper);
476-
if (state.isStopped() || state.isCompleted()) {
477-
log.debug(
478-
"Response discarded because subscription was stopped or completed in the meanwhile.");
479-
} else {
480-
synchronized (STATE_LOCK) {
481-
state.getResponses().add(graphQLResponse);
452+
switch (type) {
453+
case "complete":
454+
state.setCompleted(true);
455+
log.debug("Subscription completed.");
456+
break;
457+
case "connection_ack":
458+
state.setAcknowledged(true);
459+
log.debug("WebSocket connection acknowledged by the GraphQL Server.");
460+
break;
461+
case "data":
462+
case "error":
463+
default:
464+
final JsonNode payload = jsonNode.get(PAYLOAD);
465+
assertThat(payload).as("Data/error messages must have a payload.").isNotNull();
466+
final String payloadString = objectMapper.writeValueAsString(payload);
467+
final GraphQLResponse graphQLResponse = new GraphQLResponse(
468+
ResponseEntity.ok(payloadString),
469+
objectMapper);
470+
if (state.isStopped() || state.isCompleted()) {
471+
log.debug(
472+
"Response discarded because subscription was stopped or completed in the meanwhile.");
473+
} else {
474+
synchronized (STATE_LOCK) {
475+
state.getResponses().add(graphQLResponse);
476+
}
477+
log.debug("New response recorded.");
482478
}
483-
log.debug("New response recorded.");
484-
}
479+
break;
485480
}
486481
} catch (JsonProcessingException e) {
487482
fail("Exception while parsing server response. Response is not a valid GraphQL response.",

graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestTemplate.java

Lines changed: 0 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -73,17 +73,6 @@ private String loadResource(Resource resource) throws IOException {
7373
}
7474
}
7575

76-
/**
77-
* @param name Name (key) of HTTP header to add.
78-
* @param value Value of HTTP header to add.
79-
* @deprecated use {{@link #withAdditionalHeader(String, String...)}} instead Add an HTTP header
80-
* that will be sent with each request this sends.
81-
*/
82-
@Deprecated
83-
public void addHeader(final String name, final String value) {
84-
withAdditionalHeader(name, value);
85-
}
86-
8776
/**
8877
* Add an HTTP header that will be sent with each request this sends.
8978
*
@@ -160,16 +149,6 @@ public GraphQLTestTemplate withBasicAuth(@NonNull final String encodedCredential
160149
return this;
161150
}
162151

163-
/**
164-
* @param newHeaders Headers to use.
165-
* @deprecated use {{@link #withHeaders(HttpHeaders)}} instead. Replace any associated HTTP
166-
* headers with the provided headers.
167-
*/
168-
@Deprecated
169-
public void setHeaders(HttpHeaders newHeaders) {
170-
withHeaders(newHeaders);
171-
}
172-
173152
/**
174153
* Replace any associated HTTP headers with the provided headers.
175154
*
@@ -180,14 +159,6 @@ public GraphQLTestTemplate withHeaders(final HttpHeaders newHeaders) {
180159
return withClearHeaders().withAdditionalHeaders(newHeaders);
181160
}
182161

183-
/**
184-
* @deprecated use {{@link #withClearHeaders()}} instead Clear all associated HTTP headers.
185-
*/
186-
@Deprecated
187-
public void clearHeaders() {
188-
withClearHeaders();
189-
}
190-
191162
/**
192163
* Clear all associated HTTP headers.
193164
*
@@ -198,20 +169,6 @@ public GraphQLTestTemplate withClearHeaders() {
198169
return this;
199170
}
200171

201-
/**
202-
* Loads a GraphQL query or mutation from the given classpath resource and sends it to the GraphQL
203-
* server.
204-
*
205-
* @param graphqlResource path to the classpath resource containing the GraphQL query
206-
* @return {@link GraphQLResponse} containing the result of query execution
207-
* @throws IOException if the resource cannot be loaded from the classpath
208-
* @deprecated Use {@link #postForResource(String)} instead
209-
*/
210-
@Deprecated
211-
public GraphQLResponse perform(String graphqlResource) throws IOException {
212-
return postForResource(graphqlResource);
213-
}
214-
215172
/**
216173
* Loads a GraphQL query or mutation from the given classpath resource and sends it to the GraphQL
217174
* server.

0 commit comments

Comments
 (0)