Example usage for java.sql Date before

List of usage examples for java.sql Date before

Introduction

In this page you can find the example usage for java.sql Date before.

Prototype

public boolean before(Date when) 

Source Link

Document

Tests if this date is before the specified date.

Usage

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;//from  ww w .  j  a  v  a 2 s  .c o m
        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.github.binarywang.demo.spring.controller.WebController.java

/**
 * 8:30 ~ 11:30/*w  w  w . j  a  v  a2 s  .  c  o m*/
 * 2:00 ~ 4:00
 * 5 vehicles per hour
 * ???2
 * ?2
 * ?
 * @param session
 * @param file1
 * @param name
 * @param chepai
 * @param date
 * @param tel
 * @param file2
 * @return
 */
@RequestMapping("/uploader/yuyue")
@ResponseBody
public Map<String, Object> yuyue(HttpSession session,
        @RequestParam(name = "file1", required = false) MultipartFile file1,
        @RequestParam(name = "name", required = true) String name,
        @RequestParam(name = "chepai", required = true) String chepai,
        @RequestParam(name = "date", required = true) String date,
        @RequestParam(name = "tel", required = true) String tel,
        @RequestParam(name = "file2", required = false) MultipartFile file2,
        @RequestParam(name = "serverId", required = true) String serverId,
        @RequestParam(name = "time", required = true) int time) throws ParseException {
    Map<String, Object> ret = new HashMap<String, Object>();
    Date date1 = Date.valueOf(date);
    if (date1.before(Calendar.getInstance().getTime()) || date1.equals(Calendar.getInstance().getTime())) {
        ret.put("success", false);
        ret.put("reason", "????1-7");
        return ret;
    }
    if (wxService.getDayCounter().getCount(Calendar.getInstance().getTime(), date1) > 7) {
        ret.put("success", false);
        ret.put("reason", "?7");
        return ret;
    }
    if (wxService.getDayCounter().getCount(Calendar.getInstance().getTime(), date1) < 1) {
        ret.put("success", false);
        ret.put("reason", "???");
        return ret;
    }
    if (wxService.getDayCounter().isHoliday(date1)) {
        ret.put("success", false);
        ret.put("reason", "????");
        return ret;
    }
    WxMpUser wxMpUser = (WxMpUser) session.getAttribute("userOpenId");
    if (wxMpUser == null) {
        ret.put("success", false);
        ret.put("reason", "");
        return ret;
    }
    if (appointmentDao.findInOrderingAppointmentByOpenId(wxMpUser.getOpenId()).size() > 0) {
        ret.put("success", false);
        ret.put("reason", "??");
        return ret;
    }
    if (appointmentDao.isInBlackList(tel, wxMpUser.getOpenId())) {
        ret.put("success", false);
        ret.put("reason", "3????");
    }
    if (appointmentDao.findCountByOpenId(wxMpUser.getOpenId()) > 2) {
        ret.put("success", false);
        ret.put("reason", "???");
        return ret;
    }
    if (appointmentDao.findCountByTel(tel) > 2) {
        ret.put("success", false);
        ret.put("reason", "???");
        return ret;
    }

    if (appointmentDao.countForDay(date, time) >= 15 && time == 0) {
        ret.put("success", false);
        ret.put("reason", "??");
        return ret;
    }
    if (appointmentDao.countForDay(date, time) >= 10 && time == 1) {
        ret.put("success", false);
        ret.put("reason", "??");
        return ret;
    }

    Appointment appointment = new Appointment();
    appointment.setName(wxMpUser.getNickname());
    appointment.setOpenId(wxMpUser.getOpenId());
    appointment.setRealName(name);
    appointment.setChepai(chepai);
    appointment.setDate(date1);
    appointment.setDriverLicense("");
    appointment.setTel(tel);
    appointment.setServerId(serverId);
    appointment.setTime(time);
    appointmentDao.save(appointment);
    ret.put("success", true);
    return ret;
}

From source file:com.cemeterylistingsweb.services.impl.ViewListingByCemeteryImpl.java

@Override
public List<PublishedDeceasedListing> findListingByCemetery(Long cemId, Long subId) {
    ////from   ww w  .j a v  a  2  s . 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  ww .  j a  v  a 2  s . c  o 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;
    }/* w w  w.j av  a2 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:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.TraceFileProcessor.java

private void insertTraceRelationship(final Integer barcodeId, final Long traceId, final Long fileInfoId,
        final Date fileDate, final QcContext context) {
    if (barcodeId != null && barcodeId != -1) {
        final TraceRelationship tr = new TraceRelationship();
        tr.setTraceID(traceId);//w w w . j a  v a  2 s  .com
        tr.setBiospecimenID(barcodeId);
        tr.setDccReceived(fileDate);
        tr.setFileID(fileInfoId);
        final Date dateInDB = commonTraceRelationshipQueries.getDccDate(barcodeId, traceId);
        if (dateInDB != null) {
            // use earlier date, choosing between file mod date and date in db
            if (fileDate.before(dateInDB)) {
                // need to update the date
                commonTraceRelationshipQueries.updateDccDate(tr);
            }
            // since date not null, is already in db, so check the file info id
            final long fileIdInDb = commonTraceRelationshipQueries.getFileId(barcodeId, traceId);
            if (fileIdInDb != fileInfoId) {
                // need to update the file info id to this one
                commonTraceRelationshipQueries.updateFileID(tr);
            }
        } else {
            // relationship not in db yet, add it
            final int traceRelationshipId = commonTraceRelationshipQueries.addTraceRelationship(tr);
            if (traceRelationshipId == -1) {
                // -1 means it failed to add
                context.getArchive().setDeployStatus(Archive.STATUS_IN_REVIEW);
                context.addError(MessageFormat.format(MessagePropertyType.GENERAL_VALIDATION_MESSAGE,
                        new StringBuilder().append("Trace relationship between barcode with id ")
                                .append(barcodeId).append(" and trace id ").append(traceId)
                                .append(" in file with id ").append(fileInfoId)
                                .append(" failed to be added to the database").toString()));
            }
        }
    }
}

From source file:dk.netarkivet.archive.arcrepositoryadmin.ReplicaCacheDatabaseTester.java

License:asdf

@SuppressWarnings("unchecked")
@Test//w w w  . ja va  2s  . 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.//from ww  w  .ja  va2  s. c om
 *
 * @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.//from  w  ww  . java  2s  . 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.// w w w. j a  va 2  s  . com
 *
 * @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);

}