Subversion Repositories SmartDukaan

Rev

Rev 8509 | Rev 19421 | 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
{
27
 
7923 manish.sha 28
	public static ProcessShipmentReply getShipmentCreationReply(Order t_order ,ClientDetail clientDetail, WebAuthenticationDetail wac, String endpointAddress){
7905 manish.sha 29
		ProcessShipmentRequest request = new ProcessShipmentRequest(); // Build a request object
9775 manish.sha 30
        System.out.println("Account Number... "+clientDetail.getAccountNumber());
31
        System.out.println("Meter Number... "+clientDetail.getMeterNumber());
32
		request.setClientDetail(clientDetail);
7923 manish.sha 33
        request.setWebAuthenticationDetail(wac);
7905 manish.sha 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); 
7992 manish.sha 45
	    requestedShipment.setServiceType(ServiceType.STANDARD_OVERNIGHT); 
7905 manish.sha 46
	    requestedShipment.setPackagingType(PackagingType.YOUR_PACKAGING); 
47
	    requestedShipment.setShipper(addShipper());
48
	    requestedShipment.setRecipient(addRecipient(t_order));
7923 manish.sha 49
	    requestedShipment.setShippingChargesPayment(addShippingChargesPayment(clientDetail.getAccountNumber()));
7905 manish.sha 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();
7923 manish.sha 72
			updateEndPoint(service, endpointAddress);
7905 manish.sha 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);
9775 manish.sha 81
				//System.out.println("Response from FedEx End Successfull");
7905 manish.sha 82
			}	
83
 
84
		} catch (Exception e) {
85
		    e.printStackTrace();
86
		}
87
		return reply;
88
	}
89
	private static void writeServiceOutput(ProcessShipmentReply reply) throws Exception
90
	{
91
		try
92
		{
93
			//System.out.println(reply.getTransactionDetail().getCustomerTransactionId());
94
			CompletedShipmentDetail csd = reply.getCompletedShipmentDetail(); 
95
			String masterTrackingNumber=printMasterTrackingNumber(csd);
96
			//printShipmentOperationalDetails(csd.getOperationalDetail());
97
			//printShipmentRating(csd.getShipmentRating());
98
			CompletedPackageDetail cpd[] = csd.getCompletedPackageDetails();
99
			printPackageDetails(cpd);
100
			saveShipmentDocumentsToFile(csd.getShipmentDocuments(), masterTrackingNumber);
101
			//  If Express COD shipment is requested, the COD return label is returned as an Associated Shipment.
102
			getAssociatedShipmentLabels(csd.getAssociatedShipments());
103
		} catch (Exception e) {
104
			e.printStackTrace();
105
		}
106
		finally
107
		{
108
			//
109
		}
110
	}
111
 
112
	private static boolean isResponseOk(NotificationSeverityType notificationSeverityType) {
113
		if (notificationSeverityType == null) {
114
			return false;
115
		}
116
		if (notificationSeverityType.equals(NotificationSeverityType.WARNING) ||
117
			notificationSeverityType.equals(NotificationSeverityType.NOTE)    ||
118
			notificationSeverityType.equals(NotificationSeverityType.SUCCESS)) {
119
			return true;
120
		}
121
 		return false;
122
	}
123
 
124
	private static void printNotifications(Notification[] notifications) {
125
		System.out.println("Notifications:");
126
		if (notifications == null || notifications.length == 0) {
127
			System.out.println("  No notifications returned");
128
		}
129
		for (int i=0; i < notifications.length; i++){
130
			Notification n = notifications[i];
131
			System.out.print("  Notification no. " + i + ": ");
132
			if (n == null) {
133
				System.out.println("null");
134
				continue;
135
			} else {
136
				System.out.println("");
137
			}
138
			NotificationSeverityType nst = n.getSeverity();
139
 
140
			System.out.println("    Severity: " + (nst == null ? "null" : nst.getValue()));
141
			System.out.println("    Code: " + n.getCode());
142
			System.out.println("    Message: " + n.getMessage());
143
			System.out.println("    Source: " + n.getSource());
144
		}
145
	}
146
 
147
 
148
	private static Weight addPackageWeight(Double packageWeight, WeightUnits weightUnits){
149
		Weight weight = new Weight();
150
		weight.setUnits(weightUnits);
151
		weight.setValue(new BigDecimal(packageWeight.doubleValue()));
152
		return weight;
153
	}
154
 
155
 
