Subversion Repositories SmartDukaan

Rev

Rev 8509 | Rev 19492 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com;
import in.shop2020.model.v1.order.Order;


import java.util.*;
import java.io.*;
import java.math.*;

import org.apache.axis.types.NonNegativeInteger;
import org.apache.axis.types.PositiveInteger;
import com.fedex.ship.stub.*;

/** 
 * Sample code to call the FedEx Ship Service
 * <p>
 * com.fedex.ship.stub is generated via WSDL2Java, like this:<br>
 * <pre>
 * java org.apache.axis.wsdl.WSDL2Java -w -p com.fedex.ship.stub http://www.fedex.com/...../ShipService?wsdl
 * </pre>
 * 
 * This sample code has been tested with JDK 5 and Apache Axis 1.4
 */


public class ShipWebServiceClient 
{

        public static ProcessShipmentReply getShipmentCreationReply(Order t_order ,ClientDetail clientDetail, WebAuthenticationDetail wac, String endpointAddress){
                ProcessShipmentRequest request = new ProcessShipmentRequest(); // Build a request object
        System.out.println("Account Number... "+clientDetail.getAccountNumber());
        System.out.println("Meter Number... "+clientDetail.getMeterNumber());
                request.setClientDetail(clientDetail);
        request.setWebAuthenticationDetail(wac);
        
        TransactionDetail transactionDetail = new TransactionDetail();
            transactionDetail.setCustomerTransactionId("Domestic Express Ship Request"); // The client will get the same value back in the response
            request.setTransactionDetail(transactionDetail);
            
            VersionId versionId = new VersionId("ship", 12, 1, 0);
        request.setVersion(versionId);
           
        RequestedShipment requestedShipment = new RequestedShipment();
            requestedShipment.setShipTimestamp(Calendar.getInstance()); 
            requestedShipment.setDropoffType(DropoffType.REGULAR_PICKUP); 
            requestedShipment.setServiceType(ServiceType.STANDARD_OVERNIGHT); 
            requestedShipment.setPackagingType(PackagingType.YOUR_PACKAGING); 
            requestedShipment.setShipper(addShipper());
            requestedShipment.setRecipient(addRecipient(t_order));
            requestedShipment.setShippingChargesPayment(addShippingChargesPayment(clientDetail.getAccountNumber()));
            if(t_order.isCod()){
                requestedShipment.setSpecialServicesRequested(addShipmentSpecialServicesRequested(t_order)); 
            }
            else{
                requestedShipment.setSpecialServicesRequested(null); 
            }
            requestedShipment.setLabelSpecification(addLabelSpecification());
            requestedShipment.setPackageCount(new NonNegativeInteger("1"));
            requestedShipment.setCustomsClearanceDetail(addCustomsClearanceDetail(t_order));
            RateRequestType rateRequestType[] = new RateRequestType[1];
            rateRequestType[0] = RateRequestType.ACCOUNT; 
            requestedShipment.setRateRequestTypes(new RateRequestType[]{rateRequestType[0]});
            requestedShipment.setRequestedPackageLineItems(new RequestedPackageLineItem[] {addRequestedPackageLineItem(t_order)});
        
            request.setRequestedShipment(requestedShipment);
            ProcessShipmentReply reply = new ProcessShipmentReply();
            try {
                        // Initialize the service
                        ShipServiceLocator service;
                        ShipPortType port;
                        
                        service = new ShipServiceLocator();
                        updateEndPoint(service, endpointAddress);
                        port = service.getShipServicePort();

                        reply = port.processShipment(request); // This is the call to the ship web service passing in a request object and returning a reply object
                        
                        printNotifications(reply.getNotifications());
                        if (isResponseOk(reply.getHighestSeverity())) // check if the call was successful
                        {
                                writeServiceOutput(reply);
                                //System.out.println("Response from FedEx End Successfull");
                        }       

                } catch (Exception e) {
                    e.printStackTrace();
                }
                return reply;
        }
        private static void writeServiceOutput(ProcessShipmentReply reply) throws Exception
        {
                try
                {
                        //System.out.println(reply.getTransactionDetail().getCustomerTransactionId());
                        CompletedShipmentDetail csd = reply.getCompletedShipmentDetail(); 
                        String masterTrackingNumber=printMasterTrackingNumber(csd);
                        //printShipmentOperationalDetails(csd.getOperationalDetail());
                        //printShipmentRating(csd.getShipmentRating());
                        CompletedPackageDetail cpd[] = csd.getCompletedPackageDetails();
                        printPackageDetails(cpd);
                        saveShipmentDocumentsToFile(csd.getShipmentDocuments(), masterTrackingNumber);
                        //  If Express COD shipment is requested, the COD return label is returned as an Associated Shipment.
                        getAssociatedShipmentLabels(csd.getAssociatedShipments());
                } catch (Exception e) {
                        e.printStackTrace();
                }
                finally
                {
                        //
                }
        }
        
