Subversion Repositories SmartDukaan

Rev

Rev 19506 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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