Search in sources :

Example 1 with DateMidnight

use of org.joda.time.DateMidnight in project qi4j-sdk by Qi4j.

the class BookNewCargo method buildRouteSpecification.

public RouteSpecification buildRouteSpecification(ValueBuilderFactory vbf, Location origin, Location destination, Date deadline) {
    if (origin == destination) {
        throw new RouteException("Origin location can't be same as destination location.");
    }
    if (deadline == null) {
        throw new RouteException("Arrival deadline cannot be null.");
    }
    Date endOfToday = new DateMidnight().plusDays(1).toDate();
    if (deadline.before(endOfToday)) {
        throw new RouteException("Arrival deadline is in the past or Today." + "\nDeadline           " + deadline + "\nToday (midnight)   " + endOfToday);
    }
    ValueBuilder<RouteSpecification> routeSpec = vbf.newValueBuilder(RouteSpecification.class);
    routeSpec.prototype().origin().set(origin);
    routeSpec.prototype().destination().set(destination);
    routeSpec.prototype().arrivalDeadline().set(deadline);
    return routeSpec.newInstance();
}
Also used : DateMidnight(org.joda.time.DateMidnight) RouteSpecification(org.qi4j.sample.dcicargo.sample_a.data.shipping.cargo.RouteSpecification) Date(java.util.Date)

Example 2 with DateMidnight

use of org.joda.time.DateMidnight in project ice by Netflix.

the class BasicLineItemProcessor method process.

