1+ package examples ;
2+
3+ import java .io .File ;
4+ import java .io .FileOutputStream ;
5+ import java .util .List ;
6+ import java .util .Map ;
7+ import java .util .UUID ;
8+
9+ import javax .ws .rs .client .ClientBuilder ;
10+
11+ import factset .analyticsapi .engines .models .*;
12+ import org .apache .poi .xssf .usermodel .XSSFCell ;
13+ import org .apache .poi .xssf .usermodel .XSSFRow ;
14+ import org .apache .poi .xssf .usermodel .XSSFSheet ;
15+ import org .apache .poi .xssf .usermodel .XSSFWorkbook ;
16+
17+ import com .factset .protobuf .stach .extensions .RowStachExtensionBuilder ;
18+ import com .factset .protobuf .stach .extensions .StachExtensionFactory ;
19+ import com .factset .protobuf .stach .extensions .models .StachVersion ;
20+ import com .factset .protobuf .stach .extensions .models .TableData ;
21+ import com .fasterxml .jackson .core .JsonProcessingException ;
22+ import com .fasterxml .jackson .databind .JsonNode ;
23+ import com .fasterxml .jackson .databind .ObjectMapper ;
24+
25+ import factset .analyticsapi .engines .ApiClient ;
26+ import factset .analyticsapi .engines .ApiException ;
27+ import factset .analyticsapi .engines .ApiResponse ;
28+ import factset .analyticsapi .engines .api .AfiOptimizerApi ;
29+ import factset .analyticsapi .engines .models .OptimizerTradesList .IdentifierTypeEnum ;
30+
31+ public class AfiInteractiveOptimizerEngineExample {
32+ private static FdsApiClient apiClient = null ;
33+ private static String BASE_PATH = "https://api.factset.com" ;
34+ private static String USERNAME = "<username-serial>" ;
35+ private static String PASSWORD = "<apiKey>" ;
36+
37+ private static String STRATEGY_ID = "CLIENT:/Analytics_api/AFIAPISIMPLE" ;
38+ private static IdentifierTypeEnum TRADES_ID_TYPE = IdentifierTypeEnum .ASSET ;
39+ private static Boolean INCLUDE_CASH = false ;
40+
41+ public static void main (String [] args ) throws InterruptedException , JsonProcessingException {
42+ try {
43+ AfiOptimizerApi apiInstance = new AfiOptimizerApi (getApiClient ());
44+ AFIOptimizationParameters afiItem = new AFIOptimizationParameters ();
45+
46+ AFIOptimizerStrategy strategy = new AFIOptimizerStrategy ();
47+ strategy .setId (STRATEGY_ID );
48+
49+ OptimizerOutputTypes optOutputTypes = new OptimizerOutputTypes ();
50+ OptimizerTradesList tradesList = new OptimizerTradesList ();
51+ tradesList .setIdentifierType (TRADES_ID_TYPE );
52+ tradesList .setIncludeCash (INCLUDE_CASH );
53+ optOutputTypes .setTrades (tradesList );
54+
55+ afiItem .setStrategy (strategy );
56+ afiItem .setOutputTypes (optOutputTypes );
57+
58+ AFIOptimizationParametersRoot afiOptimizerParam = new AFIOptimizationParametersRoot ();
59+ afiOptimizerParam .setData (afiItem );
60+
61+ ApiResponse <Object > response = apiInstance .postAndOptimizeWithHttpInfo (null , null , afiOptimizerParam );
62+ Map <String , List <String >> headers = response .getHeaders ();
63+
64+ Object result = null ;
65+ switch (response .getStatusCode ()) {
66+ case 201 : // Calculation completed
67+ System .out .println ("Calculation successful!!!" );
68+ result = ((ObjectRoot ) response .getData ()).getData ();
69+ break ;
70+ case 202 :
71+ CalculationInfoRoot status = (CalculationInfoRoot ) response .getData ();
72+ String calculationId = status .getData ().getCalculationId ();
73+ do {
74+ response = apiInstance .getOptimizationStatusByIdWithHttpInfo (calculationId );
75+ headers = response .getHeaders ();
76+
77+ List <String > cacheControl = headers .get ("Cache-Control" );
78+ if (cacheControl != null ) {
79+ int maxAge = Integer .parseInt (cacheControl .get (0 ).replace ("max-age=" , "" ));
80+ System .out .println ("Sleeping for: " + maxAge + " seconds" );
81+ Thread .sleep (maxAge * 1000L );
82+ } else {
83+ System .out .println ("Sleeping for: 2 seconds" );
84+ Thread .sleep (2 * 1000L );
85+ }
86+ } while (response .getStatusCode () == 202 );
87+
88+ System .out .println ("Calculation successful!!!" );
89+ // Get Calculation Result
90+ ApiResponse <ObjectRoot > resultResponse = apiInstance .getOptimizationResultWithHttpInfo (calculationId );
91+ result = resultResponse .getData ().getData ();
92+ break ;
93+ }
94+
95+ List <TableData > tables = null ;
96+ try {
97+ ObjectMapper mapper = new ObjectMapper ();
98+ String jsonString = mapper .writeValueAsString (result );
99+ JsonNode jsonObject = mapper .readTree (jsonString );
100+
101+ RowStachExtensionBuilder stachExtensionBuilder = StachExtensionFactory .getRowOrganizedBuilder (StachVersion .V2 );
102+ stachExtensionBuilder .addTable ("tradesTable" , jsonObject .get ("trades" ));
103+ // stachExtensionBuilder.addTable("optimalTable", jsonObject.get("optimal"));
104+ tables = stachExtensionBuilder .build ().convertToTable ();
105+ } catch (Exception e ) {
106+ System .out .println (e .getMessage ());
107+ e .printStackTrace ();
108+ }
109+
110+ ObjectMapper mapper = new ObjectMapper ();
111+ String json = mapper .writeValueAsString (tables );
112+ System .out .println (json ); // Prints the result in 2D table format.
113+ // Uncomment the following line to generate an Excel file
114+ // generateExcel(tables);
115+ } catch (ApiException e ) {
116+ handleException ("AfiOptimizerEngineExample#Main" , e );
117+ }
118+ }
119+
120+ private static void generateExcel (List <TableData > tableList ) {
121+ for (TableData table : tableList ) {
122+ writeDataToExcel (table , UUID .randomUUID ().toString () + ".xlsv" );
123+ }
124+ }
125+
126+ private static void writeDataToExcel (TableData table , String fileLocation ) {
127+ XSSFWorkbook workbook = new XSSFWorkbook ();
128+ XSSFSheet sheet = workbook .createSheet ("Calculation Report" );
129+ int rowsSize = table .getRows ().size ();
130+ for (int rowIndex = 0 ; rowIndex < rowsSize ; rowIndex ++) {
131+ XSSFRow xsswRow = sheet .createRow (rowIndex );
132+ List <String > cells = table .getRows ().get (rowIndex ).getCells ();
133+ for (int cellIndex = 0 ; cellIndex < cells .size (); cellIndex ++) {
134+ XSSFCell xssfCell = xsswRow .createCell (cellIndex );
135+ xssfCell .setCellValue (cells .get (cellIndex ));
136+ }
137+ }
138+ try {
139+ FileOutputStream fileStream = new FileOutputStream (new File (fileLocation ));
140+ workbook .write (fileStream );
141+ fileStream .close ();
142+ workbook .close ();
143+ } catch (Exception e ) {
144+ System .err .println ("Failed to write data to excel" );
145+ e .printStackTrace ();
146+ }
147+ }
148+
149+ private static class FdsApiClient extends ApiClient {
150+ // Uncomment the below lines to use a proxy server
151+ /*@Override
152+ protected void customizeClientBuilder(ClientBuilder clientBuilder) {
153+ clientConfig.property( ClientProperties.PROXY_URI, "http://127.0.0.1:8866" );
154+ clientConfig.connectorProvider( new ApacheConnectorProvider() );
155+ }*/
156+ }
157+
158+ private static FdsApiClient getApiClient () {
159+ if (apiClient != null ) {
160+ return apiClient ;
161+ }
162+
163+ apiClient = new FdsApiClient ();
164+ apiClient .setConnectTimeout (30000 );
165+ apiClient .setReadTimeout (30000 );
166+ apiClient .setBasePath (BASE_PATH );
167+ apiClient .setUsername (USERNAME );
168+ apiClient .setPassword (PASSWORD );
169+
170+ return apiClient ;
171+ }
172+
173+ private static void handleException (String method , ApiException e ) {
174+ System .err .println ("Exception when calling " + method );
175+ if (e .getResponseHeaders () != null && e .getResponseHeaders ().containsKey ("x-datadirect-request-key" )) {
176+ System .out .println ("x-datadirect-request-key: " + e .getResponseHeaders ().get ("x-datadirect-request-key" ).get (0 ));
177+ }
178+ System .out .println ("Status code: " + e .getCode ());
179+ System .out .println ("Reason: " + e .getClientErrorResponse ());
180+ e .printStackTrace ();
181+ }
182+ }
0 commit comments