1+ package com .convertapi ;
2+
3+ import com .convertapi .Model .ConversionResponse ;
4+ import com .google .gson .Gson ;
5+ import okhttp3 .HttpUrl ;
6+ import okhttp3 .MultipartBody ;
7+ import okhttp3 .Request ;
8+ import okhttp3 .Response ;
9+
10+ import java .io .IOException ;
11+ import java .util .Arrays ;
12+ import java .util .List ;
13+ import java .util .concurrent .CompletableFuture ;
14+ import java .util .concurrent .ExecutionException ;
15+
16+ public class ConvertApi {
17+ private static final List <String > IGNORE_PARAMS = Arrays .asList ( "storefile" , "async" , "jobid" , "timeout" );
18+
19+ public static ConversionResult convert (String fromFormat , String toFormat , Param [] params ) {
20+ return convert (fromFormat , toFormat , params , Config .defaults ());
21+ }
22+
23+ public static ConversionResult convert (String fromFormat , String toFormat , Param [] params , Config config ) {
24+ CompletableFuture <ConversionResponse > completableResponse = CompletableFuture .supplyAsync (() -> {
25+ HttpUrl url = Http .getUrlBuilder (config )
26+ .addPathSegment (fromFormat )
27+ .addPathSegment ("to" )
28+ .addPathSegment (toFormat )
29+ .addQueryParameter ("storefile" , "true" )
30+ .build ();
31+
32+ MultipartBody .Builder multipartBuilder = new MultipartBody .Builder ();
33+ for (Param param : params ) {
34+ if (!IGNORE_PARAMS .contains (param .getName ())) {
35+ try {
36+ multipartBuilder .addFormDataPart (param .getName (), param .getValue ());
37+ } catch (ExecutionException | InterruptedException e ) {
38+ throw new RuntimeException (e );
39+ }
40+ }
41+ }
42+
43+ Request request = new Request .Builder ()
44+ .url (url )
45+ .addHeader ("Accept" , "application/json" )
46+ .post (multipartBuilder .build ())
47+ .build ();
48+
49+ String bodyString ;
50+ try {
51+ Response response = Http .getClient ().newCall (request ).execute ();
52+ bodyString = response .body ().string ();
53+ if (response .code () != 200 ) {
54+ throw new ConversionException (bodyString );
55+ }
56+ } catch (IOException e ) {
57+ throw new RuntimeException (e );
58+ }
59+
60+ return new Gson ().fromJson (bodyString , ConversionResponse .class );
61+ });
62+
63+ return new ConversionResult (completableResponse );
64+ }
65+ }
0 commit comments