private < T extends Object > T getResponse ( HttpResponse httpResponse , Class < T > clazz ) throws IOException , HttpRosetteAPIException { int status = httpResponse . getStatusLine ( ) . getStatusCode ( ) ; String encoding = headerValueOrNull ( httpResponse . getFirstHeader ( HttpHeaders . CONTENT_ENCODING ) ) ; try ( InputStream stream = httpResponse . getEntity ( ) . getContent ( ) ; InputStream inputStream = "gzip" . equalsIgnoreCase ( encoding ) ? new GZIPInputStream ( stream ) : stream ) { String ridHeader = headerValueOrNull ( httpResponse . getFirstHeader ( "X-RosetteAPI-DocumentRequest-Id" ) ) ; if ( HTTP_OK != status ) { String ecHeader = headerValueOrNull ( httpResponse . getFirstHeader ( "X-RosetteAPI-Status-Code" ) ) ; String emHeader = headerValueOrNull ( httpResponse . getFirstHeader ( "X-RosetteAPI-Status-Message" ) ) ; String responseContentType = headerValueOrNull ( httpResponse . getFirstHeader ( HttpHeaders . CONTENT_TYPE ) ) ; if ( "application/json" . equals ( responseContentType ) ) { ErrorResponse errorResponse = mapper . readValue ( inputStream , ErrorResponse . class ) ; if ( ridHeader != null ) { LOG . debug ( "DocumentRequest ID " + ridHeader ) ; } if ( ecHeader != null ) { errorResponse . setCode ( ecHeader ) ; } if ( 429 == status ) { String concurrencyMessage = "You have exceeded your plan's limit on concurrent calls. " + "This could be caused by multiple processes or threads making Rosette API calls in parallel, " + "or if your httpClient is configured with higher concurrency than your plan allows." ; if ( emHeader == null ) { emHeader = concurrencyMessage ; } else { emHeader = concurrencyMessage + System . lineSeparator ( ) + emHeader ; } } if ( emHeader != null ) { errorResponse . setMessage ( emHeader ) ; } throw new HttpRosetteAPIException ( errorResponse , status ) ; } else { String errorContent ; if ( inputStream != null ) { byte [ ] content = getBytes ( inputStream ) ; errorContent = new String ( content , "utf-8" ) ; } else { errorContent = "(no body)" ; } // something not from us at all throw new HttpRosetteAPIException ( "Invalid error response (not json)" , ErrorResponse . builder ( ) . code ( "invalidErrorResponse" ) . message ( errorContent ) . build ( ) , status ) ; } } else { return mapper . readValue ( inputStream , clazz ) ; } } }
Gets response from HTTP connection according to the specified response class ; throws for an error response .