Subversion Repositories SmartDukaan

Rev

Rev 8005 | Rev 8509 | 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
	    }
8408 manish.sha 205
	    if(len2!=0){
206
		    if(len2>35){
207
		    	address[1] = new String(t_order.getCustomer_address2().substring(len2-35, len2-1));
208
		    }
209
		    else{
210
		    	address[1] = new String(t_order.getCustomer_address2());
211
		    }
7905 manish.sha 212
	    }
213
	    else{
8408 manish.sha 214
	    	address[1]= " ";
7905 manish.sha 215
	    }
216
	    recipientAddress.setStreetLines(address);
217
	    recipientAddress.setCity(t_order.getCustomer_city());
218
	    recipientAddress.setStateOrProvinceCode("DL");
219
	    recipientAddress.setPostalCode(t_order.getCustomer_pincode());
220
	    recipientAddress.setCountryCode("IN");
221
	    recipientAddress.setResidential(Boolean.valueOf(true));	    
222
	    recipientParty.setContact(recipientContact);
223
	    recipientParty.setAddress(recipientAddress);
224
	    return recipientParty;
225
	}
226
 
7923 manish.sha 227
	private static Payment addShippingChargesPayment(String payorAccountNumber){
7905 manish.sha 228
	    Payment payment = new Payment(); 
229
	    payment.setPaymentType(PaymentType.SENDER);
230
	    Payor payor = new Payor();
231
	    Party responsibleParty = new Party();
7923 manish.sha 232
	    responsibleParty.setAccountNumber(payorAccountNumber);
7905 manish.sha 233
	    Address responsiblePartyAddress = new Address();
234
	    String address[] = new String[2];
235
	    address[0] = new String("Plot No. 19A-19B");
236
	    address[1] = new String("Sector - 125");
237
	    responsiblePartyAddress.setCountryCode("IN");
238
	    responsiblePartyAddress.setStreetLines(address);
239
	    responsiblePartyAddress.setCity("Noida");
240
	    responsiblePartyAddress.setStateOrProvinceCode("UP");
241
	    responsibleParty.setAddress(responsiblePartyAddress);
242
	    responsibleParty.setContact(new Contact());
243
		payor.setResponsibleParty(responsibleParty);
244
	    payment.setPayor(payor);
245
	    return payment;
246
	}
247
 
248
	public static CustomsClearanceDetail addCustomsClearanceDetail(Order t_order){
249
		CustomsClearanceDetail detail = new CustomsClearanceDetail();
250
		detail.setClearanceBrokerage(ClearanceBrokerageType.BROKER_INCLUSIVE);
251
		detail.setCustomsOptions(new CustomsOptionDetail(CustomsOptionType.TRIAL,"Trail Order"));
252
		Commodity commodities[] = new Commodity[1];
253
		commodities[0]= new Commodity();
254
		commodities[0].setNumberOfPieces(new NonNegativeInteger(1+""));
255
		commodities[0].setDescription("Sample Commodity Data");
256
		commodities[0].setCountryOfManufacture("India");
257
		commodities[0].setQuantity(new NonNegativeInteger(1+""));
258
		commodities[0].setQuantityUnits("EA");
259
		commodities[0].setWeight(new Weight(WeightUnits.LB,new BigDecimal(t_order.getTotal_weight())));
260
		commodities[0].setUnitPrice(new Money("INR",new BigDecimal(t_order.getTotal_amount())));
261
		CommercialInvoice ci= new CommercialInvoice();
262
		ci.setPurpose(PurposeOfShipmentType.SOLD);
263
		detail.setCommercialInvoice(ci);
264
		detail.setCommodities(commodities);
265
		detail.setCustomsValue(new Money("INR",new BigDecimal(t_order.getTotal_amount())));
266
		return detail;
267
	}
268
 