public Result process(long startMilli, boolean processDelayed, ProcessorConfig config, String[] items, Map<Product, ReadWriteData> usageDataByProduct, Map<Product, ReadWriteData> costDataByProduct, Map<String, Double> ondemandRate) {
    if (StringUtils.isEmpty(items[accountIdIndex]) || StringUtils.isEmpty(items[productIndex]) || StringUtils.isEmpty(items[usageTypeIndex]) || StringUtils.isEmpty(items[operationIndex]) || StringUtils.isEmpty(items[usageQuantityIndex]) || StringUtils.isEmpty(items[costIndex]))
        return Result.ignore;
    Account account = config.accountService.getAccountById(items[accountIdIndex]);
    if (account == null)
        return Result.ignore;
    double usageValue = Double.parseDouble(items[usageQuantityIndex]);
    double costValue = Double.parseDouble(items[costIndex]);
    long millisStart;
    long millisEnd;
    try {
        millisStart = amazonBillingDateFormat.parseMillis(items[startTimeIndex]);
        millisEnd = amazonBillingDateFormat.parseMillis(items[endTimeIndex]);
    } catch (IllegalArgumentException e) {
        millisStart = amazonBillingDateFormat2.parseMillis(items[startTimeIndex]);
        millisEnd = amazonBillingDateFormat2.parseMillis(items[endTimeIndex]);
    }
    Product product = config.productService.getProductByAwsName(items[productIndex]);
    boolean reservationUsage = "Y".equals(items[reservedIndex]);
    ReformedMetaData reformedMetaData = reform(millisStart, config, product, reservationUsage, items[operationIndex], items[usageTypeIndex], items[descriptionIndex], costValue);
    product = reformedMetaData.product;
    Operation operation = reformedMetaData.operation;
    UsageType usageType = reformedMetaData.usageType;
    Zone zone = Zone.getZone(items[zoneIndex], reformedMetaData.region);
    int startIndex = (int) ((millisStart - startMilli) / AwsUtils.hourMillis);
    int endIndex = (int) ((millisEnd + 1000 - startMilli) / AwsUtils.hourMillis);
    Result result = Result.hourly;
    if (product == Product.ec2_instance) {
        result = processEc2Instance(processDelayed, reservationUsage, operation, zone);
    } else if (product == Product.redshift) {
        result = processRedshift(processDelayed, reservationUsage, operation, costValue);
    } else if (product == Product.data_transfer) {
        result = processDataTranfer(processDelayed, usageType);
    } else if (product == Product.cloudhsm) {
        result = processCloudhsm(processDelayed, usageType);
    } else if (product == Product.ebs) {
        result = processEbs(usageType);
    } else if (product == Product.rds) {
        result = processRds(usageType);
    }
    if (result == Result.ignore || result == Result.delay)
        return result;
    if (usageType.name.startsWith("TimedStorage-ByteHrs"))
        result = Result.daily;
    boolean monthlyCost = StringUtils.isEmpty(items[descriptionIndex]) ? false : items[descriptionIndex].toLowerCase().contains("-month");
    ReadWriteData usageData = usageDataByProduct.get(null);
    ReadWriteData costData = costDataByProduct.get(null);
    ReadWriteData usageDataOfProduct = usageDataByProduct.get(product);
    ReadWriteData costDataOfProduct = costDataByProduct.get(product);
    if (result == Result.daily) {
        DateMidnight dm = new DateMidnight(millisStart, DateTimeZone.UTC);
        millisStart = dm.getMillis();
        startIndex = (int) ((millisStart - startMilli) / AwsUtils.hourMillis);
        endIndex = startIndex + 24;
    } else if (result == Result.monthly) {
        startIndex = 0;
        endIndex = usageData.getNum();
        int numHoursInMonth = new DateTime(startMilli, DateTimeZone.UTC).dayOfMonth().getMaximumValue() * 24;
        usageValue = usageValue * endIndex / numHoursInMonth;
        costValue = costValue * endIndex / numHoursInMonth;
    }
    if (monthlyCost) {
        int numHoursInMonth = new DateTime(startMilli, DateTimeZone.UTC).dayOfMonth().getMaximumValue() * 24;
        usageValue = usageValue * numHoursInMonth;
    }
    int[] indexes;
    if (endIndex - startIndex > 1) {
        usageValue = usageValue / (endIndex - startIndex);
        costValue = costValue / (endIndex - startIndex);
        indexes = new int[endIndex - startIndex];
        for (int i = 0; i < indexes.length; i++) indexes[i] = startIndex + i;
    } else {
        indexes = new int[] { startIndex };
    }
    TagGroup tagGroup = TagGroup.getTagGroup(account, reformedMetaData.region, zone, product, operation, usageType, null);
    TagGroup resourceTagGroup = null;
    if (costValue > 0 && !reservationUsage && product == Product.ec2_instance && tagGroup.operation == Operation.ondemandInstances) {
        String key = operation + "|" + tagGroup.region + "|" + usageType;
        ondemandRate.put(key, costValue / usageValue);
    }
    double resourceCostValue = costValue;
    if (items.length > resourceIndex && !StringUtils.isEmpty(items[resourceIndex]) && config.resourceService != null) {
        if (config.useCostForResourceGroup.equals("modeled") && product == Product.ec2_instance)
            operation = Operation.getReservedInstances(config.reservationService.getDefaultReservationUtilization(0L));
        if (product == Product.ec2_instance && operation instanceof Operation.ReservationOperation) {
            UsageType usageTypeForPrice = usageType;
            if (usageType.name.endsWith(InstanceOs.others.name())) {
                usageTypeForPrice = UsageType.getUsageType(usageType.name.replace(InstanceOs.others.name(), InstanceOs.windows.name()), usageType.unit);
            }
            try {
                resourceCostValue = usageValue * config.reservationService.getLatestHourlyTotalPrice(millisStart, tagGroup.region, usageTypeForPrice, config.reservationService.getDefaultReservationUtilization(0L));
            } catch (Exception e) {
                logger.error("failed to get RI price for " + tagGroup.region + " " + usageTypeForPrice);
                resourceCostValue = -1;
            }
        }
        String resourceGroupStr = config.resourceService.getResource(account, reformedMetaData.region, product, items[resourceIndex], items, millisStart);
        if (!StringUtils.isEmpty(resourceGroupStr)) {
            ResourceGroup resourceGroup = ResourceGroup.getResourceGroup(resourceGroupStr);
            resourceTagGroup = TagGroup.getTagGroup(account, reformedMetaData.region, zone, product, operation, usageType, resourceGroup);
            if (usageDataOfProduct == null) {
                usageDataOfProduct = new ReadWriteData();
                costDataOfProduct = new ReadWriteData();
                usageDataByProduct.put(product, usageDataOfProduct);
                costDataByProduct.put(product, costDataOfProduct);
            }
        }
    }
    if (config.randomizer != null && product == Product.monitor)
        return result;
    for (int i : indexes) {
        if (config.randomizer != null) {
            if (tagGroup.product != Product.rds && tagGroup.product != Product.s3 && usageData.getData(i).get(tagGroup) != null)
                break;
            long time = millisStart + i * AwsUtils.hourMillis;
            usageValue = config.randomizer.randomizeUsage(time, resourceTagGroup == null ? tagGroup : resourceTagGroup, usageValue);
            costValue = usageValue * config.randomizer.randomizeCost(tagGroup);
        }
        if (product != Product.monitor) {
            Map<TagGroup, Double> usages = usageData.getData(i);
            Map<TagGroup, Double> costs = costData.getData(i);
            addValue(usages, tagGroup, usageValue, config.randomizer == null || tagGroup.product == Product.rds || tagGroup.product == Product.s3);
            addValue(costs, tagGroup, costValue, config.randomizer == null || tagGroup.product == Product.rds || tagGroup.product == Product.s3);
        } else {
            resourceCostValue = usageValue * config.costPerMonitorMetricPerHour;
        }
        if (resourceTagGroup != null) {
            Map<TagGroup, Double> usagesOfResource = usageDataOfProduct.getData(i);
            Map<TagGroup, Double> costsOfResource = costDataOfProduct.getData(i);
            if (config.randomizer == null || tagGroup.product == Product.rds || tagGroup.product == Product.s3) {
                addValue(usagesOfResource, resourceTagGroup, usageValue, product != Product.monitor);
                if (!config.useCostForResourceGroup.equals("modeled") || resourceCostValue < 0) {
                    addValue(costsOfResource, resourceTagGroup, costValue, product != Product.monitor);
                } else {
                    addValue(costsOfResource, resourceTagGroup, resourceCostValue, product != Product.monitor);
                }
            } else {
                Map<String, Double> distribution = config.randomizer.getDistribution(tagGroup);
                for (Map.Entry<String, Double> entry : distribution.entrySet()) {
                    String app = entry.getKey();
                    double dist = entry.getValue();
                    resourceTagGroup = TagGroup.getTagGroup(account, reformedMetaData.region, zone, product, operation, usageType, ResourceGroup.getResourceGroup(app));
                    double usage = usageValue * dist;
                    if (product == Product.ec2_instance)
                        usage = (int) usageValue * dist;
                    addValue(usagesOfResource, resourceTagGroup, usage, false);
                    addValue(costsOfResource, resourceTagGroup, usage * config.randomizer.randomizeCost(tagGroup), false);
                }
            }
        }
    }
    return result;
}
Also used : DateTime(org.joda.time.DateTime) DateMidnight(org.joda.time.DateMidnight) DateTimeZone(org.joda.time.DateTimeZone) Map(java.util.Map)

