aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/juick/config
diff options
context:
space:
mode:
authorGravatar Vitaly Takmazov2023-01-18 20:39:41 +0300
committerGravatar Vitaly Takmazov2023-01-19 14:30:01 +0300
commit12e2206f9d24b29c8276b2743603635620643444 (patch)
tree3af762f3fa6a1ce016df219fb88ab2b394ba35bb /src/main/java/com/juick/config
parent5b0f0bebda5d6369111ae35f8c335324ffa4cc7e (diff)
RestTemplate -> OkHttpClient
Diffstat (limited to 'src/main/java/com/juick/config')
-rw-r--r--src/main/java/com/juick/config/ActivityPubClientConfig.java78
-rw-r--r--src/main/java/com/juick/config/ActivityPubClientErrorHandler.java42
-rw-r--r--src/main/java/com/juick/config/AppConfig.java4
-rw-r--r--src/main/java/com/juick/config/HttpClientConfig.java113
4 files changed, 42 insertions, 195 deletions
diff --git a/src/main/java/com/juick/config/ActivityPubClientConfig.java b/src/main/java/com/juick/config/ActivityPubClientConfig.java
deleted file mode 100644
index 7df8350e..00000000
--- a/src/main/java/com/juick/config/ActivityPubClientConfig.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2008-2023, Juick
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-package com.juick.config;
-
-import java.nio.charset.StandardCharsets;
-
-import javax.inject.Inject;
-
-import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.core.convert.ConversionService;
-import org.springframework.http.client.ClientHttpRequestFactory;
-import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
-import org.springframework.http.converter.StringHttpMessageConverter;
-import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
-import org.springframework.web.client.RestTemplate;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.juick.model.User;
-import com.juick.service.SignatureService;
-import com.juick.util.ActivityPubRequestInterceptor;
-import com.juick.www.api.activity.model.objects.Actor;
-
-@Configuration
-public class ActivityPubClientConfig {
- @Inject
- CloseableHttpClient httpClient;
- @Inject
- ObjectMapper jsonMapper;
- @Inject
- private ActivityPubClientErrorHandler activityPubClientErrorHandler;
- @Inject
- private SignatureService signatureService;
- @Inject
- private ConversionService conversionService;
- @Inject
- private User serviceUser;
-
- @Bean
- ClientHttpRequestFactory clientHttpRequestFactory() {
- var clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
- clientHttpRequestFactory.setHttpClient(httpClient);
- return clientHttpRequestFactory;
- }
-
- @Bean
- MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() {
- MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
- converter.setObjectMapper(jsonMapper);
- return converter;
- }
-
- @Bean
- RestTemplate restClient() {
- RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
- restTemplate.getMessageConverters().add(0, mappingJacksonHttpMessageConverter());
- restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
- restTemplate.setErrorHandler(activityPubClientErrorHandler);
- restTemplate.getInterceptors().add(new ActivityPubRequestInterceptor());
- return restTemplate;
- }
-}
diff --git a/src/main/java/com/juick/config/ActivityPubClientErrorHandler.java b/src/main/java/com/juick/config/ActivityPubClientErrorHandler.java
index 08b98c82..65b67110 100644
--- a/src/main/java/com/juick/config/ActivityPubClientErrorHandler.java
+++ b/src/main/java/com/juick/config/ActivityPubClientErrorHandler.java
@@ -18,33 +18,39 @@
package com.juick.config;
import com.juick.service.activities.DeleteUserEvent;
+import okhttp3.Interceptor;
+import okhttp3.Response;
+import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
-import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
-import org.springframework.http.client.ClientHttpResponse;
-import org.springframework.stereotype.Component;
-import org.springframework.web.client.DefaultResponseErrorHandler;
-import javax.inject.Inject;
import java.io.IOException;
-import java.net.URI;
-@Component
-public class ActivityPubClientErrorHandler extends DefaultResponseErrorHandler {
+public class ActivityPubClientErrorHandler implements Interceptor {
private static final Logger logger = LoggerFactory.getLogger("ActivityPub");
- @Inject
- private ApplicationEventPublisher applicationEventPublisher;
+ private final ApplicationEventPublisher applicationEventPublisher;
+
+ public ActivityPubClientErrorHandler(ApplicationEventPublisher applicationEventPublisher) {
+ this.applicationEventPublisher = applicationEventPublisher;
+ }
+
+ @NotNull
@Override
- public void handleError(URI contextUri, HttpMethod method, ClientHttpResponse response)
- throws IOException {
- if (response.getStatusCode().equals(HttpStatus.GONE)) {
- logger.warn("Server report {} is gone, deleting", contextUri.toASCIIString());
- applicationEventPublisher.publishEvent(new DeleteUserEvent(this, contextUri.toASCIIString()));
- } else {
- logger.warn("HTTP ERROR {} on {} : {}", response.getStatusCode().value(),
- contextUri.toASCIIString(), response.getStatusText());
+ public Response intercept(@NotNull Interceptor.Chain chain) throws IOException {
+ var request = chain.request();
+ var response = chain.proceed(request);
+ var url = request.url();
+ if (!response.isSuccessful()) {
+ if (response.code() == HttpStatus.GONE.value()) {
+ logger.warn("Server report {} is gone, deleting", url);
+ applicationEventPublisher.publishEvent(new DeleteUserEvent(this, url.toString()));
+ } else {
+ logger.warn("HTTP ERROR {} on {} : {}", response.code(),
+ url, response.body() != null ? response.body().string() : "");
+ }
}
+ return response;
}
}
diff --git a/src/main/java/com/juick/config/AppConfig.java b/src/main/java/com/juick/config/AppConfig.java
index c579c64c..32926bd1 100644
--- a/src/main/java/com/juick/config/AppConfig.java
+++ b/src/main/java/com/juick/config/AppConfig.java
@@ -34,7 +34,6 @@ import io.pebbletemplates.pebble.loader.Loader;
import io.pebbletemplates.spring.extension.SpringExtension;
import io.pebbletemplates.spring.servlet.PebbleViewResolver;
-import org.apache.commons.codec.CharEncoding;
import org.commonmark.ext.autolink.AutolinkExtension;
import org.commonmark.node.Link;
import org.commonmark.parser.Parser;
@@ -49,6 +48,7 @@ import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter;
import org.springframework.web.servlet.resource.ResourceUrlProvider;
+import java.nio.charset.StandardCharsets;
import java.util.Collections;
import javax.inject.Inject;
@@ -173,7 +173,7 @@ public class AppConfig {
PebbleViewResolver viewResolver = new PebbleViewResolver(pebbleEngine());
viewResolver.setPrefix("templates");
viewResolver.setSuffix(".html");
- viewResolver.setCharacterEncoding(CharEncoding.UTF_8);
+ viewResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
viewResolver.setExposeRequestAttributes(true);
return viewResolver;
}
diff --git a/src/main/java/com/juick/config/HttpClientConfig.java b/src/main/java/com/juick/config/HttpClientConfig.java
index 081e51dd..18b56293 100644
--- a/src/main/java/com/juick/config/HttpClientConfig.java
+++ b/src/main/java/com/juick/config/HttpClientConfig.java
@@ -17,110 +17,29 @@
package com.juick.config;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.hc.client5.http.ConnectionKeepAliveStrategy;
-import org.apache.hc.client5.http.config.RequestConfig;
-import org.apache.hc.client5.http.cookie.StandardCookieSpec;
-import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
-import org.apache.hc.client5.http.impl.classic.HttpClients;
-import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
-import org.apache.hc.core5.http.HeaderElement;
-import org.apache.hc.core5.http.HttpResponse;
-import org.apache.hc.core5.http.message.BasicHeaderElementIterator;
-import org.apache.hc.core5.http.protocol.HttpContext;
-import org.apache.hc.core5.util.TimeValue;
-import org.apache.hc.core5.util.Timeout;
+import com.juick.util.ActivityPubRequestInterceptor;
+import okhttp3.OkHttpClient;
+import okhttp3.logging.HttpLoggingInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-import org.springframework.scheduling.annotation.Scheduled;
-
-/**
- * - Uses a connection pool to re-use connections and save overhead of creating connections.
- * - Has a custom connection keep-alive strategy (to apply a default keep-alive if one isn't specified)
- * - Starts an idle connection monitor to continuously clean up stale connections.
- */
-@Configuration
-public class HttpClientConfig {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientConfig.class);
-
- // Determines the timeout in milliseconds until a connection is established.
- private static final int CONNECT_TIMEOUT = 30000;
-
- // The timeout when requesting a connection from the connection manager.
- private static final int REQUEST_TIMEOUT = 30000;
-
- // The timeout for waiting for data
- private static final int SOCKET_TIMEOUT = 60000;
-
- private static final int MAX_TOTAL_CONNECTIONS = 50;
- private static final int DEFAULT_KEEP_ALIVE_TIME_MILLIS = 20 * 1000;
- private static final int CLOSE_IDLE_CONNECTION_WAIT_TIME_SECS = 30;
-
- @Bean
- PoolingHttpClientConnectionManager poolingConnectionManager() {
- PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager();
- poolingConnectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS);
- return poolingConnectionManager;
- }
-
- @Bean
- ConnectionKeepAliveStrategy connectionKeepAliveStrategy() {
- return new ConnectionKeepAliveStrategy() {
- @Override
- public TimeValue getKeepAliveDuration(HttpResponse response, HttpContext context) {
- BasicHeaderElementIterator it = new BasicHeaderElementIterator
- (response.headerIterator("Keep-Alive"));
- while (it.hasNext()) {
- HeaderElement he = it.next();
- String param = he.getName();
- String value = he.getValue();
- if (value != null && param.equalsIgnoreCase("timeout")) {
- return TimeValue.of(Long.parseLong(value) * 1000, TimeUnit.MILLISECONDS);
- }
- }
- return TimeValue.of(DEFAULT_KEEP_ALIVE_TIME_MILLIS, TimeUnit.MILLISECONDS);
- }
- };
- }
+import javax.inject.Inject;
+@Configuration
+public class HttpClientConfig {
+ private final static Logger logger = LoggerFactory.getLogger("ActivityPub");
+ @Inject
+ ApplicationEventPublisher applicationEventPublisher;
@Bean
- CloseableHttpClient httpClient() {
- RequestConfig requestConfig = RequestConfig.custom()
- .setCookieSpec(StandardCookieSpec.IGNORE)
- .setConnectionRequestTimeout(Timeout.of(REQUEST_TIMEOUT, TimeUnit.MILLISECONDS))
- .setConnectTimeout(Timeout.of(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS))
- .setResponseTimeout(Timeout.of(SOCKET_TIMEOUT, TimeUnit.MILLISECONDS)).build();
-
- return HttpClients.custom()
- .setDefaultRequestConfig(requestConfig)
- .setConnectionManager(poolingConnectionManager())
- .setKeepAliveStrategy(connectionKeepAliveStrategy())
+ public OkHttpClient httpClient() {
+ return new OkHttpClient.Builder()
+ .addInterceptor(new HttpLoggingInterceptor(logger::debug)
+ .setLevel(HttpLoggingInterceptor.Level.HEADERS))
+ .addInterceptor(new ActivityPubRequestInterceptor())
+ .addInterceptor(new ActivityPubClientErrorHandler(applicationEventPublisher))
.build();
}
-
- @Bean
- Runnable idleConnectionMonitor(final PoolingHttpClientConnectionManager connectionManager) {
- return new Runnable() {
- @Override
- @Scheduled(fixedDelay = 10000)
- public void run() {
- try {
- if (connectionManager != null) {
- LOGGER.trace("run IdleConnectionMonitor - Closing expired and idle connections...");
- connectionManager.closeExpired();
- connectionManager.closeIdle(TimeValue.of(CLOSE_IDLE_CONNECTION_WAIT_TIME_SECS, TimeUnit.SECONDS));
- } else {
- LOGGER.trace("run IdleConnectionMonitor - Http Client Connection manager is not initialised");
- }
- } catch (Exception e) {
- LOGGER.error("run IdleConnectionMonitor - Exception occurred. msg={}, e={}", e.getMessage(), e);
- }
- }
- };
- }
}