Skip to content

Commit

Permalink
fixed many sonar lint findings
Browse files Browse the repository at this point in the history
  • Loading branch information
mcs committed Dec 19, 2021
1 parent cf0f955 commit e453b32
Show file tree
Hide file tree
Showing 24 changed files with 105 additions and 110 deletions.
36 changes: 13 additions & 23 deletions .mvn/wrapper/MavenWrapperDownloader.java
Expand Up @@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.net.*;
import java.io.*;
import java.nio.channels.*;
Expand All @@ -25,7 +26,7 @@ public class MavenWrapperDownloader {
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";

/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
Expand Down Expand Up @@ -54,33 +55,22 @@ public static void main(String args[]) {
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
if (mavenWrapperPropertyFile.exists()) {
try (FileInputStream mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile)) {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);

File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
Expand All @@ -106,12 +96,12 @@ protected PasswordAuthentication getPasswordAuthentication() {
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
try (
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination)
) {
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}
}

}
5 changes: 2 additions & 3 deletions src/main/java/kafdrop/Kafdrop.java
Expand Up @@ -43,7 +43,7 @@

@SpringBootApplication
public class Kafdrop {
private final static Logger LOG = LoggerFactory.getLogger(Kafdrop.class);
private static final Logger LOG = LoggerFactory.getLogger(Kafdrop.class);

public static void main(String[] args) {
createApplicationBuilder()
Expand Down Expand Up @@ -99,8 +99,7 @@ public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
try {
System.setProperty("logging.dir", new File(loggingFile).getParent());
} catch (Exception ex) {
System.err.println("Unable to set up logging.dir from logging.file " + loggingFile + ": " +
Throwables.getStackTraceAsString(ex));
LOG.error("Unable to set up logging.dir from logging.file {}", loggingFile, ex);
}
}
if (environment.containsProperty("debug") &&
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/kafdrop/config/CorsConfiguration.java
Expand Up @@ -69,6 +69,7 @@ public Filter corsFilter() {
return new Filter() {
@Override
public void init(FilterConfig filterConfig) {
// nothing to init
}

@Override
Expand All @@ -91,6 +92,7 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)

@Override
public void destroy() {
// nothing to destroy
}
};
}
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/kafdrop/config/HealthCheckConfiguration.java
Expand Up @@ -38,15 +38,15 @@ public HealthCheck(HealthEndpoint healthEndpoint) {
}

@ManagedAttribute
public Map getHealth() {
public Map<String, Object> getHealth() {
final var health = (Health) healthEndpoint.health();
final var healthMap = new LinkedHashMap<String, Object>();
healthMap.put("status", getStatus(health));
healthMap.put("detail", getDetails(health.getDetails()));
return healthMap;
}

private Map getDetails(Map<String, Object> details) {
private Map<String, Object> getDetails(Map<String, Object> details) {
return details.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e -> {
Expand Down
3 changes: 1 addition & 2 deletions src/main/java/kafdrop/config/InterceptorConfiguration.java
Expand Up @@ -22,7 +22,6 @@
import org.springframework.stereotype.*;
import org.springframework.web.servlet.*;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.*;

import javax.servlet.http.*;

Expand All @@ -39,7 +38,7 @@ public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ProfileHandlerInterceptor());
}

public class ProfileHandlerInterceptor extends HandlerInterceptorAdapter {
public class ProfileHandlerInterceptor implements AsyncHandlerInterceptor {
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
final var activeProfiles = environment.getActiveProfiles();
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/kafdrop/config/KafkaConfiguration.java
Expand Up @@ -17,7 +17,7 @@ public final class KafkaConfiguration {
private static final Logger LOG = LoggerFactory.getLogger(KafkaConfiguration.class);

private String brokerConnect;
private Boolean isSecured = false;
private boolean isSecured = false;
private String saslMechanism;
private String securityProtocol;
private String truststoreFile;
Expand Down
Expand Up @@ -7,6 +7,7 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -43,17 +44,10 @@ public List<String> getDescFilesList() {
File path = new File(directory);

// apply filter for listing only .desc file
FilenameFilter filter = new FilenameFilter() {

@Override
public boolean accept(File dir, String name) {
return name.endsWith(".desc");
}

};
FilenameFilter filter = (dir, name) -> name.endsWith(".desc");

pathnames = path.list(filter);
return Arrays.asList(pathnames);
return Arrays.asList(Objects.requireNonNull(pathnames));
}
}
}
10 changes: 6 additions & 4 deletions src/main/java/kafdrop/config/SwaggerConfiguration.java
Expand Up @@ -18,6 +18,7 @@

package kafdrop.config;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.*;
Expand All @@ -33,6 +34,7 @@

import java.lang.reflect.Field;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -60,7 +62,7 @@ public Docket swagger() {
/**
* Swagger Predicate for only selecting JSON endpoints.
*/
public final class JsonRequestHandlerPredicate implements Predicate<RequestHandler> {
public static final class JsonRequestHandlerPredicate implements Predicate<RequestHandler> {
@Override
public boolean test(RequestHandler input) {
return input.produces().contains(MediaType.APPLICATION_JSON);
Expand All @@ -70,7 +72,7 @@ public boolean test(RequestHandler input) {
/**
* Swagger Predicate for ignoring {@code /actuator} endpoints.
*/
public final class IgnoreDebugPathPredicate implements Predicate<String> {
public static final class IgnoreDebugPathPredicate implements Predicate<String> {
@Override
public boolean test(String input) {
return !input.startsWith("/actuator");
Expand All @@ -85,7 +87,7 @@ public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
return new BeanPostProcessor() {

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
public Object postProcessAfterInitialization(@NotNull Object bean, @NotNull String beanName) throws BeansException {
if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
}
Expand All @@ -104,7 +106,7 @@ private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHand
private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
try {
Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
field.setAccessible(true);
Objects.requireNonNull(field).setAccessible(true);
return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new IllegalStateException(e);
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/kafdrop/controller/AclController.java
Expand Up @@ -26,8 +26,8 @@
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
Expand All @@ -52,7 +52,7 @@ public String acls(Model model) {
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success", response = String.class, responseContainer = "List")
})
@RequestMapping(path = "/acl", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
@GetMapping(path = "/acl", produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody List<AclVO> getAllTopics() {
return kafkaMonitor.getAcls();
}
Expand Down
6 changes: 5 additions & 1 deletion src/main/java/kafdrop/controller/BasicErrorController.java
@@ -1,5 +1,7 @@
package kafdrop.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.servlet.error.*;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.*;
Expand All @@ -12,14 +14,16 @@

@Controller
public final class BasicErrorController extends AbstractErrorController {
private static final Logger LOG = LoggerFactory.getLogger(BasicErrorController.class);

public BasicErrorController(ErrorAttributes errorAttributes) {
super(errorAttributes);
}

@RequestMapping("/error")
public ModelAndView handleError(HttpServletRequest request) {
final var error = getErrorAttributes(request, ErrorAttributeOptions.of(ErrorAttributeOptions.Include.STACK_TRACE));
System.out.println("errorAtts: " + error);
LOG.info("errorAtts: {}", error);
final var model = Map.of("error", error);
return new ModelAndView("error", model);
}
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/kafdrop/controller/BrokerController.java
Expand Up @@ -49,7 +49,7 @@ public String brokerDetails(@PathVariable("id") int brokerId, Model model) {
@ApiResponse(code = 200, message = "Success", response = BrokerVO.class),
@ApiResponse(code = 404, message = "Invalid Broker ID")
})
@RequestMapping(path = "/broker/{id}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
@GetMapping(path = "/broker/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody BrokerVO brokerDetailsJson(@PathVariable("id") int brokerId) {
return kafkaMonitor.getBroker(brokerId).orElseThrow(() -> new BrokerNotFoundException("No such broker " + brokerId));
}
Expand All @@ -58,7 +58,7 @@ public String brokerDetails(@PathVariable("id") int brokerId, Model model) {
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success", response = BrokerVO.class)
})
@RequestMapping(path = "/broker", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
@GetMapping(path = "/broker", produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody List<BrokerVO> brokerDetailsJson() {
return kafkaMonitor.getBrokers();
}
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/kafdrop/controller/ClusterController.java
Expand Up @@ -30,7 +30,6 @@
import org.springframework.ui.*;
import org.springframework.web.bind.annotation.*;

import java.time.*;
import java.util.*;
import java.util.stream.*;

Expand Down Expand Up @@ -93,7 +92,7 @@ public String clusterInfo(Model model,
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success", response = ClusterInfoVO.class)
})
@RequestMapping(path = "/", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
@GetMapping(path = "/", produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ClusterInfoVO getCluster() {
final var vo = new ClusterInfoVO();
vo.brokers = kafkaMonitor.getBrokers();
Expand All @@ -112,6 +111,7 @@ public String brokerNotFound(Model model) {
@ResponseStatus(HttpStatus.OK)
@RequestMapping("/health_check")
public void healthCheck() {
// only http code shall be checked
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/kafdrop/controller/ConsumerController.java
Expand Up @@ -51,7 +51,7 @@ public String consumerDetail(@PathVariable("groupId") String groupId, Model mode
@ApiResponse(code = 200, message = "Success", response = ConsumerVO.class),
@ApiResponse(code = 404, message = "Invalid consumer group")
})
@RequestMapping(path = "/{groupId:.+}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
@GetMapping(path = "/{groupId:.+}", produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ConsumerVO getConsumer(@PathVariable("groupId") String groupId) throws ConsumerNotFoundException {
final var topicVos = kafkaMonitor.getTopics();
final var consumer = kafkaMonitor.getConsumers(topicVos)
Expand Down
10 changes: 4 additions & 6 deletions src/main/java/kafdrop/controller/MessageController.java
Expand Up @@ -36,8 +36,6 @@
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

Expand Down Expand Up @@ -210,7 +208,7 @@ private MessageFormat getSelectedMessageFormat(String format) {
@ApiResponse(code = 200, message = "Success", response = List.class),
@ApiResponse(code = 404, message = "Invalid topic name")
})
@RequestMapping(method = RequestMethod.GET, value = "/topic/{name:.+}/messages", produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping(value = "/topic/{name:.+}/messages", produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
List<Object> getPartitionOrMessages(
@PathVariable("name") String topicName,
Expand Down Expand Up @@ -264,10 +262,10 @@ private MessageDeserializer getDeserializer(String topicName, MessageFormat form
// filter the input file name

final var descFileName = descFile.replace(".desc", "")
.replaceAll("\\.", "")
.replaceAll("/", "");
.replace(".", "")
.replace("/", "");
final var fullDescFile = protobufProperties.getDirectory() + File.separator + descFileName + ".desc";
deserializer = new ProtobufMessageDeserializer(topicName, fullDescFile, msgTypeName);
deserializer = new ProtobufMessageDeserializer(fullDescFile, msgTypeName);
} else if (format == MessageFormat.PROTOBUF) {
final var schemaRegistryUrl = schemaRegistryProperties.getConnect();
final var schemaRegistryAuth = schemaRegistryProperties.getAuth();
Expand Down

0 comments on commit e453b32

Please sign in to comment.