Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package com.sprice.travelstore;
- import com.sprice.travelstore.hotel.data.BookingDetails;
- import com.sprice.travelstore.hotel.data.BookingStatus;
- import com.sprice.travelstore.hotel.data.Guest;
- import com.sprice.travelstore.hotel.data.HotelOffer;
- import com.sprice.travelstore.hotel.data.HotelResult;
- import com.sprice.travelstore.hotel.data.HotelReviewState;
- import com.sprice.travelstore.hotel.data.HotelView;
- import com.sprice.travelstore.hotel.data.InitializedHotelReview;
- import com.sprice.travelstore.hotel.data.ResultsHotelView;
- import com.sprice.travelstore.hotel.data.RoomOccupancy;
- import com.sprice.travelstore.hotel.data.json.JsonAmenitiesHotelView;
- import com.sprice.travelstore.hotel.data.json.JsonBookingDetails;
- import com.sprice.travelstore.hotel.data.json.JsonHotelReviewState;
- import com.sprice.travelstore.hotel.data.json.JsonInitializedHotelReview;
- import com.sprice.travelstore.hotel.data.json.JsonLandmarksHotelView;
- import com.sprice.travelstore.hotel.data.json.JsonPriceHotelView;
- import com.sprice.travelstore.hotel.data.json.JsonResultsHotelView;
- import com.sprice.travelstore.hotel.data.json.JsonSuppliersHotelView;
- import java.io.*;
- import java.net.*;
- import java.util.*;
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import org.json.*;
- /**
- *
- * @author demon
- */
- public class HotelService
- {
- private final static String user = "open_fire"; //damien";
- private final static String password = "open_fire"; //"test";
- private final static String hashedAuthentification = Base64.encodeBytes( ( user + ":" + password ).getBytes() );
- //private final static String defaultHost = "staging.travelportroomsandmore.com";
- private final static String defaultHost = "tp-dev.sprice.com";
- private final static String defaultProtocol = "https";
- private final static String defaultCurrency = "EUR";
- public final static DateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
- public final static DateFormat creditCardDateFormat = new SimpleDateFormat( "yyyy-MM" );
- private final static Integer defaultReflect = 0;
- private final static Integer defaultExhaustive = 0;
- private final static Language defaultLanguage = Language.English;
- private final static CharacterSet defaultCharacterSet = CharacterSet.Utf8;
- private final static int defaultSearchTimeout = 85000;
- //private final static String[] defaultViews = { "amenitieslist", "price", "results", "landmarkslist", "supplierslist" };
- private final static String[] defaultViews = { "results" };
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) throws Exception
- {
- 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 );
- InitializedHotelSearch initializedHotelSearch = initializeSearch( uninitializedHotelSearch );
- HotelSearchState hotelSearchState;
- do
- {
- hotelSearchState = pool( initializedHotelSearch );
- Thread.sleep( 2000 );
- }
- while( !hotelSearchState.getSearchStatus().equals( SearchStatus.End ) );
- System.out.println( "Search finished" );
- ResultsHotelView results = (ResultsHotelView) hotelSearchState.getViews().get( "results" );
- HotelResult result = (HotelResult) results.getResults().get( 0 );
- HotelOffer offer = (HotelOffer) result.getOffers().get( 0 );
- InitializedHotelReview initializedHotelReview = initializeReview( initializedHotelSearch, result, offer );
- HotelReviewState hotelReviewState;
- do
- {
- hotelReviewState = poolReview( initializedHotelSearch, initializedHotelReview );
- Thread.sleep( 2000 );
- }
- while( !hotelReviewState.getStatus().equals( ReviewStatus.End ) );
- System.out.println( "Review finished" );
- RoomOccupancy occupancy = new RoomOccupancy( hotelReviewState.getHotelReview().getRooms().get( 0 ).getOfferId() );
- occupancy.getGuests().add( new Guest( Salutation.Mister, "John", "Doe" ) );
- List<RoomOccupancy> occupancies = new ArrayList<RoomOccupancy>();
- occupancies.add( occupancy );
- 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 );
- while( details.getStatus().equals( BookingStatus.Progress ) )
- {
- Thread.sleep( 2000 );
- details = poolBooking( details.getId() );
- }
- System.out.println( "Booking done" );
- }
- public static InitializedHotelSearch initializeSearch( HotelSearch unitializedHotelSearch ) throws Exception
- {
- Map<String, String> data = new HashMap<String, String>();
- data.put( "city_code", unitializedHotelSearch.getCityCode() );
- data.put( "views", convertToAPIList( unitializedHotelSearch.getViews() ) );
- data.put( "lang", unitializedHotelSearch.getLanguage().toString() );
- data.put( "currency", unitializedHotelSearch.getCurrency() );
- data.put( "search_timeout", unitializedHotelSearch.getSearchTimeout().toString() );
- data.put( "charset", unitializedHotelSearch.getCharacterSet().toString() );
- data.put( "checkin", dateFormat.format( unitializedHotelSearch.getCheckin() ) );
- data.put( "checkout", dateFormat.format( unitializedHotelSearch.getCheckout() ) );
- data.put( "adults", unitializedHotelSearch.getAdultCount().toString() );
- data.put( "children", convertToAPIList( unitializedHotelSearch.getChildAges() ) );
- ApiResponse response = HotelService.getUrl( "/hotel/search", "POST", data );
- JSONObject js = new JSONObject( response.getBody() );
- String sessionIdentifier = js.getString( "session_id" );
- System.out.println( sessionIdentifier );
- return( new InitializedHotelSearch( unitializedHotelSearch.getCheckin(), unitializedHotelSearch.getCheckout(), sessionIdentifier ) );
- }
- public static ApiResponse poolJson( InitializedHotelSearch hotelSearch ) throws Exception
- {
- Map<String, String> data = new HashMap<String, String>();
- data.put( "session_id", hotelSearch.getSessionIdentifier() );
- data.put( "reflect", defaultReflect.toString() );
- data.put( "exhaustive", defaultExhaustive.toString() );
- data.put( "checkin", dateFormat.format( hotelSearch.getCheckin() ) );
- data.put( "checkout", dateFormat.format( hotelSearch.getCheckout() ) );
- data.put( "f_distance", convertToAPIList( new Float[] { hotelSearch.getMinimumDistance(), hotelSearch.getMaximumDistance() } ) );
- data.put( "p_results_size", hotelSearch.getResultsSize().toString() );
- data.put( "p_results_page", hotelSearch.getResultsPage().toString() );
- data.put( "p_results_sort", hotelSearch.getResultsSort().toString() );
- data.put( "f_amenitygroups", convertToAPIList( hotelSearch.getAmenities() ) );
- data.put( "f_name", hotelSearch.getName() );
- data.put( "f_suppliers", convertToAPIList( hotelSearch.getSuppliers() ) );
- data.put( "f_price", convertToAPIList( new Float[] { hotelSearch.getMinimumPrice(), hotelSearch.getMaximumPrice() } ) );
- data.put( "f_categories", convertToAPIList( hotelSearch.getCategories() ) );
- data.put( "f_paymenttype", hotelSearch.getPaymentType() == null ? "" : hotelSearch.getPaymentType().toString() );
- ApiResponse response = HotelService.getUrl( "/hotel/search/" + hotelSearch.getSessionIdentifier() + "/", "GET", data );
- return response;
- }
- public static HotelSearchState json_to_HotelSearchState( String response ) throws Exception
- {
- JSONObject js = new JSONObject(response );
- HashMap<String, HotelView> views = new HashMap<String, HotelView>();
- JSONArray jsonViews = js.getJSONArray( "views" );
- String keyName = "";
- for( int i = 0; i < jsonViews.length(); i++ )
- {
- JSONObject current = jsonViews.getJSONObject(i);
- if( current.getString("name").equals( "amenitieslist" ) )
- {
- views.put("amenitieslist", new JsonAmenitiesHotelView( current ) );
- }
- else if( current.getString("name").equals( "price" ) )
- {
- views.put("price", new JsonPriceHotelView( current ) );
- }
- else if( current.getString("name").equals( "results" ) )
- {
- views.put("results", new JsonResultsHotelView( current ) );
- }
- else if( current.getString("name").equals( "landmarkslist" ) )
- {
- views.put("landmarkslist", new JsonLandmarksHotelView( current ) );
- }
- else if( current.getString("name").equals( "supplierslist" ) )
- {
- views.put("supplierslist", new JsonSuppliersHotelView( current ) );
- }
- }
- 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 );
- return( hotelSearchState );
- }
- public static HotelSearchState pool( InitializedHotelSearch hotelSearch ) throws Exception
- {
- ApiResponse response = poolJson( hotelSearch );
- HotelSearchState hotelSearchState = json_to_HotelSearchState( response.getBody() );
- return( hotelSearchState );
- }
- public static InitializedHotelReview initializeReview( String session_id, String hotel_code, String supplier_code) throws Exception
- {
- Map<String, String> data = new HashMap<String, String>();
- data.put( "session_id", session_id );
- data.put( "hotel_code", hotel_code );
- data.put( "supplier_code", supplier_code );
- ApiResponse response = HotelService.getUrl( "/hotel/search/" + session_id + "/review", "POST", data );
- JSONObject js = new JSONObject( response.getBody() );
- return( new JsonInitializedHotelReview( js ) );
- }
- public static InitializedHotelReview initializeReview( InitializedHotelSearch hotelSearch, HotelResult hotelResult, HotelOffer hotelOffer ) throws Exception
- {
- Map<String, String> data = new HashMap<String, String>();
- data.put( "session_id", hotelSearch.getSessionIdentifier() );
- data.put( "hotel_code", hotelResult.getHotelCode() );
- data.put( "supplier_code", hotelOffer.getSupplierCode() );
- ApiResponse response = HotelService.getUrl( "/hotel/search/" + hotelSearch.getSessionIdentifier() + "/review", "POST", data );
- JSONObject js = new JSONObject( response.getBody() );
- return( new JsonInitializedHotelReview( js ) );
- }
- public static ApiResponse poolReviewJson( String offer_id, String sessionIdentifier ) throws Exception
- {
- Map<String, String> data = new HashMap<String, String>();
- data.put( "offer_id", offer_id );
- ApiResponse response = HotelService.getUrl( "/hotel/search/" + sessionIdentifier + "/review", "GET", data );
- return response;
- }
- public static HotelReviewState poolReview( InitializedHotelSearch hotelSearch, InitializedHotelReview initializedHotelReview ) throws Exception
- {
- ApiResponse response = poolReviewJson( initializedHotelReview.getOfferId(), hotelSearch.getSessionIdentifier() );
- JSONObject js = new JSONObject( response.getBody() );
- return( new JsonHotelReviewState( js ) );
- }
- 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
- {
- Map<String, String> data = new HashMap<String, String>();
- data.put( "session_id", session_id );
- data.put( "offer_id", offer_id );
- data.put( "booking_info[credit_card][credit_card_cvc]", cardVerificationNumber.toString() );
- data.put( "booking_info[credit_card][credit_card_expiration]", creditCardDateFormat.format( cardExpiry ) );
- data.put( "booking_info[credit_card][credit_card_holder_name]", cardHolderName );
- data.put( "booking_info[credit_card][credit_card_issue_bank]", cardIssueBank );
- data.put( "booking_info[credit_card][credit_card_issue_country]", cardIssueCountry );
- data.put( "booking_info[credit_card][credit_card_number]", cardNumber );
- data.put( "booking_info[credit_card][credit_card_type]", cardType.toString() );
- data.put( "booking_info[customer][customer_birth_date]", dateFormat.format( customerBirthDate ) );
- data.put( "booking_info[customer][customer_city_name]", customerCityName );
- data.put( "booking_info[customer][customer_country_code]", customerCountryCode );
- data.put( "booking_info[customer][customer_email]", customerEmail );
- data.put( "booking_info[customer][customer_first_name]", customerFirstName );
- data.put( "booking_info[customer][customer_last_name]", customerLastName );
- data.put( "booking_info[customer][customer_nationality]", customerNationality );
- data.put( "booking_info[customer][customer_phone_area_code]", customerPhoneAreaCode );
- data.put( "booking_info[customer][customer_phone_country_code]", customerPhoneCountryCode);
- data.put( "booking_info[customer][customer_phone_number]", customerPhoneNumber );
- data.put( "booking_info[customer][customer_post_code]", customerPostCode );
- data.put( "booking_info[customer][customer_salutation]", customerSalutation.toString() );
- data.put( "booking_info[customer][customer_street_address]", customerAddress );
- for( int i = 0; i < occupancies.size(); i++ )
- {
- RoomOccupancy occupancy = occupancies.get( i );
- data.put( "booking_info[rooms][room[" + i + "][offer_id]]", occupancy.getOfferId() );
- for( int j = 0; j < occupancy.getGuests().size(); j++ )
- {
- data.put( "booking_info[rooms][room[" + i + "][guest][" + j + "][salutation]]", occupancy.getGuests().get( j ).getSalutation().toString() );
- data.put( "booking_info[rooms][room[" + i + "][guest][" + j + "][first_name]]", occupancy.getGuests().get( j ).getFirstName() );
- data.put( "booking_info[rooms][room[" + i + "][guest][" + j + "][last_name]]", occupancy.getGuests().get( j ).getLastName() );
- }
- if (! occupancy.getGuestsChild().isEmpty())
- {
- for (int j = 0; j < occupancy.getGuestsChild().size(); j++) {
- data.put("booking_info[rooms][room[" + i + "][child_guest][" + j + "][age]]", Integer.toString(occupancy.getGuestsChild().get(j).getAge()));
- data.put("booking_info[rooms][room[" + i + "][child_guest][" + j + "][first_name]]", occupancy.getGuestsChild().get(j).getFirstName());
- data.put("booking_info[rooms][room[" + i + "][child_guest][" + j + "][last_name]]", occupancy.getGuestsChild().get(j).getLastName());
- }
- }
- }
- ApiResponse response = HotelService.getUrl( "/hotel/bookings", "POST", data );
- return response;
- }
- 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
- {
- 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 );
- JSONObject js = new JSONObject( response.getBody() );
- return( new JsonBookingDetails( js ) );
- }
- public static ApiResponse poolBookingJson( Integer bookingId ) throws Exception
- {
- ApiResponse response = HotelService.getUrl( "/hotel/bookings/" + bookingId.toString(), "GET", null );
- return response;
- }
- public static BookingDetails poolBooking( Integer bookingId ) throws Exception
- {
- ApiResponse response = HotelService.poolBookingJson(bookingId);
- JSONObject js = new JSONObject( response.getBody() );
- return( new JsonBookingDetails( js ) );
- }
- public static ApiResponse poolLstBookingJson( String user_id ) throws Exception
- {
- //client_id
- ApiResponse response = HotelService.getUrl( "/hotel/bookings/", "GET", null );
- return response;
- }
- public static void poolLstBooking(String user_id) throws Exception
- {
- ApiResponse response = HotelService.poolLstBookingJson(user_id);
- JSONObject js = new JSONObject( response.getBody() );
- //return null; //( new JsonBookingDetails( js ) );
- }
- public static String convertToAPIList( List<?> list )
- {
- return( convertToAPIList( list.toArray() ) );
- }
- public static String convertToAPIList( Object[] array )
- {
- String result = "";
- if( array == null || array.length == 0 )
- {
- return( "" );
- }
- for( int i = 0; i < array.length; i++ )
- {
- result += ( array[ i ] == null ? "" : array[ i ].toString() ) + ",";
- }
- return( result.substring( 0, result.length() - 1 ) );
- }
- public static ApiResponse getUrl( String path, String method, Map<String, String> postData ) throws Exception
- {
- String parameters = "";
- if( postData != null && postData.size() > 0 )
- {
- for (Map.Entry<String, String> entry : postData.entrySet())
- {
- String key = entry.getKey();
- String value = entry.getValue();
- parameters += key + "=" + ( value == null ? "" : URLEncoder.encode( value, "UTF-8" ) ) + "&";
- }
- }
- if( method.equals( "GET" ) && parameters.length() > 0 )
- {
- path += "?" + parameters;
- }
- System.out.println( defaultProtocol + "://" + defaultHost + path );
- URL url = new URL( defaultProtocol + "://" + defaultHost + path );
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setDoOutput( true );
- conn.addRequestProperty( "Authorization", "Basic " + hashedAuthentification );
- conn.addRequestProperty( "X-Requested-With", "XMLHttpRequest" );
- conn.setRequestMethod( method );
- if( method.equals( "POST" ) )
- {
- OutputStreamWriter writer = new OutputStreamWriter( conn.getOutputStream() );
- writer.write( parameters.substring( 0, parameters.length() - 1 ) );
- writer.flush();
- writer.close();
- }
- String responseLine = "";
- String responseBody = "";
- BufferedReader bufferedReader;
- try
- {
- bufferedReader = new BufferedReader( new InputStreamReader( conn.getInputStream() ) );
- }
- catch( IOException e )
- {
- bufferedReader = new BufferedReader( new InputStreamReader( conn.getErrorStream() ) );
- }
- finally
- {
- }
- while( ( responseLine = bufferedReader.readLine() ) != null )
- {
- responseBody += responseLine;
- }
- bufferedReader.close();
- System.out.println( responseBody );
- return( new ApiResponse( conn.getResponseCode(), responseBody ) );
- }
Add Comment
Please, Sign In to add comment