Rev 19508 | 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{/*fedex_account_number_mumbai=512033946fedex_meter_number=105452205fedex_authenication_key=ggqFObyBaF3ECQbQfedex_authenication_password=LIf9WMXsKqJV30AsGbK2Fy4TQfedex_endpoint_address_track=https://ws.fedex.com:443/web-services/trackfedex_endpoint_address_ship=https://ws.fedex.com:443/web-services/ship*//*public static void main(String[] args) throws Exception {ClientDetail clientDetail = new ClientDetail();clientDetail.setAccountNumber("512033946");clientDetail.setMeterNumber("106151740");WebAuthenticationCredential wac = new WebAuthenticationCredential();wac.setKey("DERXFRxP8qOqw0h8");//ta0q2IFeWpPcnuEAr8pdav3PDwac.setPassword("ta0q2IFeWpPcnuEAr8pdav3PD");String endPointAddress = "https://ws.fedex.com:443/web-services/ship";Order order = new TransactionClient().getClient().getOrder(554218L);ProcessShipmentReply reply = getShipmentCreationReply(order,clientDetail, new WebAuthenticationDetail(wac), endPointAddress);System.out.println(reply);}*/public static ProcessShipmentReply getShipmentCreationReply(List<Order> orders ,ClientDetail clientDetail, WebAuthenticationDetail wac, String endpointAddress, long providerId){ProcessShipmentRequest request = new ProcessShipmentRequest(); // Build a request objectSystem.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 responserequest.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);if(providerId==7){requestedShipment.setServiceType(ServiceType.STANDARD_OVERNIGHT);}else{requestedShipment.setServiceType(ServiceType.FEDEX_EXPRESS_SAVER);}requestedShipment.setPackagingType(PackagingType.YOUR_PACKAGING);requestedShipment.setShipper(addShipper());requestedShipment.setRecipient(addRecipient(orders.get(0)));requestedShipment.setShippingChargesPayment(addShippingChargesPayment(clientDetail.getAccountNumber()));if(orders.get(0).isCod()){requestedShipment.setSpecialServicesRequested(addShipmentSpecialServicesRequested(orders));}else{requestedShipment.setSpecialServicesRequested(null);}requestedShipment.setLabelSpecification(addLabelSpecification());requestedShipment.setPackageCount(new NonNegativeInteger("1"));requestedShipment.setCustomsClearanceDetail(addCustomsClearanceDetail(orders));RateRequestType rateRequestType[] = new RateRequestType[1];rateRequestType[0] = RateRequestType.ACCOUNT;requestedShipment.setRateRequestTypes(new RateRequestType[]{rateRequestType[0]});requestedShipment.setRequestedPackageLineItems(new RequestedPackageLineItem[] {addRequestedPackageLineItem(orders)});request.setRequestedShipment(requestedShipment);ProcessShipmentReply reply = new ProcessShipmentReply();try {// Initialize the serviceShipServiceLocator 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 objectprintNotifications(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 packageString trackingNumber = cpd[i].getTrackingIds()[0].getTrackingNumber();//printTrackingNumbers(cpd[i]);//printPackageRating(cpd[i].getPackageRating());// Write label buffer to fileShippingDocument sd = cpd[i].getLabel();saveLabelToFile(sd, trackingNumber);//printPackageOperationalDetails(cpd[i].getOperationalDetail());//System.out.println();}}}private static Party addShipper(){Party shipperParty = new Party(); // Sender informationContact shipperContact = new Contact();shipperContact.setPersonName("Hotspot Sales & Solutions Pvt. Ltd.");shipperContact.setCompanyName("Hotspot Sales & Solutions Pvt. Ltd.");shipperContact.setPhoneNumber("09811247808");Address shipperAddress = new Address();String address[] = new String[2];address[0] = new String("C/O,PIBCO LIMITED,Basement,Punjsons 2");address[1] = new String("Kalkaji Industrial Area");shipperAddress.setStreetLines(address);shipperAddress.setCity("New Delhi");shipperAddress.setStateOrProvinceCode("DL");shipperAddress.setPostalCode("110019");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(List<Order> orders){double totalAmount = 0;double totalWeight = 0;for(Order t_order: orders){totalAmount = totalAmount + t_order.getTotal_amount();totalWeight = totalWeight + t_order.getTotal_weight();}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("IN");commodities[0].setQuantity(new NonNegativeInteger(1+""));commodities[0].setQuantityUnits("EA");commodities[0].setWeight(new Weight(WeightUnits.KG,new BigDecimal(totalWeight)));commodities[0].setUnitPrice(new Money("INR",new BigDecimal(totalAmount)));CommercialInvoice ci= new CommercialInvoice();ci.setPurpose(PurposeOfShipmentType.SOLD);detail.setCommercialInvoice(ci);detail.setCommodities(commodities);detail.setFreightOnValue(FreightOnValueType.OWN_RISK);detail.setCustomsValue(new Money("INR",new BigDecimal(totalAmount)));return detail;}private static ShipmentSpecialServicesRequested addShipmentSpecialServicesRequested(List<Order> orders){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");double totalAmount = 0;for(Order t_order : orders){totalAmount = totalAmount + t_order.getTotal_amount();}codMoney.setAmount(new BigDecimal(totalAmount));codDetail.setCodCollectionAmount(codMoney);shipmentSpecialServicesRequested.setCodDetail(codDetail);return shipmentSpecialServicesRequested;}private static RequestedPackageLineItem addRequestedPackageLineItem(List<Order> orders){double totalWeight = 0;for(Order t_order: orders){totalWeight = totalWeight + t_order.getTotal_weight();}RequestedPackageLineItem requestedPackageLineItem = new RequestedPackageLineItem();requestedPackageLineItem.setSequenceNumber(new PositiveInteger("1"));requestedPackageLineItem.setWeight(addPackageWeight(new Double(totalWeight), WeightUnits.KG));requestedPackageLineItem.setCustomerReferences(new CustomerReference[]{addCustomerReference(CustomerReferenceType.CUSTOMER_REFERENCE.getValue(), orders.get(0).getCustomer_name()),addCustomerReference(CustomerReferenceType.INVOICE_NUMBER.getValue(), orders.get(0).getLogisticsTransactionId()+""),addCustomerReference(CustomerReferenceType.P_O_NUMBER.getValue(), orders.get(0).getLogisticsTransactionId()+""),});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 specificationlabelSpecification.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);}}}