        private static boolean isResponseOk(NotificationSeverityType notificationSeverityType) {
                if (notificationSeverityType == null) {
                        return false;
                }
                if (notificationSeverityType.equals(NotificationSeverityType.WARNING) ||
                        notificationSeverityType.equals(NotificationSeverityType.NOTE)    ||
                        notificationSeverityType.equals(NotificationSeverityType.SUCCESS)) {
                        return true;
                }
                return false;
        }

        private static void printNotifications(Notification[] notifications) {
                System.out.println("Notifications:");
                if (notifications == null || notifications.length == 0) {
                        System.out.println("  No notifications returned");
                }
                for (int i=0; i < notifications.length; i++){
                        Notification n = notifications[i];
                        System.out.print("  Notification no. " + i + ": ");
                        if (n == null) {
                                System.out.println("null");
                                continue;
                        } else {
                                System.out.println("");
                        }
                        NotificationSeverityType nst = n.getSeverity();

                        System.out.println("    Severity: " + (nst == null ? "null" : nst.getValue()));
                        System.out.println("    Code: " + n.getCode());
                        System.out.println("    Message: " + n.getMessage());
                        System.out.println("    Source: " + n.getSource());
                }
        }
        
        
        private static Weight addPackageWeight(Double packageWeight, WeightUnits weightUnits){
                Weight weight = new Weight();
                weight.setUnits(weightUnits);
                weight.setValue(new BigDecimal(packageWeight.doubleValue()));
                return weight;
        }
        
        
        private static void printPackageDetails(CompletedPackageDetail[] cpd) throws Exception{
                if(cpd!=null){
                        for (int i=0; i < cpd.length; i++) { // Package details / Rating information for each package
                                String trackingNumber = cpd[i].getTrackingIds()[0].getTrackingNumber();
                                //printTrackingNumbers(cpd[i]);
                                //printPackageRating(cpd[i].getPackageRating());
                                //      Write label buffer to file
                                ShippingDocument sd = cpd[i].getLabel();
                                saveLabelToFile(sd, trackingNumber);
                                //printPackageOperationalDetails(cpd[i].getOperationalDetail());
                                //System.out.println();
                        }
                }
        }
                        
                
        private static Party addShipper(){
            Party shipperParty = new Party(); // Sender information
            Contact shipperContact = new Contact();
            shipperContact.setPersonName("Spice Online");
            shipperContact.setCompanyName("Spice Online Retail Pvt Ltd");
            shipperContact.setPhoneNumber("01203355131");
            Address shipperAddress = new Address();
            String address[] = new String[2];
            address[0] = new String("Plot No. 19A-19B");
            address[1] = new String("Sector - 125");
            shipperAddress.setStreetLines(address);
            shipperAddress.setCity("Noida");
            shipperAddress.setStateOrProvinceCode("UP");
            shipperAddress.setPostalCode("201301");
            shipperAddress.setCountryCode("IN");            
            shipperParty.setContact(shipperContact);
            shipperParty.setAddress(shipperAddress);
            return shipperParty;
        }
        
        private static Party addRecipient(Order t_order){
            Party recipientParty = new Party(); 
            Contact recipientContact = new Contact();
            recipientContact.setPersonName(t_order.getCustomer_name());
            recipientContact.setPhoneNumber(t_order.getCustomer_mobilenumber());
            Address recipientAddress = new Address();
            String address[] = new String[2];
            int len1= t_order.getCustomer_address1().length();
            int len2= t_order.getCustomer_address2()!=null ? t_order.getCustomer_address2().length() : 0;
            
            if(len1>35){
                address[0] = new String(t_order.getCustomer_address1().substring(len1-35, len1-1));
            }
            else{
                address[0] = new String(t_order.getCustomer_address1());
            }
            if(len2!=0){
                    if(len2>35){
                        address[1] = new String(t_order.getCustomer_address2().substring(len2-35, len2-1));
                    }
                    else{
                        address[1] = new String(t_order.getCustomer_address2());
                    }
            }
            else{
                address[1]= " ";
            }
            recipientAddress.setStreetLines(address);
            recipientAddress.setCity(t_order.getCustomer_city());
            recipientAddress.setStateOrProvinceCode("DL");
            recipientAddress.setPostalCode(t_order.getCustomer_pincode());
            recipientAddress.setCountryCode("IN");
            recipientAddress.setResidential(Boolean.valueOf(true));         
            recipientParty.setContact(recipientContact);
            recipientParty.setAddress(recipientAddress);
            return recipientParty;
        }
        