Example 3 with DateMidnight

use of org.joda.time.DateMidnight in project ice by Netflix.

the class BasicReservationService method pollAPI.

private void pollAPI() throws Exception {
    long currentTime = new DateMidnight().getMillis();
    DescribeReservedInstancesOfferingsRequest req = new DescribeReservedInstancesOfferingsRequest().withFilters(new com.amazonaws.services.ec2.model.Filter().withName("marketplace").withValues("false"));
    String token = null;
    boolean hasNewPrice = false;
    AmazonEC2Client ec2Client = new AmazonEC2Client(AwsUtils.awsCredentialsProvider, AwsUtils.clientConfig);
    for (Region region : Region.getAllRegions()) {
        ec2Client.setEndpoint("ec2." + region.name + ".amazonaws.com");
        do {
            if (!StringUtils.isEmpty(token))
                req.setNextToken(token);
            DescribeReservedInstancesOfferingsResult offers = ec2Client.describeReservedInstancesOfferings(req);
            token = offers.getNextToken();
            for (ReservedInstancesOffering offer : offers.getReservedInstancesOfferings()) {
                if (offer.getProductDescription().indexOf("Amazon VPC") >= 0)
                    continue;
                ReservationUtilization utilization = ReservationUtilization.get(offer.getOfferingType());
                Ec2InstanceReservationPrice.ReservationPeriod term = offer.getDuration() / 24 / 3600 > 366 ? Ec2InstanceReservationPrice.ReservationPeriod.threeyear : Ec2InstanceReservationPrice.ReservationPeriod.oneyear;
                if (term != this.term)
                    continue;
                double hourly = offer.getUsagePrice();
                if (hourly <= 0) {
                    for (RecurringCharge recurringCharge : offer.getRecurringCharges()) {
                        if (recurringCharge.getFrequency().equals("Hourly")) {
                            hourly = recurringCharge.getAmount();
                            break;
                        }
                    }
                }
                UsageType usageType = getUsageType(offer.getInstanceType(), offer.getProductDescription());
                // Unknown Zone
                if (Zone.getZone(offer.getAvailabilityZone()) == null) {
                    logger.error("No Zone for " + offer.getAvailabilityZone());
                } else {
                    hasNewPrice = setPrice(utilization, currentTime, Zone.getZone(offer.getAvailabilityZone()).region, usageType, offer.getFixedPrice(), hourly) || hasNewPrice;
                    logger.info("Setting RI price for " + Zone.getZone(offer.getAvailabilityZone()).region + " " + utilization + " " + usageType + " " + offer.getFixedPrice() + " " + hourly);
                }
            }
        } while (!StringUtils.isEmpty(token));
    }
    ec2Client.shutdown();
    if (hasNewPrice) {
        for (ReservationUtilization utilization : files.keySet()) {
            File file = files.get(utilization);
            DataOutputStream out = new DataOutputStream(new FileOutputStream(file));
            try {
                Serializer.serialize(out, this.ec2InstanceReservationPrices.get(utilization));
                AwsUtils.upload(config.workS3BucketName, config.workS3BucketPrefix, file);
            } finally {
                out.close();
            }
        }
    }
}
Also used : AmazonEC2Client(com.amazonaws.services.ec2.AmazonEC2Client) Ec2InstanceReservationPrice(com.netflix.ice.processor.Ec2InstanceReservationPrice) DateMidnight(org.joda.time.DateMidnight) Region(com.netflix.ice.tag.Region) com.amazonaws.services.ec2.model(com.amazonaws.services.ec2.model)

