Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply idea code analysis suggestions Http module #2185

Merged
merged 1 commit into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,11 @@ public Uni<GrpcReflectionResponse> reflectionServiceInfo() {
.setListServices("").build();
Uni<ServerReflectionResponse> serverReflectionResponse = invoke(request);

Uni<GrpcReflectionResponse> grpcReflectionResponse = serverReflectionResponse.map(response -> {
return serverReflectionResponse.map(response -> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Personally I most like original version, it is easier to read what method returns. But I haven't a strong opinion on this

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMHO this method is short and what is returned is easily readable in method declaration. IMHO that is sufficient. But I also have no strong opinion.

int serviceCount = response.getListServicesResponse().getServiceCount();
List<String> reflectionServiceList = getReflectionServiceList(response);
return new GrpcReflectionResponse(serviceCount, reflectionServiceList);
});

return grpcReflectionResponse;
}

@GET
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package io.quarkus.ts.http.grpc;

import static io.quarkus.test.security.certificate.CertificateBuilder.INSTANCE_KEY;
import static io.quarkus.test.services.Certificate.Format.PEM;

import org.junit.jupiter.api.Tag;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,7 @@ public String createCity(CityListDTO cityListDTO) {
.build().toString();
}

String responseXML = serializer.toXML(cityListDTO);

return responseXML;
return serializer.toXML(cityListDTO);
}