        private static Payment addShippingChargesPayment(String payorAccountNumber){
            Payment payment = new Payment(); 
            payment.setPaymentType(PaymentType.SENDER);
            Payor payor = new Payor();
            Party responsibleParty = new Party();
            responsibleParty.setAccountNumber(payorAccountNumber);
            Address responsiblePartyAddress = new Address();
            String address[] = new String[2];
            address[0] = new String("Plot No. 19A-19B");
            address[1] = new String("Sector - 125");
            responsiblePartyAddress.setCountryCode("IN");
            responsiblePartyAddress.setStreetLines(address);
            responsiblePartyAddress.setCity("Noida");
            responsiblePartyAddress.setStateOrProvinceCode("UP");
            responsibleParty.setAddress(responsiblePartyAddress);
            responsibleParty.setContact(new Contact());
                payor.setResponsibleParty(responsibleParty);
            payment.setPayor(payor);
            return payment;
        }
        
        public static CustomsClearanceDetail addCustomsClearanceDetail(Order t_order){
                CustomsClearanceDetail detail = new CustomsClearanceDetail();
                detail.setClearanceBrokerage(ClearanceBrokerageType.BROKER_INCLUSIVE);
                detail.setCustomsOptions(new CustomsOptionDetail(CustomsOptionType.TRIAL,"Trail Order"));
                Commodity commodities[] = new Commodity[1];
                commodities[0]= new Commodity();
                commodities[0].setNumberOfPieces(new NonNegativeInteger(1+""));
                commodities[0].setDescription("Sample Commodity Data");
                commodities[0].setCountryOfManufacture("India");
                commodities[0].setQuantity(new NonNegativeInteger(1+""));
                commodities[0].setQuantityUnits("EA");
                commodities[0].setWeight(new Weight(WeightUnits.LB,new BigDecimal(t_order.getTotal_weight())));
                commodities[0].setUnitPrice(new Money("INR",new BigDecimal(t_order.getTotal_amount())));
                CommercialInvoice ci= new CommercialInvoice();
                ci.setPurpose(PurposeOfShipmentType.SOLD);
                detail.setCommercialInvoice(ci);
                detail.setCommodities(commodities);
                detail.setCustomsValue(new Money("INR",new BigDecimal(t_order.getTotal_amount())));
                return detail;
        }
        
        private static ShipmentSpecialServicesRequested addShipmentSpecialServicesRequested(Order t_order){
            ShipmentSpecialServicesRequested shipmentSpecialServicesRequested = new ShipmentSpecialServicesRequested();
            ShipmentSpecialServiceType shipmentSpecialServiceType[]=new ShipmentSpecialServiceType[1];
            shipmentSpecialServiceType[0]=ShipmentSpecialServiceType.COD;
            shipmentSpecialServicesRequested.setSpecialServiceTypes(shipmentSpecialServiceType);
            CodDetail codDetail = new CodDetail();
            codDetail.setCollectionType(CodCollectionType.CASH);
            Money codMoney = new Money();
            codMoney.setCurrency("INR");
            codMoney.setAmount(new BigDecimal(t_order.getTotal_amount()));
            codDetail.setCodCollectionAmount(codMoney);
            shipmentSpecialServicesRequested.setCodDetail(codDetail);
            return shipmentSpecialServicesRequested;
        }
        
        private static RequestedPackageLineItem addRequestedPackageLineItem(Order t_order){
                RequestedPackageLineItem requestedPackageLineItem = new RequestedPackageLineItem();
                requestedPackageLineItem.setSequenceNumber(new PositiveInteger("1"));
                requestedPackageLineItem.setGroupPackageCount(new PositiveInteger("1"));
                requestedPackageLineItem.setWeight(addPackageWeight(new Double(t_order.getTotal_weight()), WeightUnits.LB));
                requestedPackageLineItem.setCustomerReferences(new CustomerReference[]{
                                addCustomerReference(CustomerReferenceType.CUSTOMER_REFERENCE.getValue(), t_order.getCustomer_name()),
                                addCustomerReference(CustomerReferenceType.INVOICE_NUMBER.getValue(), t_order.getId()+""),
                                addCustomerReference(CustomerReferenceType.P_O_NUMBER.getValue(), t_order.getId()+""),
                });
                return requestedPackageLineItem;
        }
        
        private static CustomerReference addCustomerReference(String customerReferenceType, String customerReferenceValue){
                CustomerReference customerReference = new CustomerReference();
                customerReference.setCustomerReferenceType(CustomerReferenceType.fromString(customerReferenceType));
                customerReference.setValue(customerReferenceValue);
                return customerReference;
        }
        
