Guest User

Untitled

a guest
Mar 8th, 2018
334
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 21.32 KB | None | 0 0
  1. /*
  2. * To change this template, choose Tools | Templates
  3. * and open the template in the editor.
  4. */
  5. package com.sprice.travelstore;
  6.  
  7. import com.sprice.travelstore.hotel.data.BookingDetails;
  8. import com.sprice.travelstore.hotel.data.BookingStatus;
  9. import com.sprice.travelstore.hotel.data.Guest;
  10. import com.sprice.travelstore.hotel.data.HotelOffer;
  11. import com.sprice.travelstore.hotel.data.HotelResult;
  12. import com.sprice.travelstore.hotel.data.HotelReviewState;
  13. import com.sprice.travelstore.hotel.data.HotelView;
  14. import com.sprice.travelstore.hotel.data.InitializedHotelReview;
  15. import com.sprice.travelstore.hotel.data.ResultsHotelView;
  16. import com.sprice.travelstore.hotel.data.RoomOccupancy;
  17. import com.sprice.travelstore.hotel.data.json.JsonAmenitiesHotelView;
  18. import com.sprice.travelstore.hotel.data.json.JsonBookingDetails;
  19. import com.sprice.travelstore.hotel.data.json.JsonHotelReviewState;
  20. import com.sprice.travelstore.hotel.data.json.JsonInitializedHotelReview;
  21. import com.sprice.travelstore.hotel.data.json.JsonLandmarksHotelView;
  22. import com.sprice.travelstore.hotel.data.json.JsonPriceHotelView;
  23. import com.sprice.travelstore.hotel.data.json.JsonResultsHotelView;
  24. import com.sprice.travelstore.hotel.data.json.JsonSuppliersHotelView;
  25. import java.io.*;
  26. import java.net.*;
  27. import java.util.*;
  28. import java.text.DateFormat;
  29. import java.text.SimpleDateFormat;
  30.  
  31. import org.json.*;
  32.  
  33. /**
  34. *
  35. * @author demon
  36. */
  37. public class HotelService
  38. {
  39. private final static String user = "open_fire"; //damien";
  40.  
  41. private final static String password = "open_fire"; //"test";
  42.  
  43. private final static String hashedAuthentification = Base64.encodeBytes( ( user + ":" + password ).getBytes() );
  44.  
  45. //private final static String defaultHost = "staging.travelportroomsandmore.com";
  46. private final static String defaultHost = "tp-dev.sprice.com";
  47.  
  48. private final static String defaultProtocol = "https";
  49.  
  50. private final static String defaultCurrency = "EUR";
  51.  
  52. public final static DateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
  53.  
  54. public final static DateFormat creditCardDateFormat = new SimpleDateFormat( "yyyy-MM" );
  55.  
  56. private final static Integer defaultReflect = 0;
  57. private final static Integer defaultExhaustive = 0;
  58.  
  59. private final static Language defaultLanguage = Language.English;
  60.  
  61. private final static CharacterSet defaultCharacterSet = CharacterSet.Utf8;
  62.  
  63. private final static int defaultSearchTimeout = 85000;
  64.  
  65. //private final static String[] defaultViews = { "amenitieslist", "price", "results", "landmarkslist", "supplierslist" };
  66. private final static String[] defaultViews = { "results" };
  67.  
  68. /**
  69. * @param args the command line arguments
  70. */
  71. public static void main(String[] args) throws Exception
  72. {
  73. HotelSearch uninitializedHotelSearch = new HotelSearch( "FRMRS@", dateFormat.parse( "2011-11-11" ), dateFormat.parse( "2011-11-15" ), 1, new Integer[] { 12, 8, 6 }, defaultViews, Language.English, defaultCurrency, CharacterSet.Utf8, defaultSearchTimeout );
  74.  
  75. InitializedHotelSearch initializedHotelSearch = initializeSearch( uninitializedHotelSearch );
  76.  
  77. HotelSearchState hotelSearchState;
  78.  
  79. do
  80. {
  81. hotelSearchState = pool( initializedHotelSearch );
  82.  
  83. Thread.sleep( 2000 );
  84. }
  85. while( !hotelSearchState.getSearchStatus().equals( SearchStatus.End ) );
  86.  
  87. System.out.println( "Search finished" );
  88.  
  89. ResultsHotelView results = (ResultsHotelView) hotelSearchState.getViews().get( "results" );
  90. HotelResult result = (HotelResult) results.getResults().get( 0 );
  91.  
  92. HotelOffer offer = (HotelOffer) result.getOffers().get( 0 );
  93.  
  94. InitializedHotelReview initializedHotelReview = initializeReview( initializedHotelSearch, result, offer );
  95.  
  96. HotelReviewState hotelReviewState;
  97.  
  98. do
  99. {
  100. hotelReviewState = poolReview( initializedHotelSearch, initializedHotelReview );
  101.  
  102. Thread.sleep( 2000 );
  103. }
  104. while( !hotelReviewState.getStatus().equals( ReviewStatus.End ) );
  105.  
  106. System.out.println( "Review finished" );
  107.  
  108. RoomOccupancy occupancy = new RoomOccupancy( hotelReviewState.getHotelReview().getRooms().get( 0 ).getOfferId() );
  109.  
  110. occupancy.getGuests().add( new Guest( Salutation.Mister, "John", "Doe" ) );
  111.  
  112. List<RoomOccupancy> occupancies = new ArrayList<RoomOccupancy>();
  113.  
  114. occupancies.add( occupancy );
  115.  
  116. BookingDetails details = initializeBooking( initializedHotelSearch.getSessionIdentifier(), initializedHotelReview.getOfferId(), "138", creditCardDateFormat.parse( "2013-02" ), "JOHN DOE", "CITY BANK", "US", "4978370200001532", CreditCard.Visa, dateFormat.parse( "1971-01-01" ), "Paris", "FR", "john.doe@example.org", "John", "Doe", "FR", "88", "033", "888888", "67000", Salutation.Mister, "99 rue de l'Impossible", occupancies );
  117.  
  118. while( details.getStatus().equals( BookingStatus.Progress ) )
  119. {
  120. Thread.sleep( 2000 );
  121.  
  122. details = poolBooking( details.getId() );
  123. }
  124.  
  125. System.out.println( "Booking done" );
  126. }
  127.  
  128. public static InitializedHotelSearch initializeSearch( HotelSearch unitializedHotelSearch ) throws Exception
  129. {
  130. Map<String, String> data = new HashMap<String, String>();
  131.  
  132. data.put( "city_code", unitializedHotelSearch.getCityCode() );
  133. data.put( "views", convertToAPIList( unitializedHotelSearch.getViews() ) );
  134. data.put( "lang", unitializedHotelSearch.getLanguage().toString() );
  135. data.put( "currency", unitializedHotelSearch.getCurrency() );
  136. data.put( "search_timeout", unitializedHotelSearch.getSearchTimeout().toString() );
  137. data.put( "charset", unitializedHotelSearch.getCharacterSet().toString() );
  138. data.put( "checkin", dateFormat.format( unitializedHotelSearch.getCheckin() ) );
  139. data.put( "checkout", dateFormat.format( unitializedHotelSearch.getCheckout() ) );
  140. data.put( "adults", unitializedHotelSearch.getAdultCount().toString() );
  141. data.put( "children", convertToAPIList( unitializedHotelSearch.getChildAges() ) );
  142.  
  143. ApiResponse response = HotelService.getUrl( "/hotel/search", "POST", data );
  144.  
  145. JSONObject js = new JSONObject( response.getBody() );
  146.  
  147. String sessionIdentifier = js.getString( "session_id" );
  148.  
  149. System.out.println( sessionIdentifier );
  150.  
  151. return( new InitializedHotelSearch( unitializedHotelSearch.getCheckin(), unitializedHotelSearch.getCheckout(), sessionIdentifier ) );
  152. }
  153.  
  154. public static ApiResponse poolJson( InitializedHotelSearch hotelSearch ) throws Exception
  155. {
  156. Map<String, String> data = new HashMap<String, String>();
  157.  
  158. data.put( "session_id", hotelSearch.getSessionIdentifier() );
  159. data.put( "reflect", defaultReflect.toString() );
  160. data.put( "exhaustive", defaultExhaustive.toString() );
  161. data.put( "checkin", dateFormat.format( hotelSearch.getCheckin() ) );
  162. data.put( "checkout", dateFormat.format( hotelSearch.getCheckout() ) );
  163. data.put( "f_distance", convertToAPIList( new Float[] { hotelSearch.getMinimumDistance(), hotelSearch.getMaximumDistance() } ) );
  164. data.put( "p_results_size", hotelSearch.getResultsSize().toString() );
  165. data.put( "p_results_page", hotelSearch.getResultsPage().toString() );
  166. data.put( "p_results_sort", hotelSearch.getResultsSort().toString() );
  167. data.put( "f_amenitygroups", convertToAPIList( hotelSearch.getAmenities() ) );
  168. data.put( "f_name", hotelSearch.getName() );
  169. data.put( "f_suppliers", convertToAPIList( hotelSearch.getSuppliers() ) );
  170. data.put( "f_price", convertToAPIList( new Float[] { hotelSearch.getMinimumPrice(), hotelSearch.getMaximumPrice() } ) );
  171. data.put( "f_categories", convertToAPIList( hotelSearch.getCategories() ) );
  172. data.put( "f_paymenttype", hotelSearch.getPaymentType() == null ? "" : hotelSearch.getPaymentType().toString() );
  173.  
  174. ApiResponse response = HotelService.getUrl( "/hotel/search/" + hotelSearch.getSessionIdentifier() + "/", "GET", data );
  175.  
  176. return response;
  177. }
  178.  
  179. public static HotelSearchState json_to_HotelSearchState( String response ) throws Exception
  180. {
  181. JSONObject js = new JSONObject(response );
  182.  
  183. HashMap<String, HotelView> views = new HashMap<String, HotelView>();
  184.  
  185. JSONArray jsonViews = js.getJSONArray( "views" );
  186. String keyName = "";
  187. for( int i = 0; i < jsonViews.length(); i++ )
  188. {
  189. JSONObject current = jsonViews.getJSONObject(i);
  190.  
  191. if( current.getString("name").equals( "amenitieslist" ) )
  192. {
  193. views.put("amenitieslist", new JsonAmenitiesHotelView( current ) );
  194. }
  195. else if( current.getString("name").equals( "price" ) )
  196. {
  197. views.put("price", new JsonPriceHotelView( current ) );
  198. }
  199. else if( current.getString("name").equals( "results" ) )
  200. {
  201. views.put("results", new JsonResultsHotelView( current ) );
  202. }
  203. else if( current.getString("name").equals( "landmarkslist" ) )
  204. {
  205. views.put("landmarkslist", new JsonLandmarksHotelView( current ) );
  206. }
  207. else if( current.getString("name").equals( "supplierslist" ) )
  208. {
  209. views.put("supplierslist", new JsonSuppliersHotelView( current ) );
  210. }
  211. }
  212.  
  213. HotelSearchState hotelSearchState = new HotelSearchState( js.getString( "session_id"), js.getInt( "search_timeout" ), js.getInt( "refresh" ), js.getInt( "revision_id" ), SearchStatus.values()[js.getInt( "search_status" )], js.getInt( "search_progress" ), js.getInt( "total_results_count" ), views );
  214.  
  215. return( hotelSearchState );
  216. }
  217.  
  218. public static HotelSearchState pool( InitializedHotelSearch hotelSearch ) throws Exception
  219. {
  220. ApiResponse response = poolJson( hotelSearch );
  221.  
  222. HotelSearchState hotelSearchState = json_to_HotelSearchState( response.getBody() );
  223.  
  224. return( hotelSearchState );
  225. }
  226.  
  227. public static InitializedHotelReview initializeReview( String session_id, String hotel_code, String supplier_code) throws Exception
  228. {
  229. Map<String, String> data = new HashMap<String, String>();
  230.  
  231. data.put( "session_id", session_id );
  232. data.put( "hotel_code", hotel_code );
  233. data.put( "supplier_code", supplier_code );
  234.  
  235. ApiResponse response = HotelService.getUrl( "/hotel/search/" + session_id + "/review", "POST", data );
  236.  
  237. JSONObject js = new JSONObject( response.getBody() );
  238.  
  239. return( new JsonInitializedHotelReview( js ) );
  240. }
  241.  
  242. public static InitializedHotelReview initializeReview( InitializedHotelSearch hotelSearch, HotelResult hotelResult, HotelOffer hotelOffer ) throws Exception
  243. {
  244. Map<String, String> data = new HashMap<String, String>();
  245.  
  246. data.put( "session_id", hotelSearch.getSessionIdentifier() );
  247. data.put( "hotel_code", hotelResult.getHotelCode() );
  248. data.put( "supplier_code", hotelOffer.getSupplierCode() );
  249.  
  250. ApiResponse response = HotelService.getUrl( "/hotel/search/" + hotelSearch.getSessionIdentifier() + "/review", "POST", data );
  251.  
  252. JSONObject js = new JSONObject( response.getBody() );
  253.  
  254. return( new JsonInitializedHotelReview( js ) );
  255. }
  256.  
  257.  
  258. public static ApiResponse poolReviewJson( String offer_id, String sessionIdentifier ) throws Exception
  259. {
  260. Map<String, String> data = new HashMap<String, String>();
  261.  
  262. data.put( "offer_id", offer_id );
  263.  
  264. ApiResponse response = HotelService.getUrl( "/hotel/search/" + sessionIdentifier + "/review", "GET", data );
  265.  
  266. return response;
  267. }
  268.  
  269. public static HotelReviewState poolReview( InitializedHotelSearch hotelSearch, InitializedHotelReview initializedHotelReview ) throws Exception
  270. {
  271. ApiResponse response = poolReviewJson( initializedHotelReview.getOfferId(), hotelSearch.getSessionIdentifier() );
  272.  
  273. JSONObject js = new JSONObject( response.getBody() );
  274.  
  275. return( new JsonHotelReviewState( js ) );
  276. }
  277.  
  278. public static ApiResponse initializeBookingJson( String session_id, String offer_id, String cardVerificationNumber, Date cardExpiry, String cardHolderName, String cardIssueBank, String cardIssueCountry, String cardNumber, CreditCard cardType, Date customerBirthDate, String customerCityName, String customerCountryCode, String customerEmail, String customerFirstName, String customerLastName, String customerNationality, String customerPhoneAreaCode, String customerPhoneCountryCode, String customerPhoneNumber, String customerPostCode, Salutation customerSalutation, String customerAddress, List<RoomOccupancy> occupancies ) throws Exception
  279. {
  280. Map<String, String> data = new HashMap<String, String>();
  281.  
  282. data.put( "session_id", session_id );
  283. data.put( "offer_id", offer_id );
  284. data.put( "booking_info[credit_card][credit_card_cvc]", cardVerificationNumber.toString() );
  285. data.put( "booking_info[credit_card][credit_card_expiration]", creditCardDateFormat.format( cardExpiry ) );
  286. data.put( "booking_info[credit_card][credit_card_holder_name]", cardHolderName );
  287. data.put( "booking_info[credit_card][credit_card_issue_bank]", cardIssueBank );
  288. data.put( "booking_info[credit_card][credit_card_issue_country]", cardIssueCountry );
  289. data.put( "booking_info[credit_card][credit_card_number]", cardNumber );
  290. data.put( "booking_info[credit_card][credit_card_type]", cardType.toString() );
  291. data.put( "booking_info[customer][customer_birth_date]", dateFormat.format( customerBirthDate ) );
  292. data.put( "booking_info[customer][customer_city_name]", customerCityName );
  293. data.put( "booking_info[customer][customer_country_code]", customerCountryCode );
  294. data.put( "booking_info[customer][customer_email]", customerEmail );
  295. data.put( "booking_info[customer][customer_first_name]", customerFirstName );
  296. data.put( "booking_info[customer][customer_last_name]", customerLastName );
  297. data.put( "booking_info[customer][customer_nationality]", customerNationality );
  298. data.put( "booking_info[customer][customer_phone_area_code]", customerPhoneAreaCode );
  299. data.put( "booking_info[customer][customer_phone_country_code]", customerPhoneCountryCode);
  300. data.put( "booking_info[customer][customer_phone_number]", customerPhoneNumber );
  301. data.put( "booking_info[customer][customer_post_code]", customerPostCode );
  302. data.put( "booking_info[customer][customer_salutation]", customerSalutation.toString() );
  303. data.put( "booking_info[customer][customer_street_address]", customerAddress );
  304.  
  305. for( int i = 0; i < occupancies.size(); i++ )
  306. {
  307. RoomOccupancy occupancy = occupancies.get( i );
  308. data.put( "booking_info[rooms][room[" + i + "][offer_id]]", occupancy.getOfferId() );
  309.  
  310. for( int j = 0; j < occupancy.getGuests().size(); j++ )
  311. {
  312. data.put( "booking_info[rooms][room[" + i + "][guest][" + j + "][salutation]]", occupancy.getGuests().get( j ).getSalutation().toString() );
  313. data.put( "booking_info[rooms][room[" + i + "][guest][" + j + "][first_name]]", occupancy.getGuests().get( j ).getFirstName() );
  314. data.put( "booking_info[rooms][room[" + i + "][guest][" + j + "][last_name]]", occupancy.getGuests().get( j ).getLastName() );
  315. }
  316.  
  317. if (! occupancy.getGuestsChild().isEmpty())
  318. {
  319. for (int j = 0; j < occupancy.getGuestsChild().size(); j++) {
  320. data.put("booking_info[rooms][room[" + i + "][child_guest][" + j + "][age]]", Integer.toString(occupancy.getGuestsChild().get(j).getAge()));
  321. data.put("booking_info[rooms][room[" + i + "][child_guest][" + j + "][first_name]]", occupancy.getGuestsChild().get(j).getFirstName());
  322. data.put("booking_info[rooms][room[" + i + "][child_guest][" + j + "][last_name]]", occupancy.getGuestsChild().get(j).getLastName());
  323. }
  324. }
  325. }
  326.  
  327. ApiResponse response = HotelService.getUrl( "/hotel/bookings", "POST", data );
  328.  
  329. return response;
  330. }
  331.  
  332. public static BookingDetails initializeBooking( String session_id, String offer_id, String cardVerificationNumber, Date cardExpiry, String cardHolderName, String cardIssueBank, String cardIssueCountry, String cardNumber, CreditCard cardType, Date customerBirthDate, String customerCityName, String customerCountryCode, String customerEmail, String customerFirstName, String customerLastName, String customerNationality, String customerPhoneAreaCode, String customerPhoneCountryCode, String customerPhoneNumber, String customerPostCode, Salutation customerSalutation, String customerAddress, List<RoomOccupancy> occupancies ) throws Exception
  333. {
  334. ApiResponse response = initializeBookingJson( session_id, offer_id, cardVerificationNumber, cardExpiry, cardHolderName, cardIssueBank, cardIssueCountry, cardNumber, cardType, customerBirthDate, customerCityName, customerCountryCode, customerEmail, customerFirstName, customerLastName, customerNationality, customerPhoneAreaCode, customerPhoneCountryCode, customerPhoneNumber, customerPostCode, customerSalutation, customerAddress, occupancies );
  335.  
  336. JSONObject js = new JSONObject( response.getBody() );
  337.  
  338. return( new JsonBookingDetails( js ) );
  339. }
  340.  
  341. public static ApiResponse poolBookingJson( Integer bookingId ) throws Exception
  342. {
  343. ApiResponse response = HotelService.getUrl( "/hotel/bookings/" + bookingId.toString(), "GET", null );
  344.  
  345. return response;
  346. }
  347.  
  348. public static BookingDetails poolBooking( Integer bookingId ) throws Exception
  349. {
  350. ApiResponse response = HotelService.poolBookingJson(bookingId);
  351.  
  352. JSONObject js = new JSONObject( response.getBody() );
  353.  
  354. return( new JsonBookingDetails( js ) );
  355. }
  356.  
  357. public static ApiResponse poolLstBookingJson( String user_id ) throws Exception
  358. {
  359. //client_id
  360. ApiResponse response = HotelService.getUrl( "/hotel/bookings/", "GET", null );
  361.  
  362. return response;
  363. }
  364.  
  365. public static void poolLstBooking(String user_id) throws Exception
  366. {
  367. ApiResponse response = HotelService.poolLstBookingJson(user_id);
  368.  
  369. JSONObject js = new JSONObject( response.getBody() );
  370.  
  371. //return null; //( new JsonBookingDetails( js ) );
  372. }
  373.  
  374. public static String convertToAPIList( List<?> list )
  375. {
  376. return( convertToAPIList( list.toArray() ) );
  377. }
  378.  
  379. public static String convertToAPIList( Object[] array )
  380. {
  381. String result = "";
  382.  
  383. if( array == null || array.length == 0 )
  384. {
  385. return( "" );
  386. }
  387.  
  388. for( int i = 0; i < array.length; i++ )
  389. {
  390. result += ( array[ i ] == null ? "" : array[ i ].toString() ) + ",";
  391. }
  392.  
  393. return( result.substring( 0, result.length() - 1 ) );
  394. }
  395.  
  396. public static ApiResponse getUrl( String path, String method, Map<String, String> postData ) throws Exception
  397. {
  398. String parameters = "";
  399.  
  400. if( postData != null && postData.size() > 0 )
  401. {
  402. for (Map.Entry<String, String> entry : postData.entrySet())
  403. {
  404. String key = entry.getKey();
  405. String value = entry.getValue();
  406.  
  407. parameters += key + "=" + ( value == null ? "" : URLEncoder.encode( value, "UTF-8" ) ) + "&";
  408. }
  409. }
  410.  
  411. if( method.equals( "GET" ) && parameters.length() > 0 )
  412. {
  413. path += "?" + parameters;
  414. }
  415.  
  416. System.out.println( defaultProtocol + "://" + defaultHost + path );
  417.  
  418. URL url = new URL( defaultProtocol + "://" + defaultHost + path );
  419.  
  420. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  421.  
  422. conn.setDoOutput( true );
  423.  
  424. conn.addRequestProperty( "Authorization", "Basic " + hashedAuthentification );
  425. conn.addRequestProperty( "X-Requested-With", "XMLHttpRequest" );
  426.  
  427. conn.setRequestMethod( method );
  428.  
  429. if( method.equals( "POST" ) )
  430. {
  431. OutputStreamWriter writer = new OutputStreamWriter( conn.getOutputStream() );
  432.  
  433. writer.write( parameters.substring( 0, parameters.length() - 1 ) );
  434.  
  435. writer.flush();
  436. writer.close();
  437. }
  438.  
  439. String responseLine = "";
  440. String responseBody = "";
  441.  
  442. BufferedReader bufferedReader;
  443.  
  444. try
  445. {
  446. bufferedReader = new BufferedReader( new InputStreamReader( conn.getInputStream() ) );
  447. }
  448. catch( IOException e )
  449. {
  450. bufferedReader = new BufferedReader( new InputStreamReader( conn.getErrorStream() ) );
  451. }
  452. finally
  453. {
  454. }
  455.  
  456. while( ( responseLine = bufferedReader.readLine() ) != null )
  457. {
  458. responseBody += responseLine;
  459. }
  460.  
  461. bufferedReader.close();
  462.  
  463. System.out.println( responseBody );
  464.  
  465. return( new ApiResponse( conn.getResponseCode(), responseBody ) );
  466. }
Add Comment
Please, Sign In to add comment