Example 4 with DateMidnight

use of org.joda.time.DateMidnight in project head by mifos.

the class CenterServiceFacadeWebTier method createNewCenter.

@Override
public CustomerDetailsDto createNewCenter(CenterCreationDetail createCenterDetail, MeetingDto meetingDto) {
    MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);
    OfficeBO userOffice = this.officeDao.findOfficeById(userContext.getBranchId());
    userContext.setBranchGlobalNum(userOffice.getGlobalOfficeNum());
    String centerName = createCenterDetail.getDisplayName();
    String externalId = createCenterDetail.getExternalId();
    AddressDto addressDto = createCenterDetail.getAddressDto();
    Address centerAddress = new Address(addressDto.getLine1(), addressDto.getLine2(), addressDto.getLine3(), addressDto.getCity(), addressDto.getState(), addressDto.getCountry(), addressDto.getZip(), addressDto.getPhoneNumber());
    PersonnelBO loanOfficer = this.personnelDao.findPersonnelById(createCenterDetail.getLoanOfficerId());
    OfficeBO centerOffice = this.officeDao.findOfficeById(createCenterDetail.getOfficeId());
    List<AccountFeesEntity> feesForCustomerAccount = createAccountFeeEntities(createCenterDetail.getFeesToApply());
    DateTime mfiJoiningDate = null;
    if (createCenterDetail.getMfiJoiningDate() != null) {
        mfiJoiningDate = createCenterDetail.getMfiJoiningDate().toDateMidnight().toDateTime();
    }
    MeetingBO meeting = new MeetingFactory().create(meetingDto);
    meeting.setUserContext(userContext);
    CenterBO center = CenterBO.createNew(userContext, centerName, mfiJoiningDate, meeting, loanOfficer, centerOffice, centerAddress, externalId, new DateMidnight().toDateTime());
    try {
        personnelDao.checkAccessPermission(userContext, center.getOfficeId(), center.getLoanOfficerId());
    } catch (AccountException e) {
        throw new MifosRuntimeException("Access denied!", e);
    }
    this.customerService.createCenter(center, meeting, feesForCustomerAccount);
    return new CustomerDetailsDto(center.getCustomerId(), center.getGlobalCustNum());
}
Also used : Address(org.mifos.framework.business.util.Address) UserContext(org.mifos.security.util.UserContext) MeetingBO(org.mifos.application.meeting.business.MeetingBO) CenterBO(org.mifos.customers.center.business.CenterBO) MifosUser(org.mifos.security.MifosUser) CustomerAddressDto(org.mifos.dto.domain.CustomerAddressDto) AddressDto(org.mifos.dto.domain.AddressDto) MeetingFactory(org.mifos.application.meeting.business.MeetingFactory) DateTime(org.joda.time.DateTime) AccountException(org.mifos.accounts.exceptions.AccountException) OfficeBO(org.mifos.customers.office.business.OfficeBO) PersonnelBO(org.mifos.customers.personnel.business.PersonnelBO) DateMidnight(org.joda.time.DateMidnight) CustomerDetailsDto(org.mifos.dto.domain.CustomerDetailsDto) AccountFeesEntity(org.mifos.accounts.business.AccountFeesEntity) MifosRuntimeException(org.mifos.core.MifosRuntimeException)