        private static LabelSpecification addLabelSpecification(){
            LabelSpecification labelSpecification = new LabelSpecification(); // Label specification        
                labelSpecification.setImageType(ShippingDocumentImageType.PDF);// Image types PDF, PNG, DPL, ...        
            labelSpecification.setLabelFormatType(LabelFormatType.COMMON2D); //LABEL_DATA_ONLY, COMMON2D
            //labelSpecification.setLabelStockType(LabelStockType.value2); // STOCK_4X6.75_LEADING_DOC_TAB          
            //labelSpecification.setLabelPrintingOrientation(LabelPrintingOrientationType.TOP_EDGE_OF_TEXT_FIRST);
            return labelSpecification;
        }
        
        
        private static String printMasterTrackingNumber(CompletedShipmentDetail csd){
                String trackingNumber="";
                if(null != csd.getMasterTrackingId()){
                        trackingNumber = csd.getMasterTrackingId().getTrackingNumber();
                }
                return trackingNumber;
        }
        
        //Saving and displaying shipping documents (labels)
        private static void saveLabelToFile(ShippingDocument shippingDocument, String trackingNumber) throws Exception {
                ShippingDocumentPart[] sdparts = shippingDocument.getParts();
                for (int a=0; a < sdparts.length; a++) {
                        ShippingDocumentPart sdpart = sdparts[a];
                        String labelLocation = System.getProperty("file.label.location");
                        if (labelLocation == null) {
                                labelLocation = "/tmp/";
                        }
                        String shippingDocumentType = shippingDocument.getType().getValue();
                        String labelFileName =  new String(labelLocation + shippingDocumentType + "." + trackingNumber + "_" + a + ".pdf");                                     
                        File labelFile = new File(labelFileName);
                        FileOutputStream fos = new FileOutputStream( labelFile );
                        fos.write(sdpart.getImage());
                        fos.close();
                        System.out.println("\nlabel file name " + labelFile.getAbsolutePath());
                }
        }

        private static void saveShipmentDocumentsToFile(ShippingDocument[] shippingDocument, String trackingNumber) throws Exception{
                if(shippingDocument!= null){
                        for(int i=0; i < shippingDocument.length; i++){
                                ShippingDocumentPart[] sdparts = shippingDocument[i].getParts();
                                for (int a=0; a < sdparts.length; a++) {
                                        ShippingDocumentPart sdpart = sdparts[a];
                                        String labelLocation = System.getProperty("file.label.location");
                                        if (labelLocation == null) {
                                                labelLocation = "/tmp/";
                                        }
                                        String labelName = shippingDocument[i].getType().getValue();
                                        String shippingDocumentLabelFileName =  new String(labelLocation + labelName + "." + trackingNumber + "_" + a + ".pdf");                                        
                                        File shippingDocumentLabelFile = new File(shippingDocumentLabelFileName);
                                        FileOutputStream fos = new FileOutputStream( shippingDocumentLabelFile );
                                        fos.write(sdpart.getImage());
                                        fos.close();
                                        System.out.println("\nAssociated shipment label file name " + shippingDocumentLabelFile.getAbsolutePath());
                                }
                        }
                }
        }
        
        private static void getAssociatedShipmentLabels(AssociatedShipmentDetail[] associatedShipmentDetail) throws Exception{
                if(associatedShipmentDetail!=null){
                        for (int j=0; j < associatedShipmentDetail.length; j++){
                                if(associatedShipmentDetail[j].getLabel()!=null && associatedShipmentDetail[j].getType()!=null){
                                        String trackingNumber = associatedShipmentDetail[j].getTrackingId().getTrackingNumber();
                                        String associatedShipmentType = associatedShipmentDetail[j].getType().getValue();
                                        ShippingDocument associatedShipmentLabel = associatedShipmentDetail[j].getLabel();
                                        saveAssociatedShipmentLabelToFile(associatedShipmentLabel, trackingNumber, associatedShipmentType);
                                }
                        }
                }
        }
        
        private static void saveAssociatedShipmentLabelToFile(ShippingDocument shippingDocument, String trackingNumber, String labelName) throws Exception {
                ShippingDocumentPart[] sdparts = shippingDocument.getParts();
                for (int a=0; a < sdparts.length; a++) {
                        ShippingDocumentPart sdpart = sdparts[a];
                        String labelLocation = System.getProperty("file.label.location");
                        if (labelLocation == null) {
                                labelLocation = "/tmp/";
                        }
                        String associatedShipmentLabelFileName =  new String(labelLocation + labelName + "." + trackingNumber + "_" + a + ".pdf");                                      
                        File associatedShipmentLabelFile = new File(associatedShipmentLabelFileName);
                        FileOutputStream fos = new FileOutputStream( associatedShipmentLabelFile );
                        fos.write(sdpart.getImage());
                        fos.close();
                        System.out.println("\nAssociated shipment label file name " + associatedShipmentLabelFile.getAbsolutePath());
                }
        }
        
        private static void updateEndPoint(ShipServiceLocator serviceLocator, String endPoint) {
                if (endPoint != null) {
                        serviceLocator.setShipServicePortEndpointAddress(endPoint);
                }
        }       
        
}