156
	private static void printPackageDetails(CompletedPackageDetail[] cpd) throws Exception{
157
		if(cpd!=null){
158
			for (int i=0; i < cpd.length; i++) { // Package details / Rating information for each package
159
				String trackingNumber = cpd[i].getTrackingIds()[0].getTrackingNumber();
160
				//printTrackingNumbers(cpd[i]);
161
				//printPackageRating(cpd[i].getPackageRating());
162
				//	Write label buffer to file
163
				ShippingDocument sd = cpd[i].getLabel();
164
				saveLabelToFile(sd, trackingNumber);
165
				//printPackageOperationalDetails(cpd[i].getOperationalDetail());
166
				//System.out.println();
167
			}
168
		}
169
	}
170
 
171
 
172
	private static Party addShipper(){
173
	    Party shipperParty = new Party(); // Sender information
174
	    Contact shipperContact = new Contact();
175
	    shipperContact.setPersonName("Spice Online");
176
	    shipperContact.setCompanyName("Spice Online Retail Pvt Ltd");
177
	    shipperContact.setPhoneNumber("01203355131");
178
	    Address shipperAddress = new Address();
179
	    String address[] = new String[2];
180
	    address[0] = new String("Plot No. 19A-19B");
181
	    address[1] = new String("Sector - 125");
182
	    shipperAddress.setStreetLines(address);
183
	    shipperAddress.setCity("Noida");
184
	    shipperAddress.setStateOrProvinceCode("UP");
185
	    shipperAddress.setPostalCode("201301");
186
	    shipperAddress.setCountryCode("IN");	    
187
	    shipperParty.setContact(shipperContact);
188
	    shipperParty.setAddress(shipperAddress);
189
	    return shipperParty;
190
	}
191
 
192
	private static Party addRecipient(Order t_order){
193
	    Party recipientParty = new Party(); 
194
	    Contact recipientContact = new Contact();
195
	    recipientContact.setPersonName(t_order.getCustomer_name());
196
	    recipientContact.setPhoneNumber(t_order.getCustomer_mobilenumber());
197
	    Address recipientAddress = new Address();
198
	    String address[] = new String[2];
199
	    int len1= t_order.getCustomer_address1().length();
8509 manish.sha 200
	    int len2= t_order.getCustomer_address2()!=null ? t_order.getCustomer_address2().length() : 0;
7905 manish.sha 201
 
202
	    if(len1>35){
203
	    	address[0] = new String(t_order.getCustomer_address1().substring(len1-35, len1-1));
204
	    }
205
	    else{
206
	    	address[0] = new String(t_order.getCustomer_address1());
207
	    }
8408 manish.sha 208
	    if(len2!=0){
209
		    if(len2>35){
210
		    	address[1] = new String(t_order.getCustomer_address2().substring(len2-35, len2-1));
211
		    }
212
		    else{
213
		    	address[1] = new String(t_order.getCustomer_address2());
214
		    }
7905 manish.sha 215
	    }
216
	    else{
8408 manish.sha 217
	    	address[1]= " ";
7905 manish.sha 218
	    }
219
	    recipientAddress.setStreetLines(address);
220
	    recipientAddress.setCity(t_order.getCustomer_city());
221
	    recipientAddress.setStateOrProvinceCode("DL");
222
	    recipientAddress.setPostalCode(t_order.getCustomer_pincode());
223
	    recipientAddress.setCountryCode("IN");
224
	    recipientAddress.setResidential(Boolean.valueOf(true));	    
225
	    recipientParty.setContact(recipientContact);
226
	    recipientParty.setAddress(recipientAddress);
227
	    return recipientParty;
228
	}
229
 
7923 manish.sha 230
	private static Payment addShippingChargesPayment(String payorAccountNumber){
7905 manish.sha 231
	    Payment payment = new Payment(); 
232
	    payment.setPaymentType(PaymentType.SENDER);
233
	    Payor payor = new Payor();
234
	    Party responsibleParty = new Party();
7923 manish.sha 235
	    responsibleParty.setAccountNumber(payorAccountNumber);
7905 manish.sha 236
	    Address responsiblePartyAddress = new Address();
237
	    String address[] = new String[2];
238
	    address[0] = new String("Plot No. 19A-19B");
239
	    address[1] = new String("Sector - 125");
240
	    responsiblePartyAddress.setCountryCode("IN");
241
	    responsiblePartyAddress.setStreetLines(address);
242
	    responsiblePartyAddress.setCity("Noida");
243
	    responsiblePartyAddress.setStateOrProvinceCode("UP");
244
	    responsibleParty.setAddress(responsiblePartyAddress);
245
	    responsibleParty.setContact(new Contact());
246
		payor.setResponsibleParty(responsibleParty);
247
	    payment.setPayor(payor);
248
	    return payment;
249
	}
250
 