Example 5 with DateMidnight

use of org.joda.time.DateMidnight in project head by mifos.

the class CenterPersistence method createCenter.

/**
     * @deprecated use {@link CustomerDao#save(org.mifos.customers.business.CustomerBO)} with {@link CustomerBO} static
     *             factory methods.
     */
@Deprecated
public CenterBO createCenter(UserContext userContext, CenterTemplate template) throws Exception {
    OfficeBO centerOffice = officePersistence.getOffice(template.getOfficeId());
    PersonnelBO loanOfficer = legacyPersonnelDao.getPersonnel(template.getLoanOfficerId());
    MeetingBO meeting = template.getMeeting();
    CenterBO center = CenterBO.createNew(userContext, template.getDisplayName(), new DateTime(template.getMfiJoiningDate()), meeting, loanOfficer, centerOffice, template.getAddress(), template.getExternalId(), new DateMidnight().toDateTime());
    CustomerDao customerDao = ApplicationContextProvider.getBean(CustomerDao.class);
    try {
        StaticHibernateUtil.startTransaction();
        customerDao.save(center);
        center.generateGlobalCustomerNumber();
        customerDao.save(center);
        StaticHibernateUtil.commitTransaction();
    } catch (Exception e) {
        StaticHibernateUtil.rollbackTransaction();
    } finally {
        StaticHibernateUtil.closeSession();
    }
    return center;
}
Also used : OfficeBO(org.mifos.customers.office.business.OfficeBO) PersonnelBO(org.mifos.customers.personnel.business.PersonnelBO) DateMidnight(org.joda.time.DateMidnight) MeetingBO(org.mifos.application.meeting.business.MeetingBO) CenterBO(org.mifos.customers.center.business.CenterBO) CustomerDao(org.mifos.customers.persistence.CustomerDao) DateTime(org.joda.time.DateTime) CustomerException(org.mifos.customers.exceptions.CustomerException) HibernateSearchException(org.mifos.framework.exceptions.HibernateSearchException) PersistenceException(org.mifos.framework.exceptions.PersistenceException)

Aggregations

DateMidnight (org.joda.time.DateMidnight)70 DateTime (org.joda.time.DateTime)33 Test (org.junit.Test)27 ArrayList (java.util.ArrayList)10 Money (org.mifos.framework.util.helpers.Money)10 Ignore (org.junit.Ignore)8 MeetingBO (org.mifos.application.meeting.business.MeetingBO)8 LocalDate (org.joda.time.LocalDate)6 SavingsScheduleEntity (org.mifos.accounts.savings.business.SavingsScheduleEntity)6 Holiday (org.mifos.application.holiday.business.Holiday)6 Date (java.util.Date)5 AccountActionDateEntity (org.mifos.accounts.business.AccountActionDateEntity)5 OfficeBO (org.mifos.customers.office.business.OfficeBO)5 HolidayBuilder (org.mifos.domain.builders.HolidayBuilder)5 AggregationInterval (org.apereo.portal.events.aggr.AggregationInterval)4 AccountFeesEntity (org.mifos.accounts.business.AccountFeesEntity)4 UserContext (org.mifos.security.util.UserContext)4 DateTimeZone (org.joda.time.DateTimeZone)3 DateTimeFormatter (org.joda.time.format.DateTimeFormatter)3 Before (org.junit.Before)3