269
	private static ShipmentSpecialServicesRequested addShipmentSpecialServicesRequested(Order t_order){
270
	    ShipmentSpecialServicesRequested shipmentSpecialServicesRequested = new ShipmentSpecialServicesRequested();
271
	    ShipmentSpecialServiceType shipmentSpecialServiceType[]=new ShipmentSpecialServiceType[1];
272
	    shipmentSpecialServiceType[0]=ShipmentSpecialServiceType.COD;
273
	    shipmentSpecialServicesRequested.setSpecialServiceTypes(shipmentSpecialServiceType);
274
	    CodDetail codDetail = new CodDetail();
275
	    codDetail.setCollectionType(CodCollectionType.CASH);
276
	    Money codMoney = new Money();
277
	    codMoney.setCurrency("INR");
278
	    codMoney.setAmount(new BigDecimal(t_order.getTotal_amount()));
279
	    codDetail.setCodCollectionAmount(codMoney);
280
	    shipmentSpecialServicesRequested.setCodDetail(codDetail);
281
	    return shipmentSpecialServicesRequested;
282
	}
283
 
284
	private static RequestedPackageLineItem addRequestedPackageLineItem(Order t_order){
285
		RequestedPackageLineItem requestedPackageLineItem = new RequestedPackageLineItem();
286
		requestedPackageLineItem.setSequenceNumber(new PositiveInteger("1"));
287
		requestedPackageLineItem.setGroupPackageCount(new PositiveInteger("1"));
288
		requestedPackageLineItem.setWeight(addPackageWeight(new Double(t_order.getTotal_weight()), WeightUnits.LB));
289
		requestedPackageLineItem.setCustomerReferences(new CustomerReference[]{
8005 manish.sha 290
				addCustomerReference(CustomerReferenceType.CUSTOMER_REFERENCE.getValue(), t_order.getCustomer_name()),
291
				addCustomerReference(CustomerReferenceType.INVOICE_NUMBER.getValue(), t_order.getId()+""),
292
				addCustomerReference(CustomerReferenceType.P_O_NUMBER.getValue(), t_order.getId()+""),
7905 manish.sha 293
		});
294
		return requestedPackageLineItem;
295
	}
296
 
297
	private static CustomerReference addCustomerReference(String customerReferenceType, String customerReferenceValue){
298
		CustomerReference customerReference = new CustomerReference();
299
		customerReference.setCustomerReferenceType(CustomerReferenceType.fromString(customerReferenceType));
300
		customerReference.setValue(customerReferenceValue);
301
		return customerReference;
302
	}
303
 
304
	private static LabelSpecification addLabelSpecification(){
305
	    LabelSpecification labelSpecification = new LabelSpecification(); // Label specification	    
306
		labelSpecification.setImageType(ShippingDocumentImageType.PDF);// Image types PDF, PNG, DPL, ...	
307
	    labelSpecification.setLabelFormatType(LabelFormatType.COMMON2D); //LABEL_DATA_ONLY, COMMON2D
308
	    //labelSpecification.setLabelStockType(LabelStockType.value2); // STOCK_4X6.75_LEADING_DOC_TAB	    
309
	    //labelSpecification.setLabelPrintingOrientation(LabelPrintingOrientationType.TOP_EDGE_OF_TEXT_FIRST);
310
	    return labelSpecification;
311
	}
312
 
313
 
314
	private static String printMasterTrackingNumber(CompletedShipmentDetail csd){
315
		String trackingNumber="";
316
		if(null != csd.getMasterTrackingId()){
317
			trackingNumber = csd.getMasterTrackingId().getTrackingNumber();
318
		}
319
		return trackingNumber;
320
	}
321
 
322
	//Saving and displaying shipping documents (labels)