251
	public static CustomsClearanceDetail addCustomsClearanceDetail(Order t_order){
252
		CustomsClearanceDetail detail = new CustomsClearanceDetail();
253
		detail.setClearanceBrokerage(ClearanceBrokerageType.BROKER_INCLUSIVE);
254
		detail.setCustomsOptions(new CustomsOptionDetail(CustomsOptionType.TRIAL,"Trail Order"));
255
		Commodity commodities[] = new Commodity[1];
256
		commodities[0]= new Commodity();
257
		commodities[0].setNumberOfPieces(new NonNegativeInteger(1+""));
258
		commodities[0].setDescription("Sample Commodity Data");
259
		commodities[0].setCountryOfManufacture("India");
260
		commodities[0].setQuantity(new NonNegativeInteger(1+""));
261
		commodities[0].setQuantityUnits("EA");
262
		commodities[0].setWeight(new Weight(WeightUnits.LB,new BigDecimal(t_order.getTotal_weight())));
263
		commodities[0].setUnitPrice(new Money("INR",new BigDecimal(t_order.getTotal_amount())));
264
		CommercialInvoice ci= new CommercialInvoice();
265
		ci.setPurpose(PurposeOfShipmentType.SOLD);
266
		detail.setCommercialInvoice(ci);
267
		detail.setCommodities(commodities);
268
		detail.setCustomsValue(new Money("INR",new BigDecimal(t_order.getTotal_amount())));
269
		return detail;
270
	}
271
 
272
	private static ShipmentSpecialServicesRequested addShipmentSpecialServicesRequested(Order t_order){
273
	    ShipmentSpecialServicesRequested shipmentSpecialServicesRequested = new ShipmentSpecialServicesRequested();
274
	    ShipmentSpecialServiceType shipmentSpecialServiceType[]=new ShipmentSpecialServiceType[1];
275
	    shipmentSpecialServiceType[0]=ShipmentSpecialServiceType.COD;
276
	    shipmentSpecialServicesRequested.setSpecialServiceTypes(shipmentSpecialServiceType);
277
	    CodDetail codDetail = new CodDetail();
278
	    codDetail.setCollectionType(CodCollectionType.CASH);
279
	    Money codMoney = new Money();
280
	    codMoney.setCurrency("INR");
281
	    codMoney.setAmount(new BigDecimal(t_order.getTotal_amount()));
282
	    codDetail.setCodCollectionAmount(codMoney);
283
	    shipmentSpecialServicesRequested.setCodDetail(codDetail);
284
	    return shipmentSpecialServicesRequested;
285
	}
286
 
287
	private static RequestedPackageLineItem addRequestedPackageLineItem(Order t_order){
288
		RequestedPackageLineItem requestedPackageLineItem = new RequestedPackageLineItem();
289
		requestedPackageLineItem.setSequenceNumber(new PositiveInteger("1"));
290
		requestedPackageLineItem.setGroupPackageCount(new PositiveInteger("1"));
291
		requestedPackageLineItem.setWeight(addPackageWeight(new Double(t_order.getTotal_weight()), WeightUnits.LB));
292
		requestedPackageLineItem.setCustomerReferences(new CustomerReference[]{
8005 manish.sha 293
				addCustomerReference(CustomerReferenceType.CUSTOMER_REFERENCE.getValue(), t_order.getCustomer_name()),
294
				addCustomerReference(CustomerReferenceType.INVOICE_NUMBER.getValue(), t_order.getId()+""),
295
				addCustomerReference(CustomerReferenceType.P_O_NUMBER.getValue(), t_order.getId()+""),
7905 manish.sha 296
		});
297
		return requestedPackageLineItem;
298
	}
299
 
300
	private static CustomerReference addCustomerReference(String customerReferenceType, String customerReferenceValue){
301
		CustomerReference customerReference = new CustomerReference();
302
		customerReference.setCustomerReferenceType(CustomerReferenceType.fromString(customerReferenceType));
303
		customerReference.setValue(customerReferenceValue);
304
		return customerReference;
305
	}
306
 
307
	private static LabelSpecification addLabelSpecification(){
308
	    LabelSpecification labelSpecification = new LabelSpecification(); // Label specification	    
309
		labelSpecification.setImageType(ShippingDocumentImageType.PDF);// Image types PDF, PNG, DPL, ...	
310
	    labelSpecification.setLabelFormatType(LabelFormatType.COMMON2D); //LABEL_DATA_ONLY, COMMON2D
311
	    //labelSpecification.setLabelStockType(LabelStockType.value2); // STOCK_4X6.75_LEADING_DOC_TAB	    
312
	    //labelSpecification.setLabelPrintingOrientation(LabelPrintingOrientationType.TOP_EDGE_OF_TEXT_FIRST);
313
	    return labelSpecification;
314
	}
315
 
316
 
