Java tutorial
package com.zuora.api; import java.io.*; import java.math.BigDecimal; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.util.*; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.SimpleDateFormat; import com.zuora.api.axis2.ZuoraServiceStub.ID; import com.zuora.api.axis2.ZuoraServiceStub.Usage; import com.zuora.csv.CSVReader; import com.zuora.entities.*; import com.zuora.utilities.Logger; import com.zuora.utilities.Utility; import org.apache.commons.codec.binary.Base64; import org.apache.commons.mail.*; public class UsageAdjInvoiceRegenerator { public static String PROPERTY_FILE_NAME = "./config.properties"; public static int MAX_PARAMETER_NUMBER_PER_QUERY = 25; //private int MAX_ITEMS_PER_CALL; // Store related data for each thread. //private ThreadData[] threadDataArray; // The index of last ThreadData been selected to process private int lastThreadIndex = 0; private static ApiClient zApiClient = null; //private PRPCEntity[] ePRPCCollected = null; private static List<PRPCEntity> ePRPCItemsValid = new ArrayList<PRPCEntity>(); //private List<InvoiceItemEntity> eInvoiceItemsFull = null; private static List<InvoiceItemEntity> eUsageItemsValid = new ArrayList<InvoiceItemEntity>(); private static List<InvoiceItemEntity> errorList = new ArrayList<InvoiceItemEntity>(); private static List<ID> deleteList = new ArrayList<ID>(); private static List<InvoiceItemEntity> newUsageCollection = new ArrayList<InvoiceItemEntity>(); protected UsageAdjInvoiceRegenerator() throws Exception { //MAX_ITEMS_PER_CALL = AppParamManager.MAX_ZOBJECTS_PER_BATCH; // Initialize the API Client. zApiClient = new ApiClient(AppParamManager.API_URL, AppParamManager.USER_NAME, AppParamManager.USER_PASSWORD, AppParamManager.USER_SESSION); zApiClient.login(); //Logger.print("logged in"); /* threadDataArray = new ThreadData[AppParamManager.MAX_WORKING_THREADS]; for (int i = 0; i < AppParamManager.MAX_WORKING_THREADS; i++) { threadDataArray[i] = new ThreadData(i); } */ //int indexOfThreadDataArray = 0; int itemsCollectionIndex = 0; String savedRPId = ""; String savedAccountId = ""; String savedInvoiceId = ""; String savedPRPCId = ""; Calendar savedServiceEndDt = null; Calendar savedInvoiceDt = null; Calendar savedTargetDt = null; String savedBaseUOM = null; String savedOverUOM = null; String basePRPCId = null; List<Usage> deleteUOMs = null; boolean skipDelete = false; /* String InvoiceNumberDisplay = ""; BufferedWriter writer = new BufferedWriter( new FileWriter("C:\\Temp\\output"+output+".txt")); */ //Logger.print("thread initiated, max objects: "+AppParamManager.MAX_ZOBJECTS_PER_BATCH+" Total number of Line Items: "+eInvoiceItemAll.size()); //String rpcQuery1 = "SELECT Price, base_quantity__c from RatePlanCharge where ProductRatePlanChargeId = '"; String rpcQuery1 = "SELECT Price from RatePlanCharge where ProductRatePlanChargeId = '"; String rpcQuery2 = "' and RatePlanId = '"; //String rpcQuery3 = "' and Base_Quantity__c <> '0'"; String rpcQuery3 = "'"; String finalquery = ""; BigDecimal result = BigDecimal.ZERO; BigDecimal amountTotal = BigDecimal.ZERO; BigDecimal baseAmount = BigDecimal.ZERO; BigDecimal savedQuantity = BigDecimal.ZERO; InvoiceItemEntity baseEntity = null; InvoiceItemEntity overageEntity = null; //Logger.print("Before loop."); for (InvoiceItemEntity eInvoiceItem : eUsageItemsValid) { Logger.print("in loop0" + eInvoiceItem.getRPId()); if (!eInvoiceItem.getRPId().equals(savedRPId)) { if (itemsCollectionIndex != 0) { Logger.print("in if 1"); if (!skipDelete) { /* //add base usage baseEntity = new InvoiceItemEntity(); baseEntity.setAccountId(savedAccountId); finalquery = rpcQuery1 + basePRPCId + rpcQuery2 + savedRPId + rpcQuery3; results = zApiClient.getBaseQuantity(finalquery); baseEntity.setQuantity(results[0]); baseAmount = results[1]; baseEntity.setUOM(savedBaseUOM); baseEntity.setServiceEnddt(savedServiceEndDt); //Logger.print("setting invoice id base: "+savedInvoiceId); baseEntity.setInvoiceId(savedInvoiceId); baseEntity.setTargetDate(savedTargetDt); baseEntity.setInvoicedate(savedInvoiceDt); newUsageCollection.add(baseEntity); */ //add overage usage BigDecimal overageQnty = amountTotal.subtract(baseAmount); if (overageQnty.compareTo(BigDecimal.ZERO) > 0) { overageEntity = new InvoiceItemEntity(); overageEntity.setAccountId(savedAccountId); Logger.print("setting invoice id over: " + savedInvoiceId); overageEntity.setInvoiceId(savedInvoiceId); overageEntity.setQuantity(overageQnty); overageEntity.setUOM(savedOverUOM); overageEntity.setServiceEnddt(savedServiceEndDt); overageEntity.setTargetDate(savedTargetDt); overageEntity.setInvoicedate(savedInvoiceDt); Logger.print("added to collection, overage: " + overageEntity.getQuantity()); newUsageCollection.add(overageEntity); } } skipDelete = false; amountTotal = BigDecimal.ZERO; baseAmount = BigDecimal.ZERO; } savedRPId = eInvoiceItem.getRPId(); savedPRPCId = eInvoiceItem.getPRPCId(); savedAccountId = eInvoiceItem.getAccountId(); if (!eInvoiceItem.getInvoiceId().equals(savedInvoiceId)) { Logger.print("getting usage for invoice: " + eInvoiceItem.getInvoiceId()); deleteUOMs = zApiClient.getUsageForDelete( "select id, uom from usage where invoiceid = '" + eInvoiceItem.getInvoiceId() + "'"); savedInvoiceId = eInvoiceItem.getInvoiceId(); } savedInvoiceDt = eInvoiceItem.getInvoicedate(); savedTargetDt = eInvoiceItem.getTargetDate(); savedServiceEndDt = eInvoiceItem.getServiceEnddt(); if (eInvoiceItem.getFeeFlag().equals("B")) { savedBaseUOM = eInvoiceItem.getUOM(); basePRPCId = eInvoiceItem.getPRPCId(); } if (eInvoiceItem.getFeeFlag().equals("O")) { savedOverUOM = eInvoiceItem.getUOM(); } savedBaseUOM = null; savedOverUOM = null; savedQuantity = BigDecimal.ZERO; } Logger.print("In loop1"); savedRPId = eInvoiceItem.getRPId(); //Logger.print("In loop2"); savedPRPCId = eInvoiceItem.getPRPCId(); //Logger.print("In loop3"); savedAccountId = eInvoiceItem.getAccountId(); //Logger.print("In loop4"); savedInvoiceDt = eInvoiceItem.getInvoicedate(); //Logger.print("In loop6"); savedTargetDt = eInvoiceItem.getTargetDate(); //Logger.print("In loop7"); savedServiceEndDt = eInvoiceItem.getServiceEnddt(); //Logger.print("In loop8"); if (eInvoiceItem.getFeeFlag().equals("B")) { Logger.print("setting base UOM"); basePRPCId = eInvoiceItem.getPRPCId(); //add base usage finalquery = rpcQuery1 + basePRPCId + rpcQuery2 + savedRPId + rpcQuery3; result = zApiClient.getBaseQuantity(finalquery); Logger.print("setting base UOM"); Logger.print( "curr line quantity: " + eInvoiceItem.getQuantity() + " base quantity: " + savedQuantity); if (result.compareTo(BigDecimal.ZERO) > 0 && eInvoiceItem.getQuantity().compareTo(savedQuantity) < 0) { //Logger.print("setting invoice id base1: "); savedBaseUOM = eInvoiceItem.getUOM(); //Logger.print("setting invoice id base2: "); baseEntity = new InvoiceItemEntity(); baseEntity.setAccountId(savedAccountId); //Logger.print("setting invoice id base3: "); //result baseEntity.setQuantity(savedQuantity); baseAmount = savedQuantity.multiply(result); baseEntity.setUOM(savedBaseUOM); baseEntity.setServiceEnddt(savedServiceEndDt); Logger.print("setting invoice id base: " + savedInvoiceId); baseEntity.setInvoiceId(savedInvoiceId); baseEntity.setTargetDate(savedTargetDt); baseEntity.setInvoicedate(savedInvoiceDt); newUsageCollection.add(baseEntity); } } if (eInvoiceItem.getLicenseFlag().equals("True")) { savedQuantity = eInvoiceItem.getQuantity(); Logger.print("within license flag, quantity set to :" + savedQuantity); } if (eInvoiceItem.getFeeFlag().equals("O")) { Logger.print("setting over UOM"); savedOverUOM = eInvoiceItem.getUOM(); } if (eInvoiceItem.getFeeFlag().equals("") && eInvoiceItem.getLicenseFlag().equals("")) { Logger.print("setting usage " + savedBaseUOM); if (savedBaseUOM == null) { skipDelete = true; } else { Logger.print("setting usage1"); amountTotal = amountTotal.add(eInvoiceItem.getAmount()); Logger.print("setting usage2: " + eInvoiceItem.getInvoiceId() + " saved: " + savedInvoiceId); if (!eInvoiceItem.getInvoiceId().equals(savedInvoiceId)) { Logger.print("setting usage3"); deleteUOMs = zApiClient.getUsageForDelete("select id, uom from usage where invoiceid = '" + eInvoiceItem.getInvoiceId() + "'"); Logger.print("deleted list: " + deleteUOMs.size()); savedInvoiceId = eInvoiceItem.getInvoiceId(); } Logger.print("before usage loop" + deleteUOMs.size()); if (deleteUOMs.size() >= 1 && deleteUOMs.get(0).getUOM() != null) { for (Usage usage : deleteUOMs) { Logger.print("in loop, usage UOM: " + usage.getUOM() + " invoice UOM: " + eInvoiceItem.getUOM()); if (usage.getUOM().equals(eInvoiceItem.getUOM())) { deleteList.add(usage.getId()); Logger.print("added to delete list: " + usage.getUOM()); break; } } } } } itemsCollectionIndex++; Logger.print("done setting usage"); } if (!skipDelete) { /* //add base usage baseEntity = new InvoiceItemEntity(); baseEntity.setAccountId(savedAccountId); Logger.print("after loop1"); finalquery = rpcQuery1 + basePRPCId + rpcQuery2 + savedRPId + rpcQuery3; results = zApiClient.getBaseQuantity(finalquery); baseEntity.setQuantity(results[0]); baseAmount = results[1]; Logger.print("after loop2"); baseEntity.setUOM(savedBaseUOM); baseEntity.setServiceEnddt(savedServiceEndDt); Logger.print("setting invoice id base: "+savedInvoiceId); baseEntity.setInvoiceId(savedInvoiceId); baseEntity.setTargetDate(savedTargetDt); baseEntity.setInvoicedate(savedInvoiceDt); newUsageCollection.add(baseEntity); Logger.print("after loop3"); //add overage usage */ BigDecimal overageQnty = amountTotal.subtract(baseAmount); if (overageQnty.compareTo(BigDecimal.ZERO) > 0) { overageEntity = new InvoiceItemEntity(); overageEntity.setAccountId(savedAccountId); Logger.print("after loop3.1"); //Logger.print("setting invoice id over: "+savedInvoiceId); overageEntity.setInvoiceId(savedInvoiceId); //Logger.print("after loop3.2"); //Logger.print("after loop3.3"); overageEntity.setQuantity(overageQnty); //Logger.print("after loop4"); overageEntity.setUOM(savedOverUOM); //Logger.print("after loop4.1"); overageEntity.setServiceEnddt(savedServiceEndDt); //Logger.print("after loop4.2"); overageEntity.setTargetDate(savedTargetDt); //Logger.print("after loop4.3"); overageEntity.setInvoicedate(savedInvoiceDt); //Logger.print("after loop4.4"); Logger.print("added to collection, overage: " + overageEntity.getQuantity()); newUsageCollection.add(overageEntity); //Logger.print("after loop5"); } skipDelete = false; } amountTotal = BigDecimal.ZERO; baseAmount = BigDecimal.ZERO; //writer.close(); } public static void main(String[] args) { String exportIdPRPC, exportIdII, exportFileIdII, exportFileIdPRPC, queryII, queryPRPC; boolean hasArgs = false; if (args != null && args.length >= 1) { UsageAdjInvoiceRegenerator.PROPERTY_FILE_NAME = args[0]; hasArgs = true; } AppParamManager.initParameters(hasArgs); if (!AppParamManager.TASK_ID.equals("")) { try { zApiClient = new ApiClient(AppParamManager.API_URL, AppParamManager.USER_NAME, AppParamManager.USER_PASSWORD, AppParamManager.USER_SESSION); zApiClient.login(); } catch (Exception ex) { Logger.print(ex); Logger.print("RefreshSession - There's exception in the API call."); } queryPRPC = AppParamManager.PRPCexportQuery; queryII = AppParamManager.IIexportQuery; exportIdPRPC = zApiClient.createExport(queryPRPC); exportIdII = zApiClient.createExport(queryII); // ERROR createExport fails if (exportIdII == null || exportIdII.equals("")) { Logger.print("Error. Failed to create Invoice Item Export"); //return false; } // ERROR createExport fails if (exportIdPRPC == null || exportIdPRPC.equals("")) { Logger.print("Error. Failed to create PRPC export"); //return false; } exportFileIdII = zApiClient.getExportFileId(exportIdII); if (exportFileIdII == null) { Logger.print("Error. Failed to get Invoice Item Export file Id"); //log.closeLogFile(); //return false; } exportFileIdPRPC = zApiClient.getExportFileId(exportIdPRPC); if (exportFileIdPRPC == null) { Logger.print("Error. Failed to get PRPC Export file Id"); //log.closeLogFile(); //return false; } // get the export file from zuora //zApiClient.getFile(exportFileIdII, exportFileIdTI); /* Logger.print("II export ID: "+exportFileIdII); Logger.print("TI export ID: "+exportFileIdTI); */ Logger.print("Opening Export file"); //Base64 bs64 = new BASE64Encoder(); /* String login = AppParamManager.USER_NAME+":"+AppParamManager.USER_PASSWORD; String authorization ="Basic "+ Base64.encodeBase64String(login.getBytes()); String zendpoint = ""; */ String authorization = ""; //Base64 bs64 = new BASE64Encoder(); if (AppParamManager.USER_SESSION.isEmpty()) { String login = AppParamManager.USER_NAME + ":" + AppParamManager.USER_PASSWORD; authorization = "Basic " + Base64.encodeBase64String(login.getBytes()); } else { authorization = "ZSession " + AppParamManager.USER_SESSION; } String zendpoint = ""; try { /* if( AppParamManager.API_URL.contains("api") ){ //look in api sandbox zendpoint = "https://apisandbox.zuora.com/apps/api/file/"; } else { //look in production zendpoint = "https://www.zuora.com/apps/api/file/"; } */ int index = AppParamManager.API_URL.indexOf("apps"); index = index + 5; zendpoint = AppParamManager.API_URL.substring(0, index) + "api/file/"; Logger.print(zendpoint); //zendpoint = AppParamManager.FILE_URL; //Start reading Invoice Items String zendpointII = zendpoint + exportFileIdII + "/"; URL url = new URL(zendpointII); URLConnection uc = url.openConnection(); //Logger.print("Opening invoice item file: "+exportFileIdII+" authorization: "+authorization); uc.setRequestProperty("Authorization", authorization); InputStream content = (InputStream) uc.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(content)); CSVReader cvsReader = new CSVReader(in); List<String[]> batchOfRawDataList = null; while ((batchOfRawDataList = cvsReader.parseEntity()) != null) { UsageAdjInvoiceRegenerator.readInvoices(batchOfRawDataList, cvsReader.getBatchStartLineNumber(), "InvoiceItem"); } in.close(); String zenpointPRPC = zendpoint + exportFileIdPRPC + "/"; url = new URL(zenpointPRPC); uc = url.openConnection(); uc.setRequestProperty("Authorization", authorization); content = (InputStream) uc.getInputStream(); in = new BufferedReader(new InputStreamReader(content)); cvsReader = new CSVReader(in); while ((batchOfRawDataList = cvsReader.parseEntity()) != null) { UsageAdjInvoiceRegenerator.readInvoices(batchOfRawDataList, cvsReader.getBatchStartLineNumber(), "PRPCItem"); } in.close(); Logger.print("start processing values"); UsageAdjInvoiceRegenerator chargeAdjustment = new UsageAdjInvoiceRegenerator(); int[] results; int totalErrors = 0; String emailmsg = ""; Logger.print("----------------------------------------"); Logger.print("start creating usages"); results = zApiClient.createUsageItems(newUsageCollection); if (results[1] != 0) { emailmsg = (results[0] - results[1]) + "/" + results[0] + " usage creation "; } totalErrors = totalErrors + results[1]; Logger.print("start cancelling invoices"); results = zApiClient.alterInvoices(newUsageCollection, "cancel"); if (results[1] != 0) { emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice cancellation "; } totalErrors = totalErrors + results[1]; Logger.print("start deleting usages"); results = zApiClient.deleteUsageItems(deleteList); if (results[1] != 0) { emailmsg = (results[0] - results[1]) + "/" + results[0] + " usage deletion "; } totalErrors = totalErrors + results[1]; Logger.print("start regenerating invoices"); results = zApiClient.alterInvoices(newUsageCollection, "generate"); if (results[1] != 0) { emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice generation "; } totalErrors = totalErrors + results[1]; Logger.print("start deleting old invoices"); results = zApiClient.alterInvoices(newUsageCollection, "delete"); if (results[1] != 0) { emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice deletion "; } totalErrors = totalErrors + results[1]; // Create the attachment EmailAttachment attachment = new EmailAttachment(); if (totalErrors > 0) { String logFileName = AppParamManager.OUTPUT_FOLDER_LOCATION + File.separator + "runtime_log_" + AppParamManager.OUTPUT_FILE_POSTFIX + ".txt"; attachment.setPath(logFileName); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("System Log"); attachment.setName("System Log"); } MultiPartEmail email = new MultiPartEmail(); email.setSmtpPort(587); email.setAuthenticator( new DefaultAuthenticator(AppParamManager.EMAIL_ADDRESS, AppParamManager.EMAIL_PASSWORD)); email.setDebug(false); email.setHostName("smtp.gmail.com"); email.setFrom("zuora@gmail.com"); if (totalErrors > 0) { email.setSubject("Base Calc Processor Finished with Errors"); email.setMsg("The base calc processing has finished " + emailmsg + "records successfully."); } else { email.setSubject("Base Calc Processor Finished Successfully"); emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice "; email.setMsg("The base calc processing has finished " + emailmsg + "records successfully."); } email.setTLS(true); email.addTo(AppParamManager.RECIPIENT_ADDRESS); if (totalErrors > 0) { email.attach(attachment); } email.send(); System.out.println("Mail sent!"); if (hasArgs) { Connection conn = AppParamManager.getConnection(); Statement stmt = conn.createStatement(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); java.util.Date date = new Date(); stmt.executeUpdate("UPDATE TASK SET STATUS = 'completed', END_TIME = '" + dateFormat.format(date) + "' WHERE ID = " + AppParamManager.TASK_ID); Utility.saveLogToDB(conn); conn.close(); } } catch (Exception e) { Logger.print("Failure, gettingFile."); Logger.print("Error getting the export file: " + e.getMessage()); //System.out.println("Error getting the export file: "+e.getMessage()); try { Connection conn = AppParamManager.getConnection(); Statement stmt = conn.createStatement(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); java.util.Date date = new Date(); stmt.executeUpdate("UPDATE TASK SET STATUS = 'failed', END_TIME = '" + dateFormat.format(date) + "' WHERE ID = " + AppParamManager.TASK_ID); Utility.saveLogToDB(conn); conn.close(); } catch (Exception e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } } else { Logger.print("No tasks in wait status"); } } public PRPCEntity find(String PRPId, String feeFlag, List<PRPCEntity> PRPCAll) { //PRPCEntity entity = null; //Logger.print("in loop 2.1: "+feeFlag+ ", "+PRPId); for (PRPCEntity entity : PRPCAll) { //Logger.print("in loop 2.2 entity: "+entity.getFeeFlag()); //Logger.print("in loop 2.3 entity: "+entity.getPRPId()); if (entity.getPRPId().equals(PRPId) && entity.getFeeFlag().equals(feeFlag)) { Logger.print("entry found, prpid: " + PRPId + ", feeflag: " + feeFlag); return entity; } } return null; } public static void readInvoices(List<String[]> rawDataList, int startLineNumber, String Type) throws Exception { int lineNumber = startLineNumber; InvoiceItemEntity eInvoice = null; PRPCEntity ePRPC = null; Logger.print("reading invoices: " + Type); //Invoice Item headers int PRPCIdIndex = InvoiceItemHeader.getColumnIndex("prpcid"); int RPIdIndex = InvoiceItemHeader.getColumnIndex("rpid"); int RPCIdIndex = InvoiceItemHeader.getColumnIndex("rpcid"); int amountIndex = InvoiceItemHeader.getColumnIndex("amount"); int serviceEndDtIndex = InvoiceItemHeader.getColumnIndex("serviceenddate"); int quantityIndex = InvoiceItemHeader.getColumnIndex("quantity"); int uomIndex = InvoiceItemHeader.getColumnIndex("uom"); int accountidIndex = InvoiceItemHeader.getColumnIndex("accountid"); int prpIdIndex = InvoiceItemHeader.getColumnIndex("prpid"); int invoiceidIndex = InvoiceItemHeader.getColumnIndex("invoiceid"); int invoicenumberIndex = InvoiceItemHeader.getColumnIndex("targetdate"); int invoicedateIndex = InvoiceItemHeader.getColumnIndex("invoicedate"); int invoiceFeeFlagIndex = InvoiceItemHeader.getColumnIndex("feeflag"); int licenseFlagIndex = InvoiceItemHeader.getColumnIndex("licenseflag"); //PRPC headers int PPRPCIdIndex = PRPCHeader.getColumnIndex("prpcid"); int PPRPIdIndex = PRPCHeader.getColumnIndex("prpid"); int puomIndex = PRPCHeader.getColumnIndex("uom"); int feeFlagIndex = PRPCHeader.getColumnIndex("feeflag"); if (Type.equals("InvoiceItem")) { for (String[] rawData : rawDataList) { eInvoice = new InvoiceItemEntity(rawData, lineNumber++, PRPCIdIndex, RPIdIndex, RPCIdIndex, amountIndex, serviceEndDtIndex, quantityIndex, uomIndex, accountidIndex, prpIdIndex, invoiceidIndex, invoicenumberIndex, invoicedateIndex, invoiceFeeFlagIndex, licenseFlagIndex); if (eInvoice.isDataValidationPassed()) { eUsageItemsValid.add(eInvoice); } } } else { for (String[] rawData : rawDataList) { ePRPC = new PRPCEntity(rawData, lineNumber++, PPRPCIdIndex, PPRPIdIndex, puomIndex, feeFlagIndex); if (ePRPC.isDataValidationPassed()) { ePRPCItemsValid.add(ePRPC); } } } } }