Skip to content

Commit

Permalink
Merge pull request #7512 from enonic/issue-7511
Browse files Browse the repository at this point in the history
Replace okHttp and apache httpclient with Java 11 alternatives where possible #7511
  • Loading branch information
GlennRicaud authored Oct 29, 2019
2 parents 7031ecd + 22bed80 commit 639f152
Show file tree
Hide file tree
Showing 24 changed files with 331 additions and 369 deletions.
4 changes: 0 additions & 4 deletions NOTICE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,6 @@ Licenses used by Enonic XP (full license texts are provided after the list of li
Apache License 2.0
https://github.com/dropwizard/metrics/blob/4.1-development/LICENSE

OK Http
Apache License 2.0
https://github.com/square/okhttp/blob/master/LICENSE.txt

OSGi Utilities
Apache License 2.0
https://www.mvnrepository.com/artifact/org.osgi/org.osgi.core
Expand Down
1 change: 0 additions & 1 deletion modules/admin/admin-impl/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ apply from: "$rootDir/gradle/osgi.gradle"
dependencies {
compile project( ':admin:admin-api' )
compile 'org.jboss.resteasy:resteasy-jaxrs:3.0.8.Final'
compile 'com.squareup.okhttp:okhttp:2.5.0'
testCompile project( ':jaxrs:jaxrs-impl' )
testCompile project( path: ':core:core-app', configuration: 'testOutput' )
testCompile project( path: ':portal:portal-api', configuration: 'testOutput' )
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,18 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;

import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.google.common.io.CharStreams;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import com.enonic.xp.admin.impl.rest.resource.application.json.MarketApplicationsJson;
import com.enonic.xp.json.ObjectMapperHelper;
Expand All @@ -26,9 +25,7 @@
public class MarketDataHttpProvider
implements MarketDataProvider
{
private static final int connectionTimeout = 10_000;

private static final int readTimeout = 10_000;
private static final Duration CONNECTION_TIMEOUT = Duration.ofSeconds( 10 );

private String marketUrl;

Expand All @@ -41,36 +38,43 @@ public void activate( final MarketConfig config )
@Override
public MarketApplicationsJson search( List<String> ids, String version, int start, int count )
{
final Request request = MarketRequestFactory.create( marketUrl, ids, version, start, count );
final HttpRequest request = MarketRequestFactory.create( marketUrl, ids, version, start, count );

return doRequest( request );
}

private MarketApplicationsJson doRequest( Request request )
private MarketApplicationsJson doRequest( HttpRequest request )
{
final HttpClient client = HttpClient.newBuilder().
connectTimeout( CONNECTION_TIMEOUT ).
build();

final OkHttpClient client = new OkHttpClient();
client.setReadTimeout( readTimeout, TimeUnit.MILLISECONDS );
client.setConnectTimeout( connectionTimeout, TimeUnit.MILLISECONDS );

final HttpResponse<InputStream> response;
try
{
final Response response = client.newCall( request ).execute();
return parseResponse( response );
response = client.send( request, HttpResponse.BodyHandlers.ofInputStream() );
}
catch ( IOException e )
catch ( IOException | InterruptedException e )
{
throw new MarketException( "Cannot connect to market", e );
}
return parseResponse( response );
}

protected MarketApplicationsJson parseResponse( final Response response )
private MarketApplicationsJson parseResponse( final HttpResponse<InputStream> response )
{
final int code = response.code();
final int code = response.statusCode();

if ( code == HttpStatus.OK.value() )
{
return parseJson( response );
try
{
return parseResponseBody( response );
}
catch ( IOException e )
{
throw new MarketException( "Failed to get response from market", e );
}
}
else if ( code == HttpStatus.INTERNAL_SERVER_ERROR.value() )
{
Expand All @@ -82,9 +86,9 @@ else if ( code == HttpStatus.INTERNAL_SERVER_ERROR.value() )
}
}

private MarketApplicationsJson throwExceptionAttachBody( final Response response, final int code )
private MarketApplicationsJson throwExceptionAttachBody( final HttpResponse<InputStream> response, final int code )
{
try (final InputStream bodyStream = response.body().byteStream())
try (final InputStream bodyStream = response.body())
{
final String body = CharStreams.toString( new InputStreamReader( bodyStream, StandardCharsets.UTF_8 ) );

Expand All @@ -96,21 +100,34 @@ private MarketApplicationsJson throwExceptionAttachBody( final Response response
}
}

private MarketApplicationsJson parseJson( final Response response )
private MarketApplicationsJson parseResponseBody( final HttpResponse<InputStream> response )
throws IOException
{
try (final InputStream src = response.body().byteStream())
final List<String> contentEncoding = response.headers().allValues( "Content-Encoding" );

if ( contentEncoding.isEmpty() )
{
return ObjectMapperHelper.create().
readValue( src, MarketApplicationsJson.class );
try (final InputStream src = response.body())
{
return parseJson( src );
}
}
catch ( JsonParseException | JsonMappingException e )
else if ( contentEncoding.equals( List.of( "gzip" ) ) )
{
throw new MarketException( "Failed to parse response from market", e );
try (final InputStream body = response.body(); final InputStream is = new GZIPInputStream( body ))
{
return parseJson( is );
}
}
catch ( IOException e )
else
{
throw new MarketException( "Failed to get response from market", e );
throw new IOException( "Unsupported Content-Encoding " + contentEncoding );
}
}

private MarketApplicationsJson parseJson( final InputStream src )
throws IOException
{
return ObjectMapperHelper.create().readValue( src, MarketApplicationsJson.class );
}
}
Original file line number Diff line number Diff line change
@@ -1,28 +1,26 @@
package com.enonic.xp.admin.impl.market;

import java.util.HashMap;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpRequest;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.squareup.okhttp.HttpUrl;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;

class MarketRequestFactory
{
private static final Duration READ_TIMEOUT = Duration.ofSeconds( 10 );

public static Request create( final String baseUrl, final List<String> ids, final String version, final int start, final int count )
public static HttpRequest create( final String baseUrl, final List<String> ids, final String version, final int start, final int count )
{
Map<String, Object> getParams = new HashMap<>();

getParams.put( "xpVersion", version );
getParams.put( "start", start );
getParams.put( "count", count );
Map<String, String> getParams = Map.of( "xpVersion", version, "start", String.valueOf( start ), "count", String.valueOf( count ) );

ObjectMapper mapper = new ObjectMapper();
String body = null;
Expand All @@ -44,34 +42,20 @@ public static Request create( final String baseUrl, final List<String> ids, fina
return create( baseUrl, getParams, body );
}

private static Request create( final String baseUrl, Map<String, Object> getParams, String body )
{
final Request.Builder request = new Request.Builder();
request.url( baseUrl );

HttpUrl url = HttpUrl.parse( baseUrl );

url = addParams( url, getParams );

request.url( url );

request.header( "Accept", "application/json" );

request.post( RequestBody.create( MediaType.parse( "application/json" ), body ) );

return request.build();
}

private static HttpUrl addParams( final HttpUrl url, final Map<String, Object> params )
private static HttpRequest create( final String baseUrl, Map<String, String> getParams, String body )
{
HttpUrl.Builder urlBuilder = url.newBuilder();
for ( Map.Entry<String, Object> header : params.entrySet() )
{
if ( header.getValue() != null )
{
urlBuilder.addEncodedQueryParameter( header.getKey(), header.getValue().toString() );
}
}
return urlBuilder.build();
final String queryString = getParams.entrySet().stream().
map( e -> URLEncoder.encode( e.getKey(), StandardCharsets.UTF_8 ) + "=" +
URLEncoder.encode( e.getValue(), StandardCharsets.UTF_8 ) ).
collect( Collectors.joining( "&" ) );
final URI uri = URI.create( baseUrl + "?" + queryString );

return HttpRequest.newBuilder( uri ).
timeout( READ_TIMEOUT ).
header( "Content-Type", "application/json" ).
header( "Accept", "application/json" ).
header( "Accept-Encoding", "gzip" ).
POST( HttpRequest.BodyPublishers.ofString( body ) ).
build();
}
}
Loading

0 comments on commit 639f152

Please sign in to comment.