Subversion Repositories SmartDukaan

Rev

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