@POST
Expand All @@ -94,13 +92,13 @@ public Response handleDTOYamlPostRequest(CityListDTO cityListDTO) {
@GET
@Path("/getYamlFile")
@Produces("application/yaml")
public Response getYamlFile() throws IOException {
public Response getYamlFile() {

try {
CityListDTO cityListDTO = readYamlFile(YAML_FILE_PATH);

if (cityListDTO != null) {
LOG.info("content ----! " + cityListDTO.toString());
LOG.info("content ----! " + cityListDTO);
return Response.ok(cityListDTO).build();
} else {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class DownloadResource {

private static final Logger LOGGER = LoggerFactory.getLogger(DownloadResource.class);
private static final String TEST_FILE = System.getProperty("java.io.tmpdir") +
File.separator + "DownloadResource-" + UUID.randomUUID().toString() + "-test.txt";
File.separator + "DownloadResource-" + UUID.randomUUID() + "-test.txt";
private static final OpenOptions READ_ONLY = new OpenOptions().setWrite(false).setCreate(false);

@Inject
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.htmlunit.WebClient;
Expand Down Expand Up @@ -67,7 +66,7 @@ public void uiChange() throws IOException {
.lines(app.getServiceFolder().resolve("src/main/resources/application.properties"))) {
List<String> properties = lines
.filter(line -> line.contains(PROPERTY))
.collect(Collectors.toList());
.toList();
if (properties.size() != 1) {
LOG.warn("There should be only one property with name " + PROPERTY + ", but found these " + properties);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ public void nonAppRedirections() {
}

@Test
public void microprofileHttpClientRedirection() throws Exception {
public void microprofileHttpClientRedirection() {
io.restassured.response.Response health = getApp().given().get("api/client");
assertEquals(HttpStatus.SC_OK, health.statusCode());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,17 +58,17 @@ public void checkTextPlainDefaultWithoutBrotli4JEncoding() {
}

@Test
public void checkTextPlainWithtBrotli4J() {
int textPlainDataLenght = calculateTextLength("/sample.txt");
public void checkTextPlainWithBrotli4J() {
int textPlainDataLength = calculateTextLength("/sample.txt");
assertBrotli4JCompression("/compression/text", MediaType.TEXT_PLAIN, BROTLI_ENCODING, BROTLI_ENCODING,
textPlainDataLenght);
textPlainDataLength);
}

@Test
public void checkBigTextPlainWithtBrotli4J() {
int textPlainDataLenght = calculateTextLength("/big_sample.txt");
public void checkBigTextPlainWithBrotli4J() {
int textPlainDataLength = calculateTextLength("/big_sample.txt");
assertBrotli4JCompression("/compression/text/big", MediaType.TEXT_PLAIN, BROTLI_ENCODING, BROTLI_ENCODING,
textPlainDataLenght);
textPlainDataLength);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package io.quarkus.ts.http.advanced.reactive;

import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
Expand Down Expand Up @@ -52,7 +51,7 @@ void ensureAsyncFileGetsClosed() throws IOException {
.then()
.statusCode(204);

Assert.assertEquals("AsyncFile is not closed, details:\n" + lsofOutput + "\n", 0, lsofOutput.length());
assertEquals(0, lsofOutput.length(), "AsyncFile is not closed, details:\n" + lsofOutput + "\n");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import java.util.Map;

import jakarta.ws.rs.core.MediaType;
import jakarta.xml.bind.JAXBException;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpStatus;
Expand Down Expand Up @@ -67,7 +66,7 @@ public void testExpectedXmlResponse() {
}

@Test
public void testXMLPayloadPostRequest() throws JAXBException {
public void testXMLPayloadPostRequest() {

City city = new City("Paris", "France");
List<City> cityList = new ArrayList<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@ public String xmlHttpCompressionResponse() {
@Path("/decompression")
@Produces(MediaType.TEXT_PLAIN)
public String decompressionHttpResponse(byte[] compressedData) {
String decompressedData = new String(compressedData);
return decompressedData;
return new String(compressedData);
}

@GET
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ abstract static class Base implements ClientInterceptor {
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions options,
Channel next) {
String interceptedTarget = getClass().getName();
return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, options)) {
return new ForwardingClientCall.SimpleForwardingClientCall<>(next.newCall(method, options)) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
if (interceptedTarget.contains("MethodTarget")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ abstract static class Base implements ServerInterceptor {
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata metadata,
ServerCallHandler<ReqT, RespT> next) {
Context ctx = null;
Context ctx;
String interceptedTarget = getClass().getName();
// Determine where was grpc call intercepted and put client side intercepted data to Context.
if (interceptedTarget.contains("MethodTarget")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public void ensureApplicationStartsWithDomainSocketConfigured() {
}

@Test
public void ensureApplicationProvidesContent() throws InterruptedException {
public void ensureApplicationProvidesContent() {
Vertx vertx = Vertx.vertx(new VertxOptions().setPreferNativeTransport(true));
WebClient client = WebClient.create(vertx, new WebClientOptions().setFollowRedirects(false));
SocketAddress serverAddress = SocketAddress.domainSocketAddress("/tmp/io.quarkus.app.socket");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,15 @@ void sendInvalidContent() {
}

@Test
void sendZeroBytesPayload() throws IOException {
void sendZeroBytesPayload() {
ByteArrayInputStream compressedData = generateCompressedDataStream(0);
Response response = sendDataToGzipEndpoint(compressedData);
assertEquals(HttpStatus.SC_OK, response.statusCode(),
"The response should be 200 OK because the compression returns 2 bytes");
}

@Test
void sendPayloadBelowMaxInputLimit() throws IOException {
void sendPayloadBelowMaxInputLimit() {
ByteArrayInputStream compressedData = generateCompressedDataStream(SMALL_PAYLOAD);
Response response = sendDataToGzipEndpoint(compressedData);
assertEquals(HttpStatus.SC_OK, response.statusCode(),
Expand All @@ -91,7 +91,7 @@ void sendPayloadBelowMaxInputLimit() throws IOException {

@Tag("https://github.com/quarkusio/quarkus/issues/39636")
@Test
void sendMaximumAllowedPayload() throws IOException {
void sendMaximumAllowedPayload() {
ByteArrayInputStream compressedData = generateCompressedDataStream(LIMIT_PAYLOAD);
Response response = sendDataToGzipEndpoint(compressedData);
assertEquals(HttpStatus.SC_OK, response.statusCode(),
Expand All @@ -101,7 +101,7 @@ void sendMaximumAllowedPayload() throws IOException {
}

@Test
void sendMoreThanMaximumAllowedPayload() throws IOException {
void sendMoreThanMaximumAllowedPayload() {
ByteArrayInputStream compressedData = generateCompressedDataStream(OVER_LIMIT_PAYLOAD);
Response response = sendDataToGzipEndpoint(compressedData);
assertEquals(HttpStatus.SC_REQUEST_TOO_LONG, response.statusCode(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ private GenerateLargeFile() {
public static void main(String[] args) throws Exception {
// args[0] is expected to be something like {path to repository}/http/http-static/target/classes

try (RandomAccessFile f = new RandomAccessFile(args[0] + "/META-INF/resources/big-file", "rw");) {
try (RandomAccessFile f = new RandomAccessFile(args[0] + "/META-INF/resources/big-file", "rw")) {
f.setLength(HALF_GIGABYTE);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ public Uni<String> forceNoCompression(RoutingContext rc) {
@Path("/big/payload")
@Compressed
public Uni<byte[]> bigCompression(@RestQuery("bodyCharSize") String bodyCharSize) {
byte[] payload = new byte[Integer.valueOf(bodyCharSize)];
byte[] payload = new byte[Integer.parseInt(bodyCharSize)];
new Random().nextBytes(payload);
LOG.info("Big compression payload generated.");
return Uni.createFrom().item(payload);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public byte[] postFormReturnData(@MultipartForm MultipartBody multipartBody) thr
@Path("/echo")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public String echo(String requestBody) throws Exception {
public String echo(String requestBody) {
return requestBody;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import static org.junit.jupiter.api.Assertions.assertFalse;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ValidationAssertions {
Expand All @@ -31,7 +30,7 @@ public static final void assertValidationErrorCount(ValidationErrorResponse resp

public static final void assertValidationErrorField(ValidationErrorResponse response, String fieldName, String message) {
List<ValidationError> violations = Stream.of(response.getViolations()).filter(v -> fieldName.equals(v.getField()))
.collect(Collectors.toList());
.toList();
assertFalse(violations.isEmpty(), "No violations found for field: " + fieldName);
assertEquals(1, violations.size(), "More than one violation found for field: " + fieldName);
assertEquals(message, violations.get(0).getMessage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class RequestIdContainerRequestFilter implements ContainerRequestFilter {
public void filter(ContainerRequestContext requestContext) {
MultivaluedMap<String, String> headers = requestContext.getHeaders();
if (headers.containsKey("REQUEST_ID")) {
int requestId = Integer.valueOf(headers.getFirst("REQUEST_ID"));
int requestId = Integer.parseInt(headers.getFirst("REQUEST_ID"));
requestIdManagerImpl.overrideRequestId(requestId);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package io.quarkus.ts.http.restclient.reactive.files;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import jakarta.xml.bind.DatatypeConverter;

class JavaUtils extends OsUtils {

@Override
public String getSum(Path path) {
try {
final MessageDigest digest = MessageDigest.getInstance("MD5");
try (BufferedInputStream stream = new BufferedInputStream(Files.newInputStream(path))) {
DigestOutputStream digestStream = new DigestOutputStream(OutputStream.nullOutputStream(), digest);
stream.transferTo(digestStream);
return DatatypeConverter.printHexBinary(digest.digest()).toLowerCase();
} catch (IOException e) {
throw new IllegalStateException(e);
}
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}

@Override
public void createFile(Path path, long size) {
try (RandomAccessFile f = new RandomAccessFile(path.toAbsolutePath().toString(), "rw")) {
f.setLength(size);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,6 @@
package io.quarkus.ts.http.restclient.reactive.files;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import jakarta.xml.bind.DatatypeConverter;

public abstract class OsUtils {
public static final long SIZE_2049MiB = 2148532224L;
Expand All @@ -23,31 +13,3 @@ public static OsUtils get() {
return new JavaUtils();
}
}

class JavaUtils extends OsUtils {

@Override
public String getSum(Path path) {
try {
final MessageDigest digest = MessageDigest.getInstance("MD5");
try (BufferedInputStream stream = new BufferedInputStream(Files.newInputStream(path))) {
DigestOutputStream digestStream = new DigestOutputStream(OutputStream.nullOutputStream(), digest);
stream.transferTo(digestStream);
return DatatypeConverter.printHexBinary(digest.digest()).toLowerCase();
} catch (IOException e) {
throw new IllegalStateException(e);
}
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}

@Override
public void createFile(Path path, long size) {
try (RandomAccessFile f = new RandomAccessFile(path.toAbsolutePath().toString(), "rw");) {
f.setLength(size);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package io.quarkus.ts.http.restclient.reactive.filter;

import java.io.IOException;

import jakarta.ws.rs.client.ClientRequestContext;
import jakarta.ws.rs.client.ClientRequestFilter;
import jakarta.ws.rs.container.ContainerRequestContext;
Expand All @@ -25,7 +23,7 @@ public void filter(ContainerRequestContext requestContext, ContainerResponseCont
}

@Override
public void filter(ClientRequestContext requestContext) throws IOException {
public void filter(ClientRequestContext requestContext) {
requestContext.getHeaders().add("clientFilter", "clientFilterInvoked");
}
}
Loading
Loading