Skip to content

Commit

Permalink
Feature #11801: Using the new HttpClient and HttpRequest API provided…
Browse files Browse the repository at this point in the history
… by Java 11.
  • Loading branch information
SilverYoCha committed Nov 5, 2020
1 parent 369de48 commit 1d4585c
Show file tree
Hide file tree
Showing 6 changed files with 112 additions and 84 deletions.
Expand Up @@ -406,5 +406,10 @@ public void switchAllowingDownloadForReaders(final SimpleDocumentPK pk,
public void switchEnableDisplayAsContent(final SimpleDocumentPK pk, final boolean enable) {

}

@Override
public void switchEnableEditSimultaneously(final SimpleDocumentPK pk, final boolean enable) {

}
}
}
@@ -1,21 +1,21 @@
package org.silverpeas.components.gallery;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.silverpeas.core.util.file.FileRepositoryManager;
import org.silverpeas.core.util.logging.SilverLogger;

import javax.ws.rs.core.MediaType;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static java.net.http.HttpResponse.BodyHandlers.ofInputStream;
import static org.apache.commons.io.FilenameUtils.*;
import static org.silverpeas.core.util.HttpUtil.httpClient;
import static org.silverpeas.core.util.HttpUtil.toUrl;
import static org.silverpeas.core.util.StringUtil.isDefined;

