List of usage examples for java.sql Date after
public boolean after(Date when)
From source file:com.l2jfree.loginserver.tools.L2AccountManager.java
/** * Launches the interactive account manager. * /*from w w w. ja v a 2 s . co m*/ * @param args ignored */ public static void main(String[] args) { // LOW rework this crap Util.printSection("Account Management"); _log.info("Please choose:"); //_log.info("list - list registered accounts"); _log.info("reg - register a new account"); _log.info("rem - remove a registered account"); _log.info("prom - promote a registered account"); _log.info("dem - demote a registered account"); _log.info("ban - ban a registered account"); _log.info("unban - unban a registered account"); _log.info("quit - exit this application"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); L2AccountManager acm = new L2AccountManager(); String line; try { while ((line = br.readLine()) != null) { line = line.trim(); Connection con = null; switch (acm.getState()) { case USER_NAME: line = line.toLowerCase(); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?"); ps.setString(1, line); ResultSet rs = ps.executeQuery(); if (!rs.next()) { acm.setUser(line); _log.info("Desired password:"); acm.setState(ManagerState.PASSWORD); } else { _log.info("User name already in use."); acm.setState(ManagerState.INITIAL_CHOICE); } rs.close(); ps.close(); } catch (SQLException e) { _log.error("Could not access database!", e); acm.setState(ManagerState.INITIAL_CHOICE); } finally { L2Database.close(con); } break; case PASSWORD: try { MessageDigest sha = MessageDigest.getInstance("SHA"); byte[] pass = sha.digest(line.getBytes("US-ASCII")); acm.setPass(HexUtil.bytesToHexString(pass)); } catch (NoSuchAlgorithmException e) { _log.fatal("SHA1 is not available!", e); Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE); } catch (UnsupportedEncodingException e) { _log.fatal("ASCII is not available!", e); Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE); } _log.info("Super user: [y/n]"); acm.setState(ManagerState.SUPERUSER); break; case SUPERUSER: try { if (line.length() != 1) throw new IllegalArgumentException("One char required."); else if (line.charAt(0) == 'y') acm.setSuper(true); else if (line.charAt(0) == 'n') acm.setSuper(false); else throw new IllegalArgumentException("Invalid choice."); _log.info("Date of birth: [yyyy-mm-dd]"); acm.setState(ManagerState.DOB); } catch (IllegalArgumentException e) { _log.info("[y/n]?"); } break; case DOB: try { Date d = Date.valueOf(line); if (d.after(new Date(System.currentTimeMillis()))) throw new IllegalArgumentException("Future date specified."); acm.setDob(d); _log.info("Ban reason ID or nothing:"); acm.setState(ManagerState.SUSPENDED); } catch (IllegalArgumentException e) { _log.info("[yyyy-mm-dd] in the past:"); } break; case SUSPENDED: try { if (line.length() > 0) { int id = Integer.parseInt(line); acm.setBan(L2BanReason.getById(id)); } else acm.setBan(null); try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement( "INSERT INTO account (username, password, superuser, birthDate, banReason) VALUES (?, ?, ?, ?, ?)"); ps.setString(1, acm.getUser()); ps.setString(2, acm.getPass()); ps.setBoolean(3, acm.isSuper()); ps.setDate(4, acm.getDob()); L2BanReason lbr = acm.getBan(); if (lbr == null) ps.setNull(5, Types.INTEGER); else ps.setInt(5, lbr.getId()); ps.executeUpdate(); _log.info("Account " + acm.getUser() + " has been registered."); ps.close(); } catch (SQLException e) { _log.error("Could not register an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); } catch (NumberFormatException e) { _log.info("Ban reason ID or nothing:"); } break; case REMOVE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement("DELETE FROM account WHERE username LIKE ?"); ps.setString(1, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been removed."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not remove an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case PROMOTE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?"); ps.setBoolean(1, true); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been promoted."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not promote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case DEMOTE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?"); ps.setBoolean(1, false); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been demoted."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not demote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case UNBAN: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?"); ps.setNull(1, Types.INTEGER); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been unbanned."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not demote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case BAN: line = line.toLowerCase(); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?"); ps.setString(1, line); ResultSet rs = ps.executeQuery(); if (rs.next()) { acm.setUser(line); _log.info("Ban reason ID:"); acm.setState(ManagerState.REASON); } else { _log.info("Account does not exist."); acm.setState(ManagerState.INITIAL_CHOICE); } rs.close(); ps.close(); } catch (SQLException e) { _log.error("Could not access database!", e); acm.setState(ManagerState.INITIAL_CHOICE); } finally { L2Database.close(con); } break; case REASON: try { int ban = Integer.parseInt(line); con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?"); ps.setInt(1, ban); ps.setString(2, acm.getUser()); ps.executeUpdate(); _log.info("Account " + acm.getUser() + " has been banned."); ps.close(); } catch (NumberFormatException e) { _log.info("Ban reason ID:"); } catch (SQLException e) { _log.error("Could not ban an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; default: line = line.toLowerCase(); if (line.equals("reg")) { _log.info("Desired user name:"); acm.setState(ManagerState.USER_NAME); } else if (line.equals("rem")) { _log.info("User name:"); acm.setState(ManagerState.REMOVE); } else if (line.equals("prom")) { _log.info("User name:"); acm.setState(ManagerState.PROMOTE); } else if (line.equals("dem")) { _log.info("User name:"); acm.setState(ManagerState.DEMOTE); } else if (line.equals("unban")) { _log.info("User name:"); acm.setState(ManagerState.UNBAN); } else if (line.equals("ban")) { _log.info("User name:"); acm.setState(ManagerState.BAN); } else if (line.equals("quit")) Shutdown.exit(TerminationStatus.MANUAL_SHUTDOWN); else _log.info("Incorrect command."); break; } } } catch (IOException e) { _log.fatal("Could not process input!", e); } finally { IOUtils.closeQuietly(br); } }
From source file:com.cemeterylistingsweb.services.impl.ViewListingByGraveNumberServiceImpl.java
@Override public List<PublishedDeceasedListing> findListingByGraveNumber(String number, Long SubId) { List<PublishedDeceasedListing> lists = publishRepo.findAll(); Subscriber sub = subRepo.findOne(SubId); List<PublishedDeceasedListing> list = new ArrayList(); for (PublishedDeceasedListing pubListing : lists) { SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); Date parsed = null;/* ww w . j a v a 2 s. c om*/ try { parsed = (Date) format.parse(pubListing.getDateOfDeath()); } catch (ParseException ex) { Logger.getLogger(ViewListingBySubscriberServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } java.sql.Date dod = new java.sql.Date(parsed.getTime()); if (pubListing.getGraveNumber().equals(number) && dod.after(sub.getSubscriptionDate()) && dod.before(sub.getValidUntil())) list.add(pubListing); } return list; }
From source file:com.cemeterylistingsweb.services.impl.ViewListingByCemeteryImpl.java
@Override public List<PublishedDeceasedListing> findListingByCemetery(Long cemId, Long subId) { ////w ww. j a v a2s . co m List<PublishedDeceasedListing> deceasedList = deadRepo.findAll(); List<PublishedDeceasedListing> Listings = new ArrayList(); Subscriber sub = subRepo.findOne(subId); for (PublishedDeceasedListing listing : deceasedList) { SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); Date parsed = null; try { parsed = (Date) format.parse(listing.getDateOfDeath()); } catch (ParseException ex) { Logger.getLogger(ViewListingBySubscriberServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } java.sql.Date dod = new java.sql.Date(parsed.getTime()); if (listing.getCemeteryID().equals(cemId) && dod.after(sub.getSubscriptionDate()) && dod.before(sub.getLastContributionYear())) { //add to list Listings.add(listing); } } return Listings; }
From source file:com.cemeterylistingsweb.services.impl.SearchSurnameImpl.java
@Override public List<PublishedDeceasedListing> getAllSurname(String surname, Long subId) { List<PublishedDeceasedListing> names = new ArrayList(); List<PublishedDeceasedListing> all = repo.findAll(); Subscriber sub = subRepo.findOne(subId); //if(surname.isEmpty() || surname.equals("") ) // return all; for (PublishedDeceasedListing all1 : all) { SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); Date parsed = null;/* w w w . j a v a 2s . co m*/ try { parsed = (Date) format.parse(all1.getDateOfDeath()); } catch (ParseException ex) { Logger.getLogger(ViewListingBySubscriberServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } java.sql.Date dod = new java.sql.Date(parsed.getTime()); if (surname.isEmpty() || surname.equals("") && dod.after(sub.getSubscriptionDate()) && dod.before(sub.getLastContributionYear())) names.add(all1); else if (all1.getSurname().equals(surname) && dod.after(sub.getSubscriptionDate()) && dod.before(sub.getLastContributionYear())) { names.add(all1); } else if (all1.getSurname().startsWith(surname) && dod.after(sub.getSubscriptionDate()) && dod.before(sub.getLastContributionYear())) names.add(all1); else if (all1.getSurname().contains(surname) && dod.after(sub.getSubscriptionDate()) && dod.before(sub.getLastContributionYear())) names.add(all1); } return names; }
From source file:edu.ku.kuali.kra.negotiations.service.NegotiationServiceImpl.java
private boolean isDateBetween(Date checkDate, Date rangeStart, Date rangeEnd) { if (rangeStart == null) { return false; }/*from ww w .j av a 2 s.c o m*/ if (checkDate == null) { checkDate = new Date(Calendar.getInstance().getTimeInMillis()); } if (rangeEnd == null) { rangeEnd = new Date(Calendar.getInstance().getTimeInMillis()); } boolean startOk = rangeStart.equals(checkDate) || rangeStart.before(checkDate); boolean endOk = rangeEnd.equals(checkDate) || rangeEnd.after(checkDate); return startOk && endOk; }
From source file:edu.cornell.kfs.fp.businessobject.PaymentMethod.java
/** * Returns the PaymentMethodChart record applicable for the given chart and transaction date. * //from w ww. ja v a 2s. c o m * @param chartOfAccountsCode * @param transDate The date of the transaction. Used for comparing to the effective date on the records. If null, the current date will be pulled from the DateTimeService. * @return Applicable PaymentMethodChart object. <b>null</b> if none is found. */ public PaymentMethodChart getPaymentMethodChartInfo(String chartOfAccountsCode, java.sql.Date transDate) { if (transDate == null) { transDate = SpringContext.getBean(DateTimeService.class).getCurrentSqlDate(); } if (ObjectUtils.isNotNull(getPaymentMethodCharts()) && chartOfAccountsCode != null) { // pull the first one matching the chart where the date is before/equal to today // the ORM mapping ensures that these are retrieved in reverse date order, // so the first one found will be the effective entry for (PaymentMethodChart pmc : getPaymentMethodCharts()) { if (StringUtils.equals(pmc.getChartOfAccountsCode(), chartOfAccountsCode) && transDate.after(pmc.getEffectiveDate())) { return pmc; } } } return null; }
From source file:dk.netarkivet.archive.arcrepositoryadmin.ReplicaCacheDatabaseTester.java
License:asdf
@SuppressWarnings("unchecked") @Test/*from ww w. j ava 2 s .c o m*/ // FIXME: Split test up. public void testAll() throws Exception { LogbackRecorder lr = LogbackRecorder.startRecorder(); Date beforeTest = new Date(Calendar.getInstance().getTimeInMillis()); assertTrue("The database should be empty to begin with.", cache.isEmpty()); // try handling output from ChecksumJob. File csFile = makeTemporaryChecksumFile1(); cache.addChecksumInformation(csFile, Replica.getReplicaFromId("ONE")); // try handling output from FilelistJob. File flFile = makeTemporaryFilelistFile(); cache.addFileListInformation(flFile, Replica.getReplicaFromId("TWO")); Date dbDate = cache.getDateOfLastMissingFilesUpdate(Replica.getReplicaFromId("TWO")); Date afterInsert = new Date(Calendar.getInstance().getTimeInMillis()); // Assert that the time of insert is between the start of this test // and now. String stepMessage = "The last missing file update for replica '" + Replica.getReplicaFromId("ONE") + "' should be after the test was begun. Thus '" + DateFormat.getDateInstance().format(dbDate) + "' should be after '" + DateFormat.getDateInstance().format(beforeTest) + "'."; assertTrue(stepMessage, dbDate.after(beforeTest)); stepMessage = "The last missing file update for replica '" + Replica.getReplicaFromId("ONE") + "' should be before " + "the current time. Thus '" + DateFormat.getDateInstance().format(dbDate) + "' should be before '" + DateFormat.getDateInstance().format(afterInsert) + "'."; assertTrue(stepMessage, dbDate.before(afterInsert)); // Check that getDateOfLastWrongFilesUpdate gives a date between // the start of this test and now. dbDate = cache.getDateOfLastWrongFilesUpdate(Replica.getReplicaFromId("ONE")); stepMessage = "The last missing file update for replica '" + Replica.getReplicaFromId("ONE") + "' should be after " + "the test was begun. Thus '" + DateFormat.getDateInstance().format(dbDate) + "' should be after '" + DateFormat.getDateInstance().format(beforeTest) + "'."; assertTrue(stepMessage, dbDate.after(beforeTest)); stepMessage = "The last missing file update for replica '" + Replica.getReplicaFromId("ONE") + "' should be before " + "the current time. Thus '" + DateFormat.getDateInstance().format(dbDate) + "' should be before '" + DateFormat.getDateInstance().format(afterInsert) + "'."; assertTrue(stepMessage, dbDate.before(afterInsert)); // retrieve empty file and set all files in replica 'THREE' to missing File fl2File = makeTemporaryEmptyFilelistFile(); cache.addFileListInformation(fl2File, Replica.getReplicaFromId("THREE")); // check that all files are unknown for the uninitialised replica. long files = FileUtils.countLines(csFile); assertEquals("All the files for replica 'THREE' should be missing.", files, cache.getNumberOfMissingFilesInLastUpdate(Replica.getReplicaFromId("THREE"))); // check that the getMissingFilesInLastUpdate works appropriately. //List<String> misFiles = toArrayList(cache.getMissingFilesInLastUpdate( List<String> misFiles = IteratorUtils .toList(cache.getMissingFilesInLastUpdate(Replica.getReplicaFromId("THREE")).iterator()); List<String> allFilenames = new ArrayList<String>(); for (String entry : FileUtils.readListFromFile(csFile)) { String[] e = entry.split("##"); allFilenames.add(e[0]); } assertEquals("All the files should be missing for replica 'THREE': " + misFiles + " == " + allFilenames, misFiles, allFilenames); // adding the checksum for the other replicas. cache.addChecksumInformation(csFile, Replica.getReplicaFromId("TWO")); // check that when a replica is given wrong checksums it will be // found by the update method. assertEquals("Replica 'THREE' has not been assigned checksums yet." + " Therefore not corrupt files yet!", 0, cache.getNumberOfWrongFilesInLastUpdate(Replica.getReplicaFromId("THREE"))); assertEquals("No files has been assigned to replica 'THREE' yet.", 0, cache.getNumberOfFiles(Replica.getReplicaFromId("THREE"))); File csFile2 = makeTemporaryChecksumFile2(); cache.addChecksumInformation(csFile2, Replica.getReplicaFromId("THREE")); stepMessage = "All the files in Replica 'THREE' has been assigned checksums, but not checksum update has been run yet. " + "Therefore no corrupt files yet!"; assertEquals(stepMessage, 0, cache.getNumberOfWrongFilesInLastUpdate(Replica.getReplicaFromId("THREE"))); assertEquals("Entries for replica 'THREE' has should be assigned.", FileUtils.countLines(csFile2), cache.getNumberOfFiles(Replica.getReplicaFromId("THREE"))); cache.updateChecksumStatus(); assertEquals("After update all the entries for replica 'THREE', " + "they should all be set to 'CORRUPT'!", FileUtils.countLines(csFile2), cache.getNumberOfWrongFilesInLastUpdate(Replica.getReplicaFromId("THREE"))); assertEquals("All the entries for replica 'THREE' is all corrupt, " + "but they should still be counted.", FileUtils.countLines(csFile2), cache.getNumberOfFiles(Replica.getReplicaFromId("THREE"))); // Check that all files are wrong for replica 'THREE' //List<String> wrongFiles = toArrayList(cache.getWrongFilesInLastUpdate( List<String> wrongFiles = IteratorUtils .toList(cache.getWrongFilesInLastUpdate(Replica.getReplicaFromId("THREE")).iterator()); assertEquals("All the files should be wrong for replica 'THREE': " + wrongFiles + " == " + allFilenames, wrongFiles, allFilenames); // check that a file can become missing, after it was ok, but still be ok! cache.addFileListInformation(flFile, Replica.getReplicaFromId("ONE")); stepMessage = "Replica 'ONE' had the files '" + allFilenames + "' before updating the filelist with '" + FileUtils.readListFromFile(flFile) + "'. Therefore one " + "file should now be missing."; assertEquals(stepMessage, 1, cache.getNumberOfMissingFilesInLastUpdate(Replica.getReplicaFromId("ONE"))); stepMessage = "Replica 'ONE' is missing 1 file, but since the checksum already is set to 'OK', then it is not CORRUPT"; assertEquals(stepMessage, 0, cache.getNumberOfWrongFilesInLastUpdate(Replica.getReplicaFromId("ONE"))); // set replica THREE to having the same checksum as the other two, // and update. cache.addChecksumInformation(csFile, Replica.getReplicaFromId("THREE")); cache.updateChecksumStatus(); // reset the checksums of replica ONE, thus setting the // 'checksum_status' to UNKNOWN. cache.addChecksumInformation(csFile, Replica.getReplicaFromId("ONE")); // Check that replica 'TWO' is found with good file. stepMessage = "Now only replica 'TWO' and 'THREE' both have checksum_status set to OK, and since replica 'TWO' is the only bitarchive, it should found when searching for replica with good file for the file 'TEST1'."; assertEquals(stepMessage, cache.getBitarchiveWithGoodFile("TEST1"), Replica.getReplicaFromId("TWO")); assertEquals("No bitarchive replica should be returned.", null, cache.getBitarchiveWithGoodFile("TEST1", Replica.getReplicaFromId("TWO"))); cache.changeStateOfReplicafileinfo("TEST1", Replica.getReplicaFromId("TWO"), ReplicaStoreState.UPLOAD_STARTED); cache.changeStateOfReplicafileinfo("TEST2", Replica.getReplicaFromId("TWO"), ReplicaStoreState.UPLOAD_STARTED); cache.changeStateOfReplicafileinfo("TEST1", Replica.getReplicaFromId("ONE"), ReplicaStoreState.UPLOAD_FAILED); Collection<String> names = cache.retrieveFilenamesForReplicaEntries("TWO", ReplicaStoreState.UPLOAD_STARTED); assertTrue("The list of names should contain TEST1", names.contains("TEST1")); assertTrue("The list of names should contain TEST2", names.contains("TEST2")); cache.insertNewFileForUpload("TEST5", "asdfasdf0123"); try { cache.insertNewFileForUpload("TEST5", "01234567890"); fail("It should not be allowed to reupload a file with another checksum."); } catch (IllegalState e) { // expected assertTrue("It should say, the checksum is wrong, but said: " + e.getMessage(), e.getMessage().contains("The file 'TEST5' with checksum 'asdfasdf0123'" + " has attempted being uploaded with the checksum '" + "01234567890" + "'")); } cache.changeStateOfReplicafileinfo("TEST5", "asdffdas0123", Replica.getReplicaFromId("TWO"), ReplicaStoreState.UPLOAD_COMPLETED); cache.changeStateOfReplicafileinfo("TEST5", "fdsafdas0123", Replica.getReplicaFromId("THREE"), ReplicaStoreState.UPLOAD_COMPLETED); try { cache.insertNewFileForUpload("TEST5", "asdfasdf0123"); fail("It should not be allowed to reupload a file when it has been completed."); } catch (IllegalState e) { // expected assertTrue("It should say, that it has already been completely uploaded, but said: " + e.getMessage(), e.getMessage().contains("The file has already been " + "completely uploaded to the replica: ")); } assertNull("No common checksum should be found for file TEST5", cache.getChecksum("TEST5")); cache.changeStateOfReplicafileinfo("TEST5", "fdsafdas0123", Replica.getReplicaFromId("TWO"), ReplicaStoreState.UPLOAD_COMPLETED); assertEquals("The checksum for file 'TEST5' should be fdsafdas0123", "fdsafdas0123", cache.getChecksum("TEST5")); // check content String content = cache.retrieveAsText(); for (String filename : cache.retrieveAllFilenames()) { assertTrue("The filename '" + filename + "' should be in the content", content.contains(filename)); } for (Replica rep : Replica.getKnown()) { assertEquals("Unexpected filelist status", FileListStatus.NO_FILELIST_STATUS, cache.retrieveFileListStatus("TEST5", rep)); } // check for duplicates cache.addFileListInformation(makeTemporaryDuplicateFilelistFile(), Replica.getReplicaFromId("ONE")); boolean stop = true; if (stop) { return; } lr.assertLogContains("Warning about duplicates should be generated", "There have been found multiple files with the name 'TEST1'"); // cleanup afterwards. cache.cleanup(); lr.stopRecorder(); }
From source file:com.wso2telco.dep.reportingservice.northbound.NbHostObjectUtils.java
/** * Apply tax for block charging.// ww w. jav a 2s .c o m * * @param CatEntry the cat entry * @param rate the rate * @param year the year * @param month the month * @throws Exception */ private static void applyTaxForBlockCharging(Map.Entry<CategoryCharge, BilledCharge> CatEntry, ChargeRate rate, String year, String month) throws Exception { TaxDAO taxDAO = new TaxDAO(); List<Tax> taxList = taxDAO.getTaxesForTaxList(rate.getTaxList()); CategoryCharge categorycharge = CatEntry.getKey(); BilledCharge billed = CatEntry.getValue(); BigDecimal totalTax = BigDecimal.ZERO; Date billingDate = Date.valueOf(year + "-" + month + "-01"); // start of // the // month for (Tax tax : taxList) { // select the taxes applicable at the billing date if (!billingDate.before(tax.getEffective_from()) && !billingDate.after(tax.getEffective_to())) { // totalTax += taxFraction x charge totalTax = totalTax.add(tax.getValue().multiply(billed.getPrice())); } } CatEntry.getValue().setTax(totalTax); }
From source file:com.wso2telco.dep.reportingservice.northbound.NbHostObjectUtils.java
/** * Apply payment charges by category.//www. ja va 2 s . c o m * * @param opSubscription the op subscription * @param categoryCharge the category charge * @param paymentRequestSet the payment request set * @throws Exception */ private static void applyPaymentChargesByCategory(BillingSubscription.OperatorSubscription opSubscription, CategoryCharge categoryCharge, Set<PaymentRequestDTO> paymentRequestSet) throws Exception { TaxDAO taxDAO = new TaxDAO(); ChargeRate rate = opSubscription.getRate(); List<Tax> taxList = taxDAO.getTaxesForTaxList(rate.getTaxList()); BigDecimal totalCharge = BigDecimal.ZERO; BigDecimal totalPrice = BigDecimal.ZERO; BigDecimal totalTax = BigDecimal.ZERO; for (PaymentRequestDTO paymentRequest : paymentRequestSet) { totalCharge = totalCharge.add(paymentRequest.getAmount()); BigDecimal price = BigDecimal.ZERO; CategoryEntity rateCategories = new CategoryEntity(); if (rateCategories == null) { throw new APIManagementException( "Payment Categoreis required for QUOTA charging are not specified in rate-card.xml"); } BigDecimal catpercent = rate.getValue().divide(new BigDecimal(100)); Date date = new Date(paymentRequest.getDate().getTime()); for (Tax tax : taxList) { // check if the date of payment request falls between this tax // validity period if (!date.before(tax.getEffective_from()) && !date.after(tax.getEffective_to())) { // totalTax += taxFraction x paymentAmount totalTax = totalTax.add(tax.getValue().multiply(price)); } } } // Get the percentage from the rate value // BigDecimal percentage = rate.getValue().divide(new BigDecimal(100)); // apply category wise charge percentage }
From source file:com.wso2telco.dep.reportingservice.northbound.NbHostObjectUtils.java
/** * Apply charges with tax.//from w w w.j a v a2s . c om * * @param apiYear the api year * @param apiMonth the api month * @param application the application * @param apiName the api name * @param apiVersion the api version * @param operatorSub the operator sub * @param CatEntry the cat entry * @param rate the rate * @throws Exception */ private static void applyChargesWithTax(String apiYear, String apiMonth, Application application, String apiName, String apiVersion, BillingSubscription.OperatorSubscription operatorSub, Map.Entry<CategoryCharge, BilledCharge> CatEntry, ChargeRate rate) throws Exception { String month = apiMonth; String year = apiYear; boolean isSurcharge = false; if (application == null) { throw new APIManagementException("no key generated for this api"); } APIKey prodKey = getAppKey(application, APIConstants.API_KEY_TYPE_PRODUCTION); TaxDAO taxDAO = new TaxDAO(); Set<APIRequestDTO> requestTimes = new HashSet<APIRequestDTO>(); if (prodKey != null) { String api_version = apiName + ":v" + apiVersion; requestTimes = taxDAO.getNbAPIRequestTimesForSubscription(Short.parseShort(year), Short.parseShort(month), apiName, api_version, prodKey.getConsumerKey(), operatorSub.getOperationId(), CatEntry.getKey().getCategory(), CatEntry.getKey().getSubcategory()); } // ChargeRate rate = operatorSub.getRate(); String billCategory = CatEntry.getKey().getCategory(); String billSubCategory = CatEntry.getKey().getSubcategory(); BigDecimal billRate = rate.getValue(); BigDecimal OpscomPercnt = null; Object SubsRate = getRateSubcategory(rate, billCategory, billSubCategory); if (SubsRate != null) { billRate = new BigDecimal((String) SubsRate); } // Surcharge value if (rate.getSurchargeEntity() != null) { billRate = new BigDecimal(rate.getSurchargeEntity().getSurchargeElementValue()); OpscomPercnt = new BigDecimal(rate.getSurchargeEntity().getSurchargeElementOpco()) .divide(new BigDecimal(100)); isSurcharge = true; } List<Tax> taxList = taxDAO.getTaxesForTaxList(rate.getTaxList()); BigDecimal totalCharge = BigDecimal.ZERO; BigDecimal totalTax = BigDecimal.ZERO; BigDecimal totalOpcom = BigDecimal.ZERO; BigDecimal totalAdscom = BigDecimal.ZERO; int reqCount = 0; for (APIRequestDTO req : requestTimes) { if (reqCount >= CatEntry.getValue().getCount()) { break; } BigDecimal charge = billRate.multiply(new BigDecimal(req.getRequestCount())); if (isSurcharge) { BigDecimal opcoCommision = billRate.multiply(OpscomPercnt); totalOpcom = totalOpcom.add(opcoCommision); totalAdscom = totalAdscom.add(charge.subtract(opcoCommision)); } else { totalCharge = totalCharge.add(charge); } Date date = req.getDate(); for (Tax tax : taxList) { // check if the date of payment request falls between this tax // validity period if (!date.before(tax.getEffective_from()) && !date.after(tax.getEffective_to())) { // totalTax += taxFraction x charge totalTax = totalTax.add(tax.getValue().multiply(charge)); } } reqCount++; } CatEntry.getValue().addPrice(totalCharge); CatEntry.getValue().addTax(totalTax); CatEntry.getValue().addOpcom(totalOpcom); CatEntry.getValue().addAdscom(totalAdscom); }