317
	private static String printMasterTrackingNumber(CompletedShipmentDetail csd){
318
		String trackingNumber="";
319
		if(null != csd.getMasterTrackingId()){
320
			trackingNumber = csd.getMasterTrackingId().getTrackingNumber();
321
		}
322
		return trackingNumber;
323
	}
324
 
325
	//Saving and displaying shipping documents (labels)
326
	private static void saveLabelToFile(ShippingDocument shippingDocument, String trackingNumber) throws Exception {
327
		ShippingDocumentPart[] sdparts = shippingDocument.getParts();
328
		for (int a=0; a < sdparts.length; a++) {
329
			ShippingDocumentPart sdpart = sdparts[a];
330
			String labelLocation = System.getProperty("file.label.location");
331
			if (labelLocation == null) {
332
				labelLocation = "/tmp/";
333
			}
334
			String shippingDocumentType = shippingDocument.getType().getValue();
335
			String labelFileName =  new String(labelLocation + shippingDocumentType + "." + trackingNumber + "_" + a + ".pdf");					
336
			File labelFile = new File(labelFileName);
337
			FileOutputStream fos = new FileOutputStream( labelFile );
338
			fos.write(sdpart.getImage());
339
			fos.close();
340
			System.out.println("\nlabel file name " + labelFile.getAbsolutePath());
341
		}
342
	}
343
 
344
	private static void saveShipmentDocumentsToFile(ShippingDocument[] shippingDocument, String trackingNumber) throws Exception{
345
		if(shippingDocument!= null){
346
			for(int i=0; i < shippingDocument.length; i++){
347
				ShippingDocumentPart[] sdparts = shippingDocument[i].getParts();
348
				for (int a=0; a < sdparts.length; a++) {
349
					ShippingDocumentPart sdpart = sdparts[a];
350
					String labelLocation = System.getProperty("file.label.location");
351
					if (labelLocation == null) {
352
						labelLocation = "/tmp/";
353
					}
354
					String labelName = shippingDocument[i].getType().getValue();
355
					String shippingDocumentLabelFileName =  new String(labelLocation + labelName + "." + trackingNumber + "_" + a + ".pdf");					
356
					File shippingDocumentLabelFile = new File(shippingDocumentLabelFileName);
357
					FileOutputStream fos = new FileOutputStream( shippingDocumentLabelFile );
358
					fos.write(sdpart.getImage());
359
					fos.close();
360
					System.out.println("\nAssociated shipment label file name " + shippingDocumentLabelFile.getAbsolutePath());
361
				}
362
			}
363
		}
364
	}
365
 
366
	private static void getAssociatedShipmentLabels(AssociatedShipmentDetail[] associatedShipmentDetail) throws Exception{
367
		if(associatedShipmentDetail!=null){
368
			for (int j=0; j < associatedShipmentDetail.length; j++){
369
				if(associatedShipmentDetail[j].getLabel()!=null && associatedShipmentDetail[j].getType()!=null){
370
					String trackingNumber = associatedShipmentDetail[j].getTrackingId().getTrackingNumber();
371
					String associatedShipmentType = associatedShipmentDetail[j].getType().getValue();
372
					ShippingDocument associatedShipmentLabel = associatedShipmentDetail[j].getLabel();
373
					saveAssociatedShipmentLabelToFile(associatedShipmentLabel, trackingNumber, associatedShipmentType);
374
				}
375
			}
376
		}
377
	}
378
 
379
	private static void saveAssociatedShipmentLabelToFile(ShippingDocument shippingDocument, String trackingNumber, String labelName) throws Exception {
380
		ShippingDocumentPart[] sdparts = shippingDocument.getParts();
381
		for (int a=0; a < sdparts.length; a++) {
382
			ShippingDocumentPart sdpart = sdparts[a];
383
			String labelLocation = System.getProperty("file.label.location");
384
			if (labelLocation == null) {
385
				labelLocation = "/tmp/";
386
			}
387
			String associatedShipmentLabelFileName =  new String(labelLocation + labelName + "." + trackingNumber + "_" + a + ".pdf");					
388
			File associatedShipmentLabelFile = new File(associatedShipmentLabelFileName);
389
			FileOutputStream fos = new FileOutputStream( associatedShipmentLabelFile );
390
			fos.write(sdpart.getImage());
391
			fos.close();
392
			System.out.println("\nAssociated shipment label file name " + associatedShipmentLabelFile.getAbsolutePath());
393
		}
394
	}
395
 
7923 manish.sha 396
	private static void updateEndPoint(ShipServiceLocator serviceLocator, String endPoint) {
7905 manish.sha 397
		if (endPoint != null) {
398
			serviceLocator.setShipServicePortEndpointAddress(endPoint);
399
		}
400
	}	
401
 
402
}