0% found this document useful (0 votes)
31 views

Back Up

This document contains code for a HotelSearchService that sends SOAP requests to search for hotel availability and pricing. It takes a search request object, sends it to a SOAP endpoint to get results, processes the response, and returns a search response object. It handles currency conversion if pricing is returned in a different currency than requested.

Uploaded by

Issam Souissi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Back Up

This document contains code for a HotelSearchService that sends SOAP requests to search for hotel availability and pricing. It takes a search request object, sends it to a SOAP endpoint to get results, processes the response, and returns a search response object. It handles currency conversion if pricing is returned in a different currency than requested.

Uploaded by

Issam Souissi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

package com.example.worldsoftbackend.

services;

import com.example.worldsoftbackend.dto.Search.searchRequest.SearchRequest;
import com.example.worldsoftbackend.dto.Search.searchResponse.SearchResult;
import com.example.worldsoftbackend.models.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;

import javax.xml.bind.JAXB;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class HotelSearchService {

@Autowired
DeviseChangeService deviseChangeService;

@Autowired
CommissionCalculatorService commissionCalculatorService;

List<HotelAvailable> hotels;

public SearchResult sendSoap(SearchRequest searchReq, boolean withprice) {

try {
// Create SOAP Connection
// SOAPConnectionFactory soapConnectionFactory =
SOAPConnectionFactory.newInstance();
// SOAPConnection soapConnection =
soapConnectionFactory.createConnection();
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
Document document =
DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

Marshaller marshaller =
JAXBContext.newInstance(searchReq.getClass()).createMarshaller();
marshaller.marshal(searchReq, document);
TransformerFactory transformerFactory =
TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapMessage.getSOAPPart().getContent();
SimpleDateFormat format = new
SimpleDateFormat("yyyyMMddHHmmssS");
StringWriter sw1 = new StringWriter();
JAXB.marshal(searchReq, sw1);

String xmlString = sw1.toString();

xmlString = xmlString.replace("<filters>",
"<filters
xmlns:a=\"http://us.dotwconnect.com/xsd/atomicCondition\"
xmlns:c=\"http://us.dotwconnect.com/xsd/complexCondition\">");
xmlString = xmlString.replace("<?xml version=\"1.0\"
encoding=\"UTF-8\" standalone=\"yes\"?>", "");
// the problem dosen't appear when no=1
xmlString = xmlString.replace("<children no=\"0\"/>", "<children
no=\"0\"></children>");
xmlString = xmlString.replace("<a:condition>\n" + "
<operator>AND</operator>\n"
+ " </a:condition>",
"<operator>AND</operator>");

xmlString = xmlString.replace("<a:condition>\n" + "


<operator>OR</operator>\n"
+ " </a:condition>",
"<operator>OR</operator>");
System.out.println("first : " + xmlString);

if (!withprice) {
int a = xmlString.indexOf("<fields>");
System.out.println("index a is : " + a);
int b = xmlString.indexOf("</fields>");
System.out.println("index b = " + b);
String fields = xmlString.substring(a, b + 9);
System.out.println("fields ====> " + fields);
xmlString = xmlString.replace(fields, "");

int c = xmlString.indexOf("</return>");
System.out.println("index of c : " + c);

xmlString = insertString(xmlString, fields, c - 1);


}

System.out.println("second : " + xmlString);

File doc = new File(System.getProperty("user.dir") +


File.separator + "HotelRQ");

if (!doc.exists()) {
doc.mkdir();
}

BufferedWriter writer = new BufferedWriter(new


FileWriter(System.getProperty("user.dir") + File.separator
+ "HotelRQ" + File.separator + format.format(new
Date()) + "SearchRQ" + ".xml", true));

writer.write(xmlString);
writer.close();
URL url = new
URL("http://xmldev.dotwconnect.com/gatewayV4.dotw");
HttpURLConnection httpsURLConnection = (HttpURLConnection)
url.openConnection();
httpsURLConnection.setDoInput(true);
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setRequestProperty("Content-Type",
"text/xml");
httpsURLConnection.setRequestProperty("Accept-Enconding",
"gzip");
httpsURLConnection.setRequestMethod("POST");

DataOutputStream wr = new
DataOutputStream(httpsURLConnection.getOutputStream());
wr.writeBytes(xmlString);
wr.flush();
wr.close();

BufferedReader in = new BufferedReader(new


InputStreamReader(httpsURLConnection.getInputStream()));

String inputLine;
StringBuffer responce = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
responce.append(inputLine);
}
in.close();

httpsURLConnection.disconnect();
File folderRs = new File(System.getProperty("user.dir") +
File.separator + "HotelRS");
if (!folderRs.exists()) {
folderRs.mkdir();
}
File response = new File(System.getProperty("user.dir") +
File.separator + "HotelRS" + File.separator
+ format.format(new Date()) + "searchRS" + ".xml");

BufferedWriter bwr = new BufferedWriter(new


FileWriter(response));
bwr.write(responce.toString());
bwr.flush();
bwr.close();
transformer = transformerFactory.newTransformer();
java.io.StringWriter swres = new java.io.StringWriter();
StreamResult result11 = new StreamResult(swres);
transformer.transform(sourceContent, result11);
StringReader reader = new StringReader(responce.toString());
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader xsr = factory.createXMLStreamReader(reader);

SearchResult rs = new SearchResult();

JAXBContext jc = JAXBContext.newInstance(rs.getClass());
Unmarshaller unmarshaller = jc.createUnmarshaller();
rs = unmarshaller.unmarshal(xsr, rs.getClass()).getValue();
return rs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

public SearchHotelResponse searchHotels(SearchHotelRequest model) {


System.out.println("modeeeeeeeeeeeeeeeee l :
"+model.getRooms().get(0).getNbInfant());
SearchRequest searchReq = new SearchRequest(model);
String currencyGds = null ;

SearchResult rs = this.sendSoap(searchReq, false);

SearchRequest searchPrice = new SearchRequest(model, true);


SearchResult rsPrice = this.sendSoap(searchPrice, true);
BigDecimal finalTxCHange = BigDecimal.ONE;
try {

SearchHotelResponse responses = new SearchHotelResponse();

List<HotelAvailable> hotels = new ArrayList<>();


if (rs.getHotels() != null && rsPrice.getHotels() != null) {
SearchResult finalRs = rs;
responses.setSuccess(Boolean.valueOf(rs.getSuccessful()));
responses.setNbHotel(rs.getHotels().getHotel().size());

/**
* here for price with commission
*
*/
try {
System.out.println("hey rs : " + rs.toString());
System.out.println("currency gds 222 : "
+
rsPrice.getHotels().getHotel().get(0).getRooms().getRoom().get(0).getRoomType().get
(0)
.getRateBases().getRateBasis(
).get(0).getRateType().getCurrencyid());
if
(rsPrice.getHotels().getHotel().get(0).getRooms().getRoom().get(0).getRoomType().ge
t(0)
.getRateBases().getRateBasis().get(0).get
RateType().getCurrencyid().equals("520"))
currencyGds = "USD";
System.out.println("devise tiers : " +
model.getCurrentDevise());
System.out.println("id entite : " +
model.getIdEntiteUser());
finalTxCHange =
deviseChangeService.getTxChangeFromTo(currencyGds,
model.getCurrentDevise(),
model.getIdEntiteUser(), BigDecimal.ONE);
System.out.println("txChange : " + finalTxCHange);
} catch (Exception e) {
finalTxCHange = new BigDecimal(1);
}
// GlobalCommisionRequest globalCommisionRequest = new
GlobalCommisionRequest();
// globalCommisionRequest.setAgenceComission(null);
// globalCommisionRequest.setFinalTxCHange(finalTxCHange);
// globalCommisionRequest.setGds(model.getGds());
//
globalCommisionRequest.setIdEntiteCible(model.getIdEntiteUser());
// globalCommisionRequest.setIdTiers(model.getIdTiers());
//
globalCommisionRequest.setIdUserTiers(model.getIdUserTiers());

// ----------------end----------------//

rs.getHotels().getHotel().forEach(hotelType -> {

rsPrice.getHotels().getHotel().stream().forEach(hotelWithPricePrice -> {
if
(hotelType.getHotelid().equals(hotelWithPricePrice.getHotelid())) {

///////////////////// For Price


Fare farePrice = new Fare();
// globalCommisionRequest.setMnt(new
BigDecimal(hotelWithPricePrice.getRooms().getRoom().get(0)
// .getRoomType().get(0).getRate
Bases().getRateBasis().get(0).getTotal()));
// GlobalComission result1 =
commissionCalculatorService
// .getCommissionAvailability(gl
obalCommisionRequest);

System.out.println("amount gds is :::::


" + hotelWithPricePrice.getRooms().getRoom().get(0)
.getRoomType().get(0).getRate
Bases().getRateBasis().get(0).getTotal());
System.out.println("total fare is ::::: "
+ hotelWithPricePrice.getRooms().getRoom().get(0)
.getRoomType().get(0).getRate
Bases().getRateBasis().get(0).getTotal());
//
farePrice.setAmount(result1.getMntFinalwithCommission());
System.out.println("amount is ::::: " +
farePrice.getAmount());
String currencyGdss = null;
if
(rsPrice.getHotels().getHotel().get(0).getRooms().getRoom().get(0).getRoomType().ge
t(0)
.getRateBases().getRateBasis(
).get(0).getRateType().getCurrencyid().equals("520"))
currencyGdss = "USD";
farePrice.setCurrencyGds(currencyGdss);

farePrice.setCurrency(model.getCurrentDevise());
farePrice.setTotalFare(new
BigDecimal(hotelWithPricePrice.getRooms().getRoom().get(0)
.getRoomType().get(0).getRate
Bases().getRateBasis().get(0).getTotal()));
farePrice.setForRoomType(
hotelWithPricePrice.getRooms().getRoom().get(0).getRoomType().get(0).getName());
//
farePrice.setAgentMarkUp(result1.getCustomerCharge());
//
farePrice.setNetCharge(result1.getNetCharge());
//
farePrice.setGsaComm(result1.getGsa_comm());

/////////////////////////// End Price

HotelAvailable hotelAvailable = new


HotelAvailable();
hotelAvailable.setPrice(farePrice);

hotelAvailable.setHotelId(hotelType.getHotelid());

hotelAvailable.setName(hotelType.getHotelName());

hotelAvailable.setAdress(hotelType.getFullAddress().getHotelStreetAddress() +
" ,"
+
hotelType.getFullAddress().getHotelZipCode() + " ,"
+
hotelType.getFullAddress().getHotelCountry() + " ,"
+
hotelType.getFullAddress().getHotelCity());

hotelAvailable.setDescription(hotelType.getDescription1().getLanguage() +
" ,"
+
hotelType.getDescription2().getLanguage());

String rating =
String.valueOf(hotelType.getRating());
String newRating = "";
//
// int firstDigit =
Integer.parseInt(rating.substring(0, 1));
// int restDigit =
Integer.parseInt(rating.substring(1, rating.length()));
//
// String newRating = firstDigit + "." +
restDigit;
// hotelAvailable.setRatings(new
BigDecimal(newRating));

switch (rating) {
case "559":
newRating = "1";
break;
case "560":
newRating = "2";
break;
case "561":
newRating = "3";
break;
case "562":
newRating = "4";
break;
case "563":
newRating = "5";
break;
case "55835":
newRating = "0";
break;
case "48055":
newRating = "10";
break;

default:
break;
}
if (newRating !=null)
hotelAvailable.setStars(new
BigDecimal(newRating));

hotelAvailable.setLattitude(String.valueOf(hotelType.getGeoPoint().getLat()));

hotelAvailable.setLongitude(String.valueOf(hotelType.getGeoPoint().getLng()));

List<String> images = new ArrayList<>();


if (hotelType.getImages() != null &&
hotelType.getImages().getHotelImages() != null
&&
hotelType.getImages().getHotelImages().getThumb() != null) {

images.add(hotelType.getImages().getHotelImages().getThumb());

hotelAvailable.setLogo(hotelType.getImages().getHotelImages().getThumb());
}

if (hotelType.getImages() != null &&


hotelType.getImages().getHotelImages() != null
&&
hotelType.getImages().getHotelImages().getImage() != null) {

hotelType.getImages().getHotelImages().getImage().stream().forEach(img -> {
images.add(img.getUrl());
});
}

hotelAvailable.setPictures(images);

/**
* here for the amenitie, Leisure and
business
*/
// System.out.println("amenitie is !!!! "+
hotelType.getAmenitie().getLanguage().get(0).getAmenitieItem().get(0));

hotelAvailable.setCheckIn(model.getCheckIn());

hotelAvailable.setCheckOut(model.getCheckOut());
hotelAvailable.setSessionId(finalRs.getIp());

hotelAvailable.setVersion(finalRs.getVersion());

hotelAvailable.setCity(model.getCityCode());
hotelAvailable.setGds("DW");

hotelAvailable.setCodeDotw(model.getCodeDotw());
hotels.add(hotelAvailable);
}
});
});
}

GlobalCommisionRequest commissionRequest = new


GlobalCommisionRequest();
commissionRequest.setFinalTxCHange(finalTxCHange);
commissionRequest.setGds(model.getGds());
commissionRequest.setIdEntiteCible(model.getIdEntiteUser());
commissionRequest.setIdTiers(model.getIdTiers());
commissionRequest.setHotels(hotels);
System.out.println("size before Com"+hotels.size());
List<HotelAvailable> result1 =
commissionCalculatorService.getNewCommissionAvailability(commissionRequest);
System.out.println("size after com"+result1.size());

responses.setHotels(result1);

return responses;

} catch (Exception e) {
System.err.println("Error occurred while sending SOAP Request to
Server ");
e.printStackTrace();
}
return null;
}

public static String insertString(String originalString, String


stringToBeInserted, int index) {

String newString = new String();


for (int i = 0; i < originalString.length(); i++) {

// Insert the original string character


// into the new string
newString += originalString.charAt(i);

if (i == index) {

// Insert the string to be inserted


// into the new string
newString += stringToBeInserted;
}
}
// return the modified String
return newString;
}

You might also like