public class Watermark {
Expand Down Expand Up @@ -121,13 +121,14 @@ private File cacheImage(final String imageUrl, File cachedFile,
SilverLogger.getLogger(this).warn("impossible to save image from URL {0}", imageUrl);
}
} else {
final HttpGet httpGet = new HttpGet(imageUrl);
httpGet.addHeader("Accept", MediaType.WILDCARD);
try (CloseableHttpClient httpClient = httpClient();
CloseableHttpResponse response = httpClient.execute(httpGet);
InputStream is = response.getEntity().getContent()) {
Files.copy(is, cachedPath);
} catch (IOException e) {
try {
final HttpResponse<InputStream> response = httpClient().send(toUrl(imageUrl)
.header("Accept", MediaType.WILDCARD)
.build(), ofInputStream());
try (final InputStream body = response.body()) {
Files.copy(body, cachedPath);
}
} catch (Exception e) {
cachedFile = null;
SilverLogger.getLogger(this).warn(e);
SilverLogger.getLogger(this).warn("impossible to save image from URL {0}", imageUrl);
Expand Down
Expand Up @@ -23,20 +23,24 @@
*/
package org.silverpeas.components.gallery.constant;

import org.silverpeas.core.util.StringUtil;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import org.silverpeas.core.util.StringUtil;
import org.silverpeas.core.util.logging.SilverLogger;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.Optional.empty;
import static java.util.Optional.of;

/**
* @author: Yohann Chastagnier
*/
Expand Down Expand Up @@ -70,7 +74,7 @@ public enum StreamingProvider {
isExtractorPattern = null;
}
this.oembedUrlPattern = oembedUrlPattern;
this.regexpDetectionParts = new ArrayList<String>();
this.regexpDetectionParts = new ArrayList<>();
this.regexpDetectionParts.add(name());
Collections.addAll(this.regexpDetectionParts, regexpDetectionParts);
}
Expand Down Expand Up @@ -113,7 +117,7 @@ public static StreamingProvider fromUrl(String streamingUrl) {
* @param homepageUrl the streaming home page url.
* @return the oembed url as string.
*/
public static String getOembedUrl(String homepageUrl) {
public static Optional<String> getOembedUrl(String homepageUrl) {
StreamingProvider streamingProvider = StreamingProvider.fromUrl(homepageUrl);
if (streamingProvider != unknown) {
final String streamingId;
Expand All @@ -122,9 +126,9 @@ public static String getOembedUrl(String homepageUrl) {
} else {
streamingId = streamingProvider.extractStreamingId(homepageUrl);
}
return MessageFormat.format(streamingProvider.oembedUrlPattern, streamingId);
return of(MessageFormat.format(streamingProvider.oembedUrlPattern, streamingId));
}
return null;
return empty();
}

@JsonValue
Expand Down
Expand Up @@ -23,11 +23,6 @@
*/
package org.silverpeas.components.gallery.model;

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.silverpeas.components.gallery.constant.MediaResolution;
import org.silverpeas.components.gallery.constant.MediaType;
import org.silverpeas.components.gallery.constant.StreamingProvider;
Expand All @@ -36,8 +31,15 @@
import org.silverpeas.core.util.logging.SilverLogger;

import javax.ws.rs.WebApplicationException;
import java.net.http.HttpResponse;
import java.util.Objects;

import static java.net.http.HttpResponse.BodyHandlers.ofString;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static javax.ws.rs.core.Response.Status.OK;
import static org.silverpeas.core.util.HttpUtil.httpClient;
import static org.silverpeas.core.util.HttpUtil.toUrl;
import static org.silverpeas.core.util.StringUtil.EMPTY;

/**
* This class represents a Streaming.
Expand Down Expand Up @@ -128,33 +130,52 @@ public String getApplicationEmbedUrl(final MediaResolution mediaResolution) {
* @return a JSON structure as string that represents oembed data.
*/
public static String getJsonOembedAsString(String homepageUrl) {
final String oembedUrl = StreamingProvider.getOembedUrl(homepageUrl);
final HttpGet httpGet = new HttpGet(oembedUrl);
httpGet.addHeader("Accept", "application/json");
try (CloseableHttpClient httpClient = httpClient();
CloseableHttpResponse response = httpClient.execute(httpGet)) {
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new WebApplicationException(response.getStatusLine().getStatusCode());
return StreamingProvider.getOembedUrl(homepageUrl).map(oembedUrl -> {
try {
final HttpResponse<String> response = httpClient().send(toUrl(oembedUrl)
.header("Accept", APPLICATION_JSON)
.build(), ofString());
if (response.statusCode() != OK.getStatusCode()) {
throw new WebApplicationException(response.statusCode());
}
String jsonResponse = response.body();
for (StreamingProvider provider : StreamingProvider.values()) {
jsonResponse = jsonResponse.replaceAll("(?i)" + provider.name(), provider.name());
}
return jsonResponse;
} catch (WebApplicationException wae) {
SilverLogger.getLogger(Streaming.class)
.error("{0} -> HTTP ERROR {1}", oembedUrl, wae.getMessage());
throw wae;
} catch (Exception e) {
SilverLogger.getLogger(Streaming.class).error("{0} -> {1}", oembedUrl, e.getMessage());
throw new WebApplicationException(e);
}
String jsonResponse = EntityUtils.toString(response.getEntity());
for (StreamingProvider provider : StreamingProvider.values()) {
jsonResponse = jsonResponse.replaceAll("(?i)" + provider.name(), provider.name());
}
return jsonResponse;
} catch (WebApplicationException wae) {
SilverLogger.getLogger(Streaming.class)
.error("{0} -> HTTP ERROR {1}", oembedUrl, wae.getMessage());
throw wae;
} catch (Exception e) {
SilverLogger.getLogger(Streaming.class).error("{0} -> {1}", oembedUrl, e.getMessage());
throw new WebApplicationException(e);
} finally {
httpGet.releaseConnection();
}
}).orElse(EMPTY);
}

@Override
public Streaming getCopy() {
return new Streaming(this);
}

@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
final Streaming streaming = (Streaming) o;
return Objects.equals(homepageUrl, streaming.homepageUrl) && provider == streaming.provider;
}

@Override
public int hashCode() {
return Objects.hash(super.hashCode(), homepageUrl, provider);
}
}
Expand Up @@ -2,7 +2,7 @@
* Copyright (C) 2000 - 2020 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* it under the terms of the GNU Affero General License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
Expand All @@ -16,27 +16,29 @@
* 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.
* GNU Affero General License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* You should have received a copy of the GNU Affero General License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package org.silverpeas.components.gallery.constant;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.silverpeas.core.test.extention.EnableSilverTestEnv;

import java.util.Optional;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.silverpeas.components.gallery.constant.StreamingProvider.getOembedUrl;

@EnableSilverTestEnv
public class StreamingProviderTest {
class StreamingProviderTest {

@Test
public void testFrom() {
void testFrom() {
assertThat(StreamingProvider.ALL_VALIDS, hasSize(StreamingProvider.values().length - 1));
assertThat(StreamingProvider.from(null), is(StreamingProvider.unknown));
assertThat(StreamingProvider.from(""), is(StreamingProvider.unknown));
Expand All @@ -48,7 +50,7 @@ public void testFrom() {
}

@Test
public void testFromUrl() {
void testFromUrl() {
assertThat(StreamingProvider.fromUrl(null), is(StreamingProvider.unknown));
assertThat(StreamingProvider.fromUrl(""), is(StreamingProvider.unknown));
assertThat(StreamingProvider.fromUrl(" "), is(StreamingProvider.unknown));
Expand All @@ -61,7 +63,7 @@ public void testFromUrl() {
}

@Test
public void testExtractStreamingId() {
void testExtractStreamingId() {
assertThat(StreamingProvider.dailymotion.extractStreamingId(
"http://www.dailymotion.com/video/x3fd843_beverly-piegee-par-l-incroyable-strategie-de" +
"-gilles_tv"), is("x3fd843"));
Expand All @@ -73,33 +75,30 @@ public void testExtractStreamingId() {
}

@Test
public void getYoutubeOembedUrl() {
assertThat(StreamingProvider.getOembedUrl("https://youtu.be/6xN3hSEj21Q"),
is("http://www.youtube.com/oembed?url=https://youtu.be/6xN3hSEj21Q&format=json"));
void getYoutubeOembedUrl() {
final Optional<String> oembedUrl = getOembedUrl("https://youtu.be/6xN3hSEj21Q");
assertThat(oembedUrl.isPresent(), is(true));
assertThat(oembedUrl.get(), is("http://www.youtube.com/oembed?url=https://youtu.be/6xN3hSEj21Q&format=json"));
}

@Test
public void getVimeoOembedUrl() {
assertThat(StreamingProvider.getOembedUrl("http://vimeo.com/21040307"),
is("http://vimeo.com/api/oembed.json?url=http://vimeo.com/21040307"));
void getVimeoOembedUrl() {
final Optional<String> oembedUrl = getOembedUrl("http://vimeo.com/21040307");
assertThat(oembedUrl.isPresent(), is(true));
assertThat(oembedUrl.get(), is("http://vimeo.com/api/oembed.json?url=http://vimeo.com/21040307"));
}

@Test
public void getDailymotionOembedUrl() {
assertThat(StreamingProvider.getOembedUrl(
"http://www.dailymotion.com/video/x3fgyln_jeff-bezos-fait-atterrir-en-secret-la-premiere" +
"-fusee-reutilisable_tech"),
is("http://www.dailymotion.com/services/oembed?url=http://www.dailymotion" +
".com/video/x3fgyln"));
void getDailymotionOembedUrl() {
final Optional<String> oembedUrl = getOembedUrl("http://www.dailymotion.com/video/x3fgyln_jeff-bezos-fait-atterrir-en-secret-la-premiere-fusee-reutilisable_tech");
assertThat(oembedUrl.isPresent(), is(true));
assertThat(oembedUrl.get(), is("http://www.dailymotion.com/services/oembed?url=http://www.dailymotion.com/video/x3fgyln"));
}

@Test
public void getSoundCloudOembedUrl() {
assertThat(StreamingProvider.getOembedUrl(
"https://soundcloud.com/empreinte-digiale/saison-1-01-la-lazy-company-jean-sebastien" +
"-vermalle?in=benjamin-roux-10/sets/lazy-compagny"),
is("http://soundcloud.com/oembed?url=http://soundcloud" +
".com/empreinte-digiale/saison-1-01-la-lazy-company-jean-sebastien-vermalle?in" +
"=benjamin-roux-10/sets/lazy-compagny&format=json"));
void getSoundCloudOembedUrl() {
final Optional<String> oembedUrl = getOembedUrl("https://soundcloud.com/empreinte-digiale/saison-1-01-la-lazy-company-jean-sebastien-vermalle?in=benjamin-roux-10/sets/lazy-compagny");
assertThat(oembedUrl.isPresent(), is(true));
assertThat(oembedUrl.get(), is("http://soundcloud.com/oembed?url=http://soundcloud.com/empreinte-digiale/saison-1-01-la-lazy-company-jean-sebastien-vermalle?in=benjamin-roux-10/sets/lazy-compagny&format=json"));
}
}
Expand Up @@ -25,13 +25,9 @@

import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.FeedException;
import com.rometools.rome.io.SyndFeedInput;
import com.rometools.rome.io.XmlReader;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.silverpeas.components.rssaggregator.model.RSSItem;
import org.silverpeas.components.rssaggregator.model.RssAgregatorException;
import org.silverpeas.components.rssaggregator.model.SPChannel;
Expand All @@ -42,14 +38,15 @@
import org.silverpeas.core.util.logging.SilverLogger;

import javax.inject.Inject;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.io.InputStream;
import java.net.http.HttpClient;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static org.silverpeas.core.util.HttpUtil.httpClient;
import static org.silverpeas.core.util.HttpUtil.httpClientTrustingAnySslContext;
import static java.net.http.HttpResponse.BodyHandlers.ofInputStream;
import static org.silverpeas.core.util.HttpUtil.*;

@Service
public class DefaultRSSService implements RSSService {
Expand Down Expand Up @@ -98,15 +95,16 @@ private void applyFeedTo(final SPChannel channel) throws RssAgregatorException {
final String channelUrl = channel.getUrl();
if (StringUtil.isDefined(channelUrl)) {
try {
final HttpGet httpGet = new HttpGet(channelUrl);
httpGet.addHeader(HttpHeaders.ACCEPT, MimeTypes.RSS_MIME_TYPE);
try (CloseableHttpClient httpClient = channel.isSafeUrl() ? httpClientTrustingAnySslContext() : httpClient();
CloseableHttpResponse response = httpClient.execute(httpGet)) {
final HttpClient httpClient = channel.isSafeUrl() ? httpClientTrustingAnySslContext() : httpClient();
final HttpResponse<InputStream> response = httpClient.send(toUrl(channelUrl)
.header(HttpHeaders.ACCEPT, MimeTypes.RSS_MIME_TYPE)
.build(), ofInputStream());
try (final InputStream body = response.body()) {
final SyndFeedInput input = new SyndFeedInput();
final SyndFeed feed = input.build(new XmlReader(response.getEntity().getContent()));
final SyndFeed feed = input.build(new XmlReader(body));
channel.setFeed(feed);
}
} catch (IOException | FeedException | GeneralSecurityException e) {
} catch (Exception e) {
throw new RssAgregatorException(e.getMessage(), e);
}
}
Expand Down

0 comments on commit 1d4585c

Please sign in to comment.