Skip to content
Open
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 @@ -20,7 +20,6 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
Expand Down Expand Up @@ -94,8 +93,7 @@ private Path toPath(String templateName) {
private void init() {
try (Stream<Path> paths =
templateStore.walk(Path.of(""), 1, (path, pathAttributes) -> pathAttributes.isValue())) {
for (Iterator<Path> it = paths.iterator(); it.hasNext(); ) {
Path path = it.next();
for (Path path : paths.toList()) {

try {
Optional<Path> localPath = templateStore.asLocalPath(path, false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public CompletionStage<Void> onStart(boolean isStartupAsync) {
init();
} catch (Throwable ex) {
LogContext.error(LOGGER, ex, "Error during initializing of {}", appContext.getName());
System.exit(1);
return CompletableFuture.failedFuture(ex);
}

return CompletableFuture.completedFuture(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public class FallbackMustacheViewRenderer extends MustacheViewRenderer implement

@Inject
FallbackMustacheViewRenderer(MustacheResolverRegistry mustacheResolverRegistry) {
super();
this.mustacheResolverRegistry = mustacheResolverRegistry;
this.factories =
CacheBuilder.newBuilder()
Expand Down Expand Up @@ -97,7 +98,9 @@ public void configure(Map<String, String> options) {
useCache = Optional.ofNullable(options.get("cache")).map(Boolean::parseBoolean).orElse(true);
}

// @Override
@VisibleForTesting
@SuppressWarnings("PMD.MissingOverride")
boolean isUseCache() {
return useCache;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public void init(AppConfiguration configuration, Environment environment) {
volatileRegistry.listen(this::register, this::unregister);
}

// @Override
@Override
public void register(String name, HealthCheck check) {
if (!healthCheckRegistry.getNames().contains(name)) {
healthCheckRegistry.register(name, check);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,9 @@ private static InputStream getAsInputStream(CloseableHttpClient client, HttpUriR
}
}

try {
CloseableHttpResponse response = client.execute(request);
return response.getEntity().getContent();
try (CloseableHttpResponse response = client.execute(request)) {
byte[] content = EntityUtils.toByteArray(response.getEntity());
return new java.io.ByteArrayInputStream(content);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,21 +78,31 @@ public class JaxRsPlugin implements DropwizardPlugin {
// should be last
@Override
public int getPriority() {
return 10000;
return 10_000;
}

@Override
public void init(AppConfiguration configuration, Environment environment) {
JerseyEnvironment jersey = environment.jersey();

setupAuthProviders(jersey);
registerEndpoints(jersey);
registerFilters(jersey);
registerBinders(jersey);
registerExceptionMappers(jersey);
processConsumers(jersey);
}

private void setupAuthProviders(JerseyEnvironment jersey) {
for (AuthProvider<?> provider : authProviders.get()) {
if (!isAuthProviderAvailable) {
jersey.register(provider.getRolesAllowedDynamicFeature());
jersey.register(provider.getAuthValueFactoryProvider());
this.isAuthProviderAvailable = true;
}
if (LOGGER.isDebugEnabled(MARKER.DI))
if (LOGGER.isDebugEnabled(MARKER.DI)) {
LOGGER.debug(MARKER.DI, "Registered JAX-RS Auth Provider {}", provider.getClass());
}
}
if (isAuthProviderAvailable) {
List<AuthFilter> filters =
Expand All @@ -104,37 +114,57 @@ public void init(AppConfiguration configuration, Environment environment) {
jersey.register(
new WebApplicationExceptionCatchingFilterPreMatching(new ChainedAuthFilter<>(filters)));
}
}

private void registerEndpoints(JerseyEnvironment jersey) {
if (isAuthProviderAvailable && !endpoints.get().isEmpty()) {
for (Object resource : endpoints.get()) {
jersey.register(resource);
if (LOGGER.isDebugEnabled(MARKER.DI))
if (LOGGER.isDebugEnabled(MARKER.DI)) {
LOGGER.debug(MARKER.DI, "Registered JAX-RS Resource {}", resource.getClass());
}
}
} else if (!isAuthProviderAvailable && !endpoints.get().isEmpty()) {
if (LOGGER.isDebugEnabled(MARKER.DI))
LOGGER.debug(
MARKER.DI, "No JAX-RS Auth Provider registered yet, cannot register Resources.");
} else if (!isAuthProviderAvailable
&& !endpoints.get().isEmpty()
&& LOGGER.isDebugEnabled(MARKER.DI)) {
LOGGER.debug(MARKER.DI, "No JAX-RS Auth Provider registered yet, cannot register Resources.");
}
}

private void registerFilters(JerseyEnvironment jersey) {
for (ContainerRequestFilter filter : containerRequestFilters.get()) {
jersey.register(filter);
if (LOGGER.isDebugEnabled(MARKER.DI))
if (LOGGER.isDebugEnabled(MARKER.DI)) {
LOGGER.debug(MARKER.DI, "Registered JAX-RS ContainerRequestFilter {})", filter.getClass());
}
}
for (ContainerResponseFilter filter : containerResponseFilters.get()) {
jersey.register(filter);
if (LOGGER.isDebugEnabled(MARKER.DI))
if (LOGGER.isDebugEnabled(MARKER.DI)) {
LOGGER.debug(MARKER.DI, "Registered JAX-RS ContainerResponseFilter {})", filter.getClass());
}
}
}

private void registerBinders(JerseyEnvironment jersey) {
for (Binder binder : binders.get()) {
jersey.register(binder);
if (LOGGER.isDebugEnabled(MARKER.DI))
if (LOGGER.isDebugEnabled(MARKER.DI)) {
LOGGER.debug(MARKER.DI, "Registered JAX-RS Binder {}", binder.getClass());
}
}
}

private void registerExceptionMappers(JerseyEnvironment jersey) {
for (ExceptionMapper<?> exceptionMapper : exceptionMappers.get()) {
jersey.register(exceptionMapper);
if (LOGGER.isDebugEnabled(MARKER.DI))
if (LOGGER.isDebugEnabled(MARKER.DI)) {
LOGGER.debug(MARKER.DI, "Registered JAX-RS ExceptionMapper {}", exceptionMapper.getClass());
}
}
}

private void processConsumers(JerseyEnvironment jersey) {
for (JaxRsConsumer consumer : consumers.get()) {
if (consumer != null) {
consumer
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import javax.ws.rs.Consumes;
import javax.ws.rs.Priorities;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;
Expand All @@ -41,15 +40,15 @@ public class JsonProviderOptionalPretty extends JacksonJaxbJsonProvider
private final ObjectMapper mapperPretty;

public JsonProviderOptionalPretty(ObjectMapper mapper) {
super();
this.mapper = mapper;
this.mapperPretty = mapper.copy().enable(SerializationFeature.INDENT_OUTPUT);

setMapper(mapper);
}

@Override
public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext)
throws IOException, WebApplicationException {
public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException {
// check if the request context has the JSON pretty property set
if (JsonPretty.isJsonPretty(writerInterceptorContext)) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ public void init(AppConfiguration configuration, Environment environment) {

@Override
public void execute(Map<String, List<String>> parameters, PrintWriter output) throws Exception {
if (LOGGER.isTraceEnabled()) LOGGER.trace("Log filter request: {}", parameters);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Log filter request: {}", parameters);
}

Optional<LoggingFilter> optionalThirdPartyLoggingFilter =
loggerContext.getTurboFilterList().stream()
Expand All @@ -66,6 +68,7 @@ public void execute(Map<String, List<String>> parameters, PrintWriter output) th
});
}

@SuppressWarnings("PMD.CyclomaticComplexity")
private void setFilter(LoggingFilter loggingFilter, String filter, boolean enable) {
switch (filter) {
case "apiRequests":
Expand Down Expand Up @@ -106,6 +109,8 @@ private void setFilter(LoggingFilter loggingFilter, String filter, boolean enabl
loggingFilter.setConfigDumps(enable);
loggingFilter.setStackTraces(enable);
break;
default:
break;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import javax.ws.rs.NotFoundException;

/** Helper methods for dealing with {@link URL} objects for local resources. */
public class ResourceURL {
public final class ResourceURL {
private ResourceURL() {
/* singleton */
}
Expand Down Expand Up @@ -59,11 +59,12 @@ public static boolean isDirectory(URL resourceURL) throws URISyntaxException {
filename =
filename.substring(
filename.indexOf('!') + 2); // leaves just the relative file path inside the jar
@SuppressWarnings("PMD.CloseResource")
final JarFile jarFile = jarConnection.getJarFile();
final ZipEntry zipEntry = jarFile.getEntry(filename);
final InputStream inputStream = jarFile.getInputStream(zipEntry);

return (inputStream == null);
try (InputStream inputStream = jarFile.getInputStream(zipEntry)) {
return inputStream == null;
}
} catch (IOException e) {
throw new NotFoundException(e);
}
Expand Down Expand Up @@ -91,8 +92,8 @@ public static URL appendTrailingSlash(URL originalURL) {
originalURL.getHost(),
originalURL.getPort(),
originalURL.getFile() + '/');
} catch (MalformedURLException ignored) { // shouldn't happen
throw new IllegalArgumentException("Invalid resource URL: " + originalURL);
} catch (MalformedURLException e) { // shouldn't happen
throw new IllegalArgumentException("Invalid resource URL: " + originalURL, e);
}
}

Expand All @@ -107,6 +108,7 @@ public static URL appendTrailingSlash(URL originalURL) {
* @return the last modified time of the resource, expressed as the number of milliseconds since
* the epoch, or 0 if there was a problem
*/
@SuppressWarnings("PMD.CyclomaticComplexity")
public static long getLastModified(URL resourceURL) {
final String protocol = resourceURL.getProtocol();
switch (protocol) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,11 @@
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.StreamingOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* @author zahnen
Expand All @@ -45,7 +42,7 @@
@Instantiate*/
public class RobotsServlet extends HttpServlet implements ContainerResponseFilter {

private static final Logger LOGGER = LoggerFactory.getLogger(RobotsServlet.class);
private static final long serialVersionUID = 1L;

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
Expand All @@ -69,7 +66,7 @@ public void filter(
StreamingOutput stream =
new StreamingOutput() {
@Override
public void write(OutputStream output) throws IOException, WebApplicationException {
public void write(OutputStream output) throws IOException {
writeContent(output);
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ public void init(AppConfiguration configuration, Environment environment) {
}

@Override
@SuppressWarnings("PMD.UselessParentheses")
public boolean handle(String path, HttpServletRequest request, HttpServletResponse response) {
for (String prefix : servlets.keySet()) {
if (path.startsWith(prefix) || ("/" + path).startsWith(prefix)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public interface StaticResourceConstants {
long CACHE_TIMEOUT_DISABLED = -1L;

/** Default cache timeout to use. */
long ONE_WEEK_IN_SECONDS = 604800L;
long ONE_WEEK_IN_SECONDS = 604_800L;

/** Key used for the contextId */
String CONTEXTID = "ContextId";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ public WebApplicationExceptionCatchingFilterPreMatching(ContainerRequestFilter u
this.underlying = underlying;
}

@Override
@SuppressWarnings("PMD.EmptyCatchBlock")
public void filter(ContainerRequestContext requestContext) throws IOException {
try {
this.underlying.filter(requestContext);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,12 @@ public CompletionStage<Void> onStart(boolean isStartupAsync) {
try {
server.get().start();

LOGGER.info("Started web server at {}", appContext.getUri());
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Started web server at {}", appContext.getUri());
}
} catch (Throwable ex) {
LogContext.error(LOGGER, ex, "Error starting {}", appContext.getName());
System.exit(1);
return CompletableFuture.failedFuture(ex);
}

return CompletableFuture.completedFuture(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,6 @@

public interface JsonPretty {

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface JsonPrettify {}

String JSON_PRETTY_HEADER = "x-ldproxy-json-pretty";

Annotation JSON_PRETTY_ANNOTATION =
Expand All @@ -33,13 +29,17 @@ public Class<? extends Annotation> annotationType() {
}
};

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface JsonPrettify {}

static boolean isJsonPretty(WriterInterceptorContext writerInterceptorContext) {
Object headerValue = writerInterceptorContext.getProperty(JSON_PRETTY_HEADER);

return headerValue instanceof String && "true".equalsIgnoreCase((String) headerValue);
}

static boolean isJsonPretty(Annotation[] annotations) {
static boolean isJsonPretty(Annotation... annotations) {
return annotations != null
&& Arrays.stream(annotations).anyMatch(annotation -> annotation instanceof JsonPrettify);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public interface LoginHandler {
String PARAM_LOGOUT_REDIRECT_URI = "post_logout_redirect_uri";
String PARAM_LOGOUT_CLIENT_ID = "client_id";

@SuppressWarnings("PMD.UseObjectForClearerAPI")
Response handle(
ContainerRequestContext containerRequestContext,
String redirectUri,
Expand Down
Loading