323
	private static void saveLabelToFile(ShippingDocument shippingDocument, String trackingNumber) throws Exception {
324
		ShippingDocumentPart[] sdparts = shippingDocument.getParts();
325
		for (int a=0; a < sdparts.length; a++) {
326
			ShippingDocumentPart sdpart = sdparts[a];
327
			String labelLocation = System.getProperty("file.label.location");
328
			if (labelLocation == null) {
329
				labelLocation = "/tmp/";
330
			}
331
			String shippingDocumentType = shippingDocument.getType().getValue();
332
			String labelFileName =  new String(labelLocation + shippingDocumentType + "." + trackingNumber + "_" + a + ".pdf");					
333
			File labelFile = new File(labelFileName);
334
			FileOutputStream fos = new FileOutputStream( labelFile );
335
			fos.write(sdpart.getImage());
336
			fos.close();
337
			System.out.println("\nlabel file name " + labelFile.getAbsolutePath());
338
		}
339
	}
340
 
341
	private static void saveShipmentDocumentsToFile(ShippingDocument[] shippingDocument, String trackingNumber) throws Exception{
342
		if(shippingDocument!= null){
343
			for(int i=0; i < shippingDocument.length; i++){
344
				ShippingDocumentPart[] sdparts = shippingDocument[i].getParts();
345
				for (int a=0; a < sdparts.length; a++) {
346
					ShippingDocumentPart sdpart = sdparts[a];
347
					String labelLocation = System.getProperty("file.label.location");
348
					if (labelLocation == null) {
349
						labelLocation = "/tmp/";
350
					}
351
					String labelName = shippingDocument[i].getType().getValue();
352
					String shippingDocumentLabelFileName =  new String(labelLocation + labelName + "." + trackingNumber + "_" + a + ".pdf");					
353
					File shippingDocumentLabelFile = new File(shippingDocumentLabelFileName);
354
					FileOutputStream fos = new FileOutputStream( shippingDocumentLabelFile );
355
					fos.write(sdpart.getImage());
356
					fos.close();
357
					System.out.println("\nAssociated shipment label file name " + shippingDocumentLabelFile.getAbsolutePath());
358
				}
359
			}
360
		}
361
	}
362
 
363
	private static void getAssociatedShipmentLabels(AssociatedShipmentDetail[] associatedShipmentDetail) throws Exception{
364
		if(associatedShipmentDetail!=null){
365
			for (int j=0; j < associatedShipmentDetail.length; j++){
366
				if(associatedShipmentDetail[j].getLabel()!=null && associatedShipmentDetail[j].getType()!=null){
367
					String trackingNumber = associatedShipmentDetail[j].getTrackingId().getTrackingNumber();
368
					String associatedShipmentType = associatedShipmentDetail[j].getType().getValue();
369
					ShippingDocument associatedShipmentLabel = associatedShipmentDetail[j].getLabel();
370
					saveAssociatedShipmentLabelToFile(associatedShipmentLabel, trackingNumber, associatedShipmentType);
371
				}
372
			}
373
		}
374
	}
375
 
376
	private static void saveAssociatedShipmentLabelToFile(ShippingDocument shippingDocument, String trackingNumber, String labelName) throws Exception {
377
		ShippingDocumentPart[] sdparts = shippingDocument.getParts();
378
		for (int a=0; a < sdparts.length; a++) {
379
			ShippingDocumentPart sdpart = sdparts[a];
380
			String labelLocation = System.getProperty("file.label.location");
381
			if (labelLocation == null) {
382
				labelLocation = "/tmp/";
383
			}
384
			String associatedShipmentLabelFileName =  new String(labelLocation + labelName + "." + trackingNumber + "_" + a + ".pdf");					
385
			File associatedShipmentLabelFile = new File(associatedShipmentLabelFileName);
386
			FileOutputStream fos = new FileOutputStream( associatedShipmentLabelFile );
387
			fos.write(sdpart.getImage());
388
			fos.close();
389
			System.out.println("\nAssociated shipment label file name " + associatedShipmentLabelFile.getAbsolutePath());
390
		}
391
	}
392
 
7923 manish.sha 393
	private static void updateEndPoint(ShipServiceLocator serviceLocator, String endPoint) {
7905 manish.sha 394
		if (endPoint != null) {
395
			serviceLocator.setShipServicePortEndpointAddress(endPoint);
396
		}
397
	}	
398
 
399
}