Subversion Repositories SmartDukaan

Rev

Rev 7923 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
7905 manish.sha 1
package com;
2
import in.shop2020.config.ConfigException;
3
import in.shop2020.model.v1.order.Order;
4
import in.shop2020.thrift.clients.config.ConfigClient;
5
 
6
 
7
import java.util.*;
8
import java.io.*;
9
import java.math.*;
10
 
11
import org.apache.axis.types.NonNegativeInteger;
12
import org.apache.axis.types.PositiveInteger;
13
import com.fedex.ship.stub.*;
14
 
15
/** 
16
 * Sample code to call the FedEx Ship Service
17
 * <p>
18
 * com.fedex.ship.stub is generated via WSDL2Java, like this:<br>
19
 * <pre>
20
 * java org.apache.axis.wsdl.WSDL2Java -w -p com.fedex.ship.stub http://www.fedex.com/...../ShipService?wsdl
21
 * </pre>
22
 * 
23
 * This sample code has been tested with JDK 5 and Apache Axis 1.4
24
 */
25
 
26
 
27
public class ShipWebServiceClient 
28
{
29
 
30
	public static ProcessShipmentReply getShipmentCreationReply(Order t_order){
31
		ProcessShipmentRequest request = new ProcessShipmentRequest(); // Build a request object
32
        request.setClientDetail(createClientDetail());
33
        request.setWebAuthenticationDetail(createWebAuthenticationDetail());
34
 
35
        TransactionDetail transactionDetail = new TransactionDetail();
36
	    transactionDetail.setCustomerTransactionId("Domestic Express Ship Request"); // The client will get the same value back in the response
37
	    request.setTransactionDetail(transactionDetail);
38
 
39
	    VersionId versionId = new VersionId("ship", 12, 1, 0);
40
        request.setVersion(versionId);
41
 
42
        RequestedShipment requestedShipment = new RequestedShipment();
43
	    requestedShipment.setShipTimestamp(Calendar.getInstance()); 
44
	    requestedShipment.setDropoffType(DropoffType.REGULAR_PICKUP); 
45
	    requestedShipment.setServiceType(ServiceType.FEDEX_EXPRESS_SAVER); 
46
	    requestedShipment.setPackagingType(PackagingType.YOUR_PACKAGING); 
47
	    requestedShipment.setShipper(addShipper());
48
	    requestedShipment.setRecipient(addRecipient(t_order));
49
	    requestedShipment.setShippingChargesPayment(addShippingChargesPayment());
50
	    if(t_order.isCod()){
51
	    	requestedShipment.setSpecialServicesRequested(addShipmentSpecialServicesRequested(t_order)); 
52
	    }
53
	    else{
54
	    	requestedShipment.setSpecialServicesRequested(null); 
55
	    }
56
	    requestedShipment.setLabelSpecification(addLabelSpecification());
57
	    requestedShipment.setPackageCount(new NonNegativeInteger("1"));
58
	    requestedShipment.setCustomsClearanceDetail(addCustomsClearanceDetail(t_order));
59
	    RateRequestType rateRequestType[] = new RateRequestType[1];
60
	    rateRequestType[0] = RateRequestType.ACCOUNT; 
61
	    requestedShipment.setRateRequestTypes(new RateRequestType[]{rateRequestType[0]});
62
	    requestedShipment.setRequestedPackageLineItems(new RequestedPackageLineItem[] {addRequestedPackageLineItem(t_order)});
63
 
64
	    request.setRequestedShipment(requestedShipment);
65
	    ProcessShipmentReply reply = new ProcessShipmentReply();
66
	    try {
67
			// Initialize the service
68
			ShipServiceLocator service;
69
			ShipPortType port;
70
 
71
			service = new ShipServiceLocator();
72
			updateEndPoint(service);
73
			port = service.getShipServicePort();
74
 
75
			reply = port.processShipment(request); // This is the call to the ship web service passing in a request object and returning a reply object
76
 
77
			printNotifications(reply.getNotifications());
78
			if (isResponseOk(reply.getHighestSeverity())) // check if the call was successful
79
			{
80
				writeServiceOutput(reply);
81
			}	
82
 
83
		} catch (Exception e) {
84
		    e.printStackTrace();
85
		}
86
		return reply;
87
	}
88
	private static void writeServiceOutput(ProcessShipmentReply reply) throws Exception
89
	{
90
		try
91
		{
92
			//System.out.println(reply.getTransactionDetail().getCustomerTransactionId());
93
			CompletedShipmentDetail csd = reply.getCompletedShipmentDetail(); 
94
			String masterTrackingNumber=printMasterTrackingNumber(csd);
95
			//printShipmentOperationalDetails(csd.getOperationalDetail());
96
			//printShipmentRating(csd.getShipmentRating());
97
			CompletedPackageDetail cpd[] = csd.getCompletedPackageDetails();
98
			printPackageDetails(cpd);
99
			saveShipmentDocumentsToFile(csd.getShipmentDocuments(), masterTrackingNumber);
100
			//  If Express COD shipment is requested, the COD return label is returned as an Associated Shipment.
101
			getAssociatedShipmentLabels(csd.getAssociatedShipments());
102
		} catch (Exception e) {
103
			e.printStackTrace();
104
		}
105
		finally
106
		{
107
			//
108
		}
109
	}
110
 
111
	private static boolean isResponseOk(NotificationSeverityType notificationSeverityType) {
112
		if (notificationSeverityType == null) {
113
			return false;
114
		}
115
		if (notificationSeverityType.equals(NotificationSeverityType.WARNING) ||
116
			notificationSeverityType.equals(NotificationSeverityType.NOTE)    ||
117
			notificationSeverityType.equals(NotificationSeverityType.SUCCESS)) {
118
			return true;
119
		}
120
 		return false;
121
	}
122
 
123
	private static void printNotifications(Notification[] notifications) {
124
		System.out.println("Notifications:");
125
		if (notifications == null || notifications.length == 0) {
126
			System.out.println("  No notifications returned");
127
		}
128
		for (int i=0; i < notifications.length; i++){
129
			Notification n = notifications[i];
130
			System.out.print("  Notification no. " + i + ": ");
131
			if (n == null) {
132
				System.out.println("null");
133
				continue;
134
			} else {
135
				System.out.println("");
136
			}
137
			NotificationSeverityType nst = n.getSeverity();
138
 
139
			System.out.println("    Severity: " + (nst == null ? "null" : nst.getValue()));
140
			System.out.println("    Code: " + n.getCode());
141
			System.out.println("    Message: " + n.getMessage());
142
			System.out.println("    Source: " + n.getSource());
143
		}
144
	}
145
 
146
 
147
	private static Weight addPackageWeight(Double packageWeight, WeightUnits weightUnits){
148
		Weight weight = new Weight();
149
		weight.setUnits(weightUnits);
150
		weight.setValue(new BigDecimal(packageWeight.doubleValue()));
151
		return weight;
152
	}
153
 
154
 
155
	private static void printPackageDetails(CompletedPackageDetail[] cpd) throws Exception{
156
		if(cpd!=null){
157
			for (int i=0; i < cpd.length; i++) { // Package details / Rating information for each package
158
				String trackingNumber = cpd[i].getTrackingIds()[0].getTrackingNumber();
159
				//printTrackingNumbers(cpd[i]);
160
				//printPackageRating(cpd[i].getPackageRating());
161
				//	Write label buffer to file
162
				ShippingDocument sd = cpd[i].getLabel();
163
				saveLabelToFile(sd, trackingNumber);
164
				//printPackageOperationalDetails(cpd[i].getOperationalDetail());
165
				//System.out.println();
166
			}
167
		}
168
	}
169
 
170
 
171
	private static String getPayorAccountNumber() {
172
		//String payorAccountNumber = System.getProperty("Payor.AccountNumber");
173
		String payorAccountNumber ="";
174
		try {
175
			payorAccountNumber = ConfigClient.getClient().get("fedex_account_number");
176
		} catch (ConfigException e) {
177
			// TODO Auto-generated catch block
178
			e.printStackTrace();
179
		}
180
		/*if (payorAccountNumber == null) {
181
			payorAccountNumber = "510087089"; // Replace "XXX" with the payor account number
182
		}*/
183
		return payorAccountNumber;
184
	}
185
 
186
	private static Party addShipper(){
187
	    Party shipperParty = new Party(); // Sender information
188
	    Contact shipperContact = new Contact();
189
	    shipperContact.setPersonName("Spice Online");
190
	    shipperContact.setCompanyName("Spice Online Retail Pvt Ltd");
191
	    shipperContact.setPhoneNumber("01203355131");
192
	    Address shipperAddress = new Address();
193
	    String address[] = new String[2];
194
	    address[0] = new String("Plot No. 19A-19B");
195
	    address[1] = new String("Sector - 125");
196
	    shipperAddress.setStreetLines(address);
197
	    shipperAddress.setCity("Noida");
198
	    shipperAddress.setStateOrProvinceCode("UP");
199
	    shipperAddress.setPostalCode("201301");
200
	    shipperAddress.setCountryCode("IN");	    
201
	    shipperParty.setContact(shipperContact);
202
	    shipperParty.setAddress(shipperAddress);
203
	    return shipperParty;
204
	}
205
 
206
	private static Party addRecipient(Order t_order){
207
	    Party recipientParty = new Party(); 
208
	    Contact recipientContact = new Contact();
209
	    recipientContact.setPersonName(t_order.getCustomer_name());
210
	    recipientContact.setPhoneNumber(t_order.getCustomer_mobilenumber());
211
	    Address recipientAddress = new Address();
212
	    String address[] = new String[2];
213
	    int len1= t_order.getCustomer_address1().length();
214
	    int len2= t_order.getCustomer_address2().length();
215
 
216
	    if(len1>35){
217
	    	address[0] = new String(t_order.getCustomer_address1().substring(len1-35, len1-1));
218
	    }
219
	    else{
220
	    	address[0] = new String(t_order.getCustomer_address1());
221
	    }
222
	    if(len2>35){
223
	    	address[1] = new String(t_order.getCustomer_address2().substring(len2-35, len2-1));
224
	    }
225
	    else{
226
	    	address[1] = new String(t_order.getCustomer_address2());
227
	    }
228
	    recipientAddress.setStreetLines(address);
229
	    recipientAddress.setCity(t_order.getCustomer_city());
230
	    recipientAddress.setStateOrProvinceCode("DL");
231
	    recipientAddress.setPostalCode(t_order.getCustomer_pincode());
232
	    recipientAddress.setCountryCode("IN");
233
	    recipientAddress.setResidential(Boolean.valueOf(true));	    
234
	    recipientParty.setContact(recipientContact);
235
	    recipientParty.setAddress(recipientAddress);
236
	    return recipientParty;
237
	}
238
 
239
	private static Payment addShippingChargesPayment(){
240
	    Payment payment = new Payment(); 
241
	    payment.setPaymentType(PaymentType.SENDER);
242
	    Payor payor = new Payor();
243
	    Party responsibleParty = new Party();
244
	    responsibleParty.setAccountNumber(getPayorAccountNumber());
245
	    Address responsiblePartyAddress = new Address();
246
	    String address[] = new String[2];
247
	    address[0] = new String("Plot No. 19A-19B");
248
	    address[1] = new String("Sector - 125");
249
	    responsiblePartyAddress.setCountryCode("IN");
250
	    responsiblePartyAddress.setStreetLines(address);
251
	    responsiblePartyAddress.setCity("Noida");
252
	    responsiblePartyAddress.setStateOrProvinceCode("UP");
253
	    responsibleParty.setAddress(responsiblePartyAddress);
254
	    responsibleParty.setContact(new Contact());
255
		payor.setResponsibleParty(responsibleParty);
256
	    payment.setPayor(payor);
257
	    return payment;
258
	}
259
 
260
	public static CustomsClearanceDetail addCustomsClearanceDetail(Order t_order){
261
		CustomsClearanceDetail detail = new CustomsClearanceDetail();
262
		detail.setClearanceBrokerage(ClearanceBrokerageType.BROKER_INCLUSIVE);
263
		detail.setCustomsOptions(new CustomsOptionDetail(CustomsOptionType.TRIAL,"Trail Order"));
264
		Commodity commodities[] = new Commodity[1];
265
		commodities[0]= new Commodity();
266
		commodities[0].setNumberOfPieces(new NonNegativeInteger(1+""));
267
		commodities[0].setDescription("Sample Commodity Data");
268
		commodities[0].setCountryOfManufacture("India");
269
		commodities[0].setQuantity(new NonNegativeInteger(1+""));
270
		commodities[0].setQuantityUnits("EA");
271
		commodities[0].setWeight(new Weight(WeightUnits.LB,new BigDecimal(t_order.getTotal_weight())));
272
		commodities[0].setUnitPrice(new Money("INR",new BigDecimal(t_order.getTotal_amount())));
273
		CommercialInvoice ci= new CommercialInvoice();
274
		ci.setPurpose(PurposeOfShipmentType.SOLD);
275
		detail.setCommercialInvoice(ci);
276
		detail.setCommodities(commodities);
277
		detail.setCustomsValue(new Money("INR",new BigDecimal(t_order.getTotal_amount())));
278
		return detail;
279
	}
280
 
281
	private static ShipmentSpecialServicesRequested addShipmentSpecialServicesRequested(Order t_order){
282
	    ShipmentSpecialServicesRequested shipmentSpecialServicesRequested = new ShipmentSpecialServicesRequested();
283
	    ShipmentSpecialServiceType shipmentSpecialServiceType[]=new ShipmentSpecialServiceType[1];
284
	    shipmentSpecialServiceType[0]=ShipmentSpecialServiceType.COD;
285
	    shipmentSpecialServicesRequested.setSpecialServiceTypes(shipmentSpecialServiceType);
286
	    CodDetail codDetail = new CodDetail();
287
	    codDetail.setCollectionType(CodCollectionType.CASH);
288
	    Money codMoney = new Money();
289
	    codMoney.setCurrency("INR");
290
	    codMoney.setAmount(new BigDecimal(t_order.getTotal_amount()));
291
	    codDetail.setCodCollectionAmount(codMoney);
292
	    shipmentSpecialServicesRequested.setCodDetail(codDetail);
293
	    return shipmentSpecialServicesRequested;
294
	}
295
 
296
	private static RequestedPackageLineItem addRequestedPackageLineItem(Order t_order){
297
		RequestedPackageLineItem requestedPackageLineItem = new RequestedPackageLineItem();
298
		requestedPackageLineItem.setSequenceNumber(new PositiveInteger("1"));
299
		requestedPackageLineItem.setGroupPackageCount(new PositiveInteger("1"));
300
		requestedPackageLineItem.setWeight(addPackageWeight(new Double(t_order.getTotal_weight()), WeightUnits.LB));
301
		requestedPackageLineItem.setCustomerReferences(new CustomerReference[]{
302
				addCustomerReference(CustomerReferenceType.CUSTOMER_REFERENCE.getValue(), t_order.getCustomer_id()+""),
303
				addCustomerReference(CustomerReferenceType.INVOICE_NUMBER.getValue(), t_order.getInvoice_number()),
304
				addCustomerReference(CustomerReferenceType.P_O_NUMBER.getValue(), t_order.getPurchaseOrderNo()),
305
		});
306
		return requestedPackageLineItem;
307
	}
308
 
309
	private static CustomerReference addCustomerReference(String customerReferenceType, String customerReferenceValue){
310
		CustomerReference customerReference = new CustomerReference();
311
		customerReference.setCustomerReferenceType(CustomerReferenceType.fromString(customerReferenceType));
312
		customerReference.setValue(customerReferenceValue);
313
		return customerReference;
314
	}
315
 
316
	private static LabelSpecification addLabelSpecification(){
317
	    LabelSpecification labelSpecification = new LabelSpecification(); // Label specification	    
318
		labelSpecification.setImageType(ShippingDocumentImageType.PDF);// Image types PDF, PNG, DPL, ...	
319
	    labelSpecification.setLabelFormatType(LabelFormatType.COMMON2D); //LABEL_DATA_ONLY, COMMON2D
320
	    //labelSpecification.setLabelStockType(LabelStockType.value2); // STOCK_4X6.75_LEADING_DOC_TAB	    
321
	    //labelSpecification.setLabelPrintingOrientation(LabelPrintingOrientationType.TOP_EDGE_OF_TEXT_FIRST);
322
	    return labelSpecification;
323
	}
324
 
325
 
326
	private static String printMasterTrackingNumber(CompletedShipmentDetail csd){
327
		String trackingNumber="";
328
		if(null != csd.getMasterTrackingId()){
329
			trackingNumber = csd.getMasterTrackingId().getTrackingNumber();
330
		}
331
		return trackingNumber;
332
	}
333
 
334
	//Saving and displaying shipping documents (labels)
335
	private static void saveLabelToFile(ShippingDocument shippingDocument, String trackingNumber) throws Exception {
336
		ShippingDocumentPart[] sdparts = shippingDocument.getParts();
337
		for (int a=0; a < sdparts.length; a++) {
338
			ShippingDocumentPart sdpart = sdparts[a];
339
			String labelLocation = System.getProperty("file.label.location");
340
			if (labelLocation == null) {
341
				labelLocation = "/tmp/";
342
			}
343
			String shippingDocumentType = shippingDocument.getType().getValue();
344
			String labelFileName =  new String(labelLocation + shippingDocumentType + "." + trackingNumber + "_" + a + ".pdf");					
345
			File labelFile = new File(labelFileName);
346
			FileOutputStream fos = new FileOutputStream( labelFile );
347
			fos.write(sdpart.getImage());
348
			fos.close();
349
			System.out.println("\nlabel file name " + labelFile.getAbsolutePath());
350
		}
351
	}
352
 
353
	private static void saveShipmentDocumentsToFile(ShippingDocument[] shippingDocument, String trackingNumber) throws Exception{
354
		if(shippingDocument!= null){
355
			for(int i=0; i < shippingDocument.length; i++){
356
				ShippingDocumentPart[] sdparts = shippingDocument[i].getParts();
357
				for (int a=0; a < sdparts.length; a++) {
358
					ShippingDocumentPart sdpart = sdparts[a];
359
					String labelLocation = System.getProperty("file.label.location");
360
					if (labelLocation == null) {
361
						labelLocation = "/tmp/";
362
					}
363
					String labelName = shippingDocument[i].getType().getValue();
364
					String shippingDocumentLabelFileName =  new String(labelLocation + labelName + "." + trackingNumber + "_" + a + ".pdf");					
365
					File shippingDocumentLabelFile = new File(shippingDocumentLabelFileName);
366
					FileOutputStream fos = new FileOutputStream( shippingDocumentLabelFile );
367
					fos.write(sdpart.getImage());
368
					fos.close();
369
					System.out.println("\nAssociated shipment label file name " + shippingDocumentLabelFile.getAbsolutePath());
370
				}
371
			}
372
		}
373
	}
374
 
375
	private static void getAssociatedShipmentLabels(AssociatedShipmentDetail[] associatedShipmentDetail) throws Exception{
376
		if(associatedShipmentDetail!=null){
377
			for (int j=0; j < associatedShipmentDetail.length; j++){
378
				if(associatedShipmentDetail[j].getLabel()!=null && associatedShipmentDetail[j].getType()!=null){
379
					String trackingNumber = associatedShipmentDetail[j].getTrackingId().getTrackingNumber();
380
					String associatedShipmentType = associatedShipmentDetail[j].getType().getValue();
381
					ShippingDocument associatedShipmentLabel = associatedShipmentDetail[j].getLabel();
382
					saveAssociatedShipmentLabelToFile(associatedShipmentLabel, trackingNumber, associatedShipmentType);
383
				}
384
			}
385
		}
386
	}
387
 
388
	private static void saveAssociatedShipmentLabelToFile(ShippingDocument shippingDocument, String trackingNumber, String labelName) throws Exception {
389
		ShippingDocumentPart[] sdparts = shippingDocument.getParts();
390
		for (int a=0; a < sdparts.length; a++) {
391
			ShippingDocumentPart sdpart = sdparts[a];
392
			String labelLocation = System.getProperty("file.label.location");
393
			if (labelLocation == null) {
394
				labelLocation = "/tmp/";
395
			}
396
			String associatedShipmentLabelFileName =  new String(labelLocation + labelName + "." + trackingNumber + "_" + a + ".pdf");					
397
			File associatedShipmentLabelFile = new File(associatedShipmentLabelFileName);
398
			FileOutputStream fos = new FileOutputStream( associatedShipmentLabelFile );
399
			fos.write(sdpart.getImage());
400
			fos.close();
401
			System.out.println("\nAssociated shipment label file name " + associatedShipmentLabelFile.getAbsolutePath());
402
		}
403
	}
404
 
405
	private static ClientDetail createClientDetail() {
406
        ClientDetail clientDetail = new ClientDetail();
407
        String accountNumber ="";
408
		try {
409
			accountNumber = ConfigClient.getClient().get("fedex_account_number");
410
		} catch (ConfigException e) {
411
			// TODO Auto-generated catch block
412
			e.printStackTrace();
413
		}
414
 
415
        String meterNumber ="";
416
		try {
417
			meterNumber = ConfigClient.getClient().get("fedex_meter_number");
418
		} catch (ConfigException e) {
419
			// TODO Auto-generated catch block
420
			e.printStackTrace();
421
		}
422
 
423
        /*if (accountNumber == null) {
424
        	accountNumber = "510087089"; // Replace "XXX" with clients account number
425
        }
426
        if (meterNumber == null) {
427
        	meterNumber = "118585428"; // Replace "XXX" with clients meter number
428
        }*/
429
        clientDetail.setAccountNumber(accountNumber);
430
        clientDetail.setMeterNumber(meterNumber);
431
        return clientDetail;
432
	}
433
 
434
	private static WebAuthenticationDetail createWebAuthenticationDetail() {
435
        WebAuthenticationCredential wac = new WebAuthenticationCredential();
436
        String key="";
437
		try {
438
			key = ConfigClient.getClient().get("fedex_authenication_key");
439
		} catch (ConfigException e) {
440
			// TODO Auto-generated catch block
441
			e.printStackTrace();
442
		}
443
 
444
        String password="";
445
		try {
446
			password = ConfigClient.getClient().get("fedex_authenication_password");
447
		} catch (ConfigException e) {
448
			// TODO Auto-generated catch block
449
			e.printStackTrace();
450
		}
451
 
452
        /*if (key == null) {
453
        	key = "4XqfCFRFM4uXe6Wm"; // Replace "XXX" with clients key
454
        }
455
        if (password == null) {
456
        	password = "LtIgtKmluqOPikdNmTjXWPkTo"; // Replace "XXX" with clients password
457
        }*/
458
        wac.setKey(key);
459
        wac.setPassword(password);
460
		return new WebAuthenticationDetail(wac);
461
	}
462
 
463
	private static void updateEndPoint(ShipServiceLocator serviceLocator) {
464
		String endPoint = System.getProperty("endPoint");
465
		if (endPoint != null) {
466
			serviceLocator.setShipServicePortEndpointAddress(endPoint);
467
		}
468
	}	
469
 
470
}