Example usage for org.apache.commons.lang.time DateUtils addYears

List of usage examples for org.apache.commons.lang.time DateUtils addYears

Introduction

In this page you can find the example usage for org.apache.commons.lang.time DateUtils addYears.

Prototype

public static Date addYears(Date date, int amount) 

Source Link

Document

Adds a number of years to a date returning a new object.

Usage

From source file:org.ala.hbase.RepoDataLoader.java

/**
 * This takes a list of infosource ids...
 * <p/>/*from   w ww .ja  v  a 2 s  . com*/
 * Usage: -stats or -reindex or -gList and list of infosourceId
 *
 * @param args
 */
public static void main(String[] args) throws Exception {
    //RepoDataLoader loader = new RepoDataLoader();
    ApplicationContext context = SpringUtils.getContext();
    RepoDataLoader loader = (RepoDataLoader) context.getBean(RepoDataLoader.class);
    long start = System.currentTimeMillis();
    loader.loadInfoSources();
    String filePath = repositoryDir;
    if (args.length > 0) {
        if (args[0].equalsIgnoreCase("-stats")) {
            loader.statsOnly = true;
            args = (String[]) ArrayUtils.subarray(args, 1, args.length);
        }
        if (args[0].equalsIgnoreCase("-reindex")) {
            loader.reindex = true;
            loader.indexer = context.getBean(PartialIndex.class);
            args = (String[]) ArrayUtils.subarray(args, 1, args.length);
            logger.info("**** -reindex: " + loader.reindex);
            logger.debug("reindex url: " + loader.reindexUrl);
        }
        if (args[0].equalsIgnoreCase("-gList")) {
            loader.gList = true;
            args = (String[]) ArrayUtils.subarray(args, 1, args.length);
            logger.info("**** -gList: " + loader.gList);
        }
        if (args[0].equalsIgnoreCase("-biocache")) {
            Hashtable<String, String> hashTable = new Hashtable<String, String>();
            hashTable.put("accept", "application/json");
            ObjectMapper mapper = new ObjectMapper();
            mapper.getDeserializationConfig().set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
                    false);
            RestfulClient restfulClient = new RestfulClient(0);
            String fq = "&fq=";
            if (args.length > 1) {
                java.util.Date date = new java.util.Date();
                if (args[1].equals("-lastWeek")) {
                    date = DateUtils.addWeeks(date, -1);
                } else if (args[1].equals("-lastMonth")) {
                    date = DateUtils.addMonths(date, -1);
                } else if (args[1].equals("-lastYear")) {
                    date = DateUtils.addYears(date, -1);
                } else
                    date = null;
                if (date != null) {
                    SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

                    fq += "last_load_date:%5B" + sfd.format(date) + "%20TO%20*%5D";
                }
            }

            Object[] resp = restfulClient
                    .restGet("http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq
                            + "&facets=data_resource_uid&pageSize=0", hashTable);
            logger.info("The URL: " + "http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq
                    + "&facets=data_resource_uid&pageSize=0");
            if ((Integer) resp[0] == HttpStatus.SC_OK) {
                String content = resp[1].toString();
                logger.debug(resp[1]);
                if (content != null && content.length() > "[]".length()) {
                    Map map = mapper.readValue(content, Map.class);
                    try {
                        List<java.util.LinkedHashMap<String, String>> list = ((List<java.util.LinkedHashMap<String, String>>) ((java.util.LinkedHashMap) ((java.util.ArrayList) map
                                .get("facetResults")).get(0)).get("fieldResult"));
                        Set<String> arg = new LinkedHashSet<String>();
                        for (int i = 0; i < list.size(); i++) {
                            java.util.LinkedHashMap<String, String> value = list.get(i);
                            String dataResource = getDataResource(value.get("fq"));
                            Object provider = (loader.getUidInfoSourceMap().get(dataResource));
                            if (provider != null) {
                                arg.add(provider.toString());
                            }
                        }
                        logger.info("Set of biocache infosource ids to load: " + arg);
                        args = new String[] {};
                        args = arg.toArray(args);
                        //handle the situation where biocache-service reports no data resources
                        if (args.length < 1) {
                            logger.error("No biocache data resources found. Unable to load.");
                            System.exit(0);
                        }
                    } catch (Exception e) {
                        logger.error("ERROR: exit process....." + e);
                        e.printStackTrace();
                        System.exit(0);
                    }
                }
            } else {
                logger.warn("Unable to process url: ");
            }
        }
    }
    int filesRead = loader.load(filePath, args); //FIX ME - move to config
    long finish = System.currentTimeMillis();
    logger.info(filesRead + " files scanned/loaded in: " + ((finish - start) / 60000) + " minutes "
            + ((finish - start) / 1000) + " seconds.");
    System.exit(1);
}

From source file:org.apache.lens.cube.metadata.TestDateUtil.java

@Test
public void testFloorDate() throws ParseException {
    Date date = ABSDATE_PARSER.get().parse("2015-01-01-00:00:00,000");
    Date curDate = date;/*from  www  .j ava2s .c  om*/
    for (int i = 0; i < 284; i++) {
        assertEquals(getFloorDate(curDate, YEARLY), date);
        curDate = addMilliseconds(curDate, 111111111);
    }
    assertEquals(getFloorDate(curDate, YEARLY), DateUtils.addYears(date, 1));
    assertEquals(getFloorDate(date, WEEKLY), ABSDATE_PARSER.get().parse("2014-12-28-00:00:00,000"));
}

From source file:org.codelabor.common.calendar.services.AbstractCalendarServiceImpl.java

public void afterPropertiesSet() {
    this.dateFormat = new SimpleDateFormat(formatPattern);
    Date currentDate = Calendar.getInstance().getTime();

    if (dateRangeFrom == null) {
        dateRangeFrom = DateUtils.addYears(currentDate, -dateRangeByYears);
    }//from   www .ja va2 s .c o m
    if (dateRangeTo == null) {
        dateRangeTo = DateUtils.addYears(currentDate, dateRangeByYears);
    }

    logger.debug("dateRangeFrom: {}", dateRangeFrom);
    logger.debug("currentDate: {}", currentDate);
    logger.debug("dateRangeTo: {}", dateRangeTo);

    Assert.isTrue(currentDate.after(dateRangeFrom));
    Assert.isTrue(currentDate.before(dateRangeTo));

    if (logger.isDebugEnabled()) {
        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(dateRangeTo);
        int yearRemains = calendar2.get(Calendar.YEAR) - calendar1.get(Calendar.YEAR);
        int monthRemains = calendar2.get(Calendar.MONTH) - calendar1.get(Calendar.MONTH);
        int dateRemains = calendar2.get(Calendar.DATE) - calendar1.get(Calendar.DATE);
        logger.debug("dateRangeTo remains: year: {}, month: {}, day: {}",
                new Object[] { yearRemains, monthRemains, dateRemains });
    }

    Date beforeOneWeekDateRangeTo = DateUtils.addWeeks(dateRangeTo, -1);
    if (currentDate.after(beforeOneWeekDateRangeTo)) {

        logger.warn("please renewer date range.");
    }
}

From source file:org.codelabor.system.calendar.services.HolidayCalendarServiceImpl.java

public void afterPropertiesSet() {
    this.dateFormat = new SimpleDateFormat(formatPattern);
    Date currentDate = Calendar.getInstance().getTime();
    logger.debug("currentDate: {}", currentDate);
    if (dateRangeTo == null && dateRangeFrom == null) {
        dateRangeTo = DateUtils.addYears(currentDate, dateRangeByYears);
        dateRangeFrom = DateUtils.addYears(currentDate, -dateRangeByYears);
    }//from  w  w w . j a v a  2  s. c o m
    logger.debug("dateRangeTo: {}", dateRangeTo);
    logger.debug("dateRangeFrom: {}", dateRangeFrom);

}

From source file:org.gbif.portal.web.controller.dataset.DataProviderLogController.java

/**
 * Adds the drop down content./*from  w  w  w  .  j  av a 2  s  . c o m*/
 * @param request
 * @param mav
 */
@SuppressWarnings("unchecked")
private void addDropDownContent(HttpServletRequest request, ModelAndView mav) {

    //add today and a year from today
    Date today = new Date(System.currentTimeMillis());
    mav.addObject("today", today);
    Date lastWeek = DateUtils.addDays(today, -6);
    mav.addObject("lastWeek", lastWeek);
    Date oneMonthAgo = DateUtils.addMonths(today, -1);
    mav.addObject("oneMonthAgo", oneMonthAgo);
    Date oneYearAgo = DateUtils.addYears(today, -1);
    mav.addObject("oneYearAgo", oneYearAgo);

    //add event enumerations
    Collection<LogEvent> logEvents = (Collection) LogEvent.getValueMap().values();
    //split into 4 categories - Harvest, Extract, User and Other
    List<KeyValueDTO> harvestEvents = new ArrayList<KeyValueDTO>();
    List<KeyValueDTO> extractEvents = new ArrayList<KeyValueDTO>();
    List<KeyValueDTO> userEvents = new ArrayList<KeyValueDTO>();
    List<KeyValueDTO> usageEvents = new ArrayList<KeyValueDTO>();
    List<KeyValueDTO> otherEvents = new ArrayList<KeyValueDTO>();

    Locale locale = RequestContextUtils.getLocale(request);

    for (LogEvent logEvent : logEvents) {
        String name = messageSource.getMessage(logEvent.getName(), null, logEvent.getName(), locale);
        KeyValueDTO keyValue = new KeyValueDTO(logEvent.getValue().toString(), name);
        if (logEvent.getValue() >= LogEvent.HARVEST_RANGE_START
                && logEvent.getValue() <= LogEvent.HARVEST_RANGE_END)
            harvestEvents.add(keyValue);
        else if (logEvent.getValue() >= LogEvent.EXTRACT_RANGE_START
                && logEvent.getValue() <= LogEvent.EXTRACT_RANGE_END)
            extractEvents.add(keyValue);
        else if (logEvent.getValue() >= LogEvent.USER_RANGE_START
                && logEvent.getValue() <= LogEvent.USER_RANGE_END)
            userEvents.add(keyValue);
        else if (logEvent.getValue() >= LogEvent.USAGE_RANGE_START
                && logEvent.getValue() <= LogEvent.USAGE_RANGE_END)
            usageEvents.add(keyValue);
        else
            otherEvents.add(keyValue);
    }

    //sort alphabetically
    Collections.sort(harvestEvents, new KeyValueDTO.ValueComparator());
    Collections.sort(extractEvents, new KeyValueDTO.ValueComparator());
    Collections.sort(userEvents, new KeyValueDTO.ValueComparator());
    Collections.sort(otherEvents, new KeyValueDTO.ValueComparator());

    if (!harvestEvents.isEmpty() && harvestEvents.size() > 1) {
        harvestEvents.add(0, new KeyValueDTO(allHarvestEventsRequestKey,
                messageSource.getMessage("harvestAll", null, "Harvest - all", locale)));
    }
    mav.addObject("harvestEvents", harvestEvents);

    if (!extractEvents.isEmpty() && extractEvents.size() > 1) {
        extractEvents.add(0, new KeyValueDTO(allExtractEventsRequestKey,
                messageSource.getMessage("extractAll", null, "Extract - all", locale)));
        extractEvents.add(1, new KeyValueDTO(allExtractIssuesEventsRequestKey,
                messageSource.getMessage("extractAllIssues", null, "Extract - all issues", locale)));
    }
    mav.addObject("extractEvents", extractEvents);

    if (!userEvents.isEmpty() && userEvents.size() > 1) {
        userEvents.add(0, new KeyValueDTO(allUserEventsRequestKey,
                messageSource.getMessage("userAll", null, "User - all", locale)));
    }
    mav.addObject("userEvents", userEvents);

    if (!usageEvents.isEmpty() && usageEvents.size() > 1) {
        usageEvents.add(0, new KeyValueDTO(allUsageEventsRequestKey,
                messageSource.getMessage("usageAll", null, "Usage - all", locale)));
    }
    mav.addObject("usageEvents", usageEvents);
    mav.addObject("otherEvents", otherEvents);
}

From source file:org.gbif.portal.web.controller.occurrence.OccurrenceFilterWizardController.java

/**
 * @see org.springframework.web.servlet.mvc.Controller#handleRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */// w  w w  . ja  v a  2 s .  c  om
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String filterId = request.getParameter("filterId");
    String currValue = request.getParameter("currValue");
    FilterDTO filterDTO = FilterUtils.getFilterById(filterMapWrapper.getFilters(), filterId);
    String viewName = filterDTO.getWizardView();
    ModelAndView mav = new ModelAndView(viewName);
    mav.addObject("messageSource", messageSource);

    if (logger.isDebugEnabled()) {
        logger.debug("filter id:" + filterId);
        logger.debug("current value:" + currValue);
        logger.debug("wizard view name:" + viewName);
    }

    //check for bounding box filter
    if (filterId.equals(boundingBoxFilter.getId()) && StringUtils.isNotEmpty(currValue)) {
        LatLongBoundingBox llbb = BoundingBoxFilterHelper.getLatLongBoundingBox(currValue);
        if (llbb != null)
            mav.addObject("boundingBox", llbb);
    }

    //check for classification filter
    if (filterId.equals(classificationFilter.getId())) {
        DataProviderDTO dataProvider = dataResourceManager.getNubDataProvider();
        List<BriefTaxonConceptDTO> concepts = null;
        if (StringUtils.isNotEmpty(currValue)) {
            concepts = taxonomyManager.getClassificationFor(currValue, false, null, true);
            List<BriefTaxonConceptDTO> childConcepts = taxonomyManager.getChildConceptsFor(currValue, true);
            BriefTaxonConceptDTO selectedConcept = taxonomyManager.getBriefTaxonConceptFor(currValue);
            taxonConceptUtils.organiseUnconfirmedNames(request, selectedConcept, concepts, childConcepts);
            mav.addObject("selectedConcept", selectedConcept);
        } else {
            // we always use the nub resource 
            concepts = taxonomyManager.getRootTaxonConceptsForTaxonomy(null, "1");
        }
        if (dataProvider != null)
            mav.addObject("dataProvider", dataProvider);
        if (concepts != null)
            mav.addObject("concepts", concepts);
    }

    //check for dataResource filter
    if (filterId.equals(dataResourceIdFilter.getId())) {
        List<KeyValueDTO> dataProviderList = dataResourceManager.getDataProviderList();
        mav.addObject("dataProviders", dataProviderList);
        List<KeyValueDTO> resourceNetworkList = dataResourceManager.getResourceNetworkList();
        mav.addObject("networks", resourceNetworkList);
    }

    //check for geoRegion filter
    if (filterId.equals(geoRegionFilter.getId())) {
        List<KeyValueDTO> countryList = geospatialManager.getCountryList();
        mav.addObject("countries", countryList);
    }

    //check for occurrence date filter
    if (filterId.equals(occurrenceDateFilter.getId())) {
        Date today = new Date(System.currentTimeMillis());
        mav.addObject("today", today);
        Date lastWeek = DateUtils.addDays(today, -6);
        mav.addObject("lastWeek", lastWeek);
        Date oneMonthAgo = DateUtils.addMonths(today, -1);
        mav.addObject("oneMonthAgo", oneMonthAgo);
        Date sixMonthsAgo = DateUtils.addMonths(today, -5);
        mav.addObject("sixMonthsAgo", sixMonthsAgo);
        Date oneYearAgo = DateUtils.addYears(today, -1);
        mav.addObject("oneYearAgo", oneYearAgo);
        Date fiveYearsAgo = DateUtils.addYears(today, -5);
        mav.addObject("fiveYearsAgo", fiveYearsAgo);
        Date tenYearsAgo = DateUtils.addYears(today, -10);
        mav.addObject("tenYearsAgo", tenYearsAgo);
    }

    //check for year range filter
    if (filterId.equals(yearRangeFilter.getId())) {
        Date today = new Date(System.currentTimeMillis());
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(today);
        int thisYear = calendar.get(Calendar.YEAR);
        mav.addObject("thisYear", thisYear);
    }

    mav.addObject("filterId", filterId);
    return mav;
}

From source file:org.jumpmind.symmetric.service.impl.ClusterService.java

public void aquireInfiniteLock(String action) {
    int tries = 600;
    Date futureTime = DateUtils.addYears(new Date(), 100);
    while (tries > 0) {
        if (!lockCluster(action, new Date(), futureTime, Lock.STOPPED)) {
            AppUtils.sleep(50);// w w w  .j av a  2  s.  co m
            tries--;
        } else {
            tries = 0;
        }
    }
}

From source file:org.kuali.kfs.module.tem.batch.service.impl.PerDiemLoadServiceImpl.java

/**
 * This method...//from w w w .j a  va 2 s  . co m
 * @param perDiem
 * @return
 */
protected Date buildDate(PerDiemForLoad perDiem, String seasonDateAsString) {
    int effectiveYear = this.getEffectiveYear(perDiem);

    Date effectiveDate = perDiem.getEffectiveFromDate();

    Date seasonDate = this.getDateFromString(seasonDateAsString, effectiveYear);
    int difference = this.getDateTimeService().dateDiff(effectiveDate, seasonDate, true);
    if (difference <= 0) {
        DateUtils.addYears(seasonDate, 1);
    }
    return seasonDate;
}

From source file:org.motechproject.server.util.DateUtilTest.java

@Test
public void isNotSameYear() {
    assertFalse(dateUtil.isSameYear(new Date(), DateUtils.addYears(new Date(), -1)));
}

From source file:org.openbravo.test.costing.TestCosting.java

/********************************************** Specific methods for tests **********************************************/

// Create a new product cloning costing Product 1
private Product cloneProduct(int num, String productType, BigDecimal purchasePrice, BigDecimal salesPrice,
        BigDecimal cost, String costType, int year, String currencyId, List<String> productIdList,
        List<BigDecimal> quantityList) {
    try {//from   w  ww . j  ava2  s . c o  m
        Product product = OBDal.getInstance().get(Product.class, PRODUCT_ID);
        Product productClone = (Product) DalUtil.copy(product, false);
        setGeneralData(productClone);

        productClone.setSearchKey("costingProduct" + num);
        productClone.setName("costing Product " + num);
        productClone.setMaterialMgmtMaterialTransactionList(null);
        productClone.setProductType(productType);
        OBDal.getInstance().save(productClone);

        if (productIdList.isEmpty()) {

            OBCriteria<ProductPrice> criteria = OBDal.getInstance().createCriteria(ProductPrice.class);
            criteria.add(Restrictions.eq(ProductPrice.PROPERTY_PRODUCT, product));
            criteria.addOrderBy(ProductPrice.PROPERTY_CREATIONDATE, true);
            int i = 0;
            for (ProductPrice productPrice : criteria.list()) {
                ProductPrice productPriceClone = (ProductPrice) DalUtil.copy(productPrice, false);
                setGeneralData(productPriceClone);
                if (i % 2 == 0) {
                    if (currencyId.equals(CURRENCY2_ID))
                        productPriceClone
                                .setPriceListVersion(OBDal.getInstance().get(Product.class, LANDEDCOSTTYPE3_ID)
                                        .getPricingProductPriceList().get(0).getPriceListVersion());
                    productPriceClone.setStandardPrice(purchasePrice);
                    productPriceClone.setListPrice(purchasePrice);
                } else {
                    productPriceClone.setStandardPrice(salesPrice);
                    productPriceClone.setListPrice(salesPrice);
                }
                productPriceClone.setProduct(productClone);
                productClone.getPricingProductPriceList().add(productPriceClone);
                i++;
            }

            if (cost != null) {
                Costing productCosting = OBProvider.getInstance().get(Costing.class);
                setGeneralData(productCosting);
                if (year != 0)
                    productCosting.setStartingDate(DateUtils.addYears(product.getPricingProductPriceList()
                            .get(0).getPriceListVersion().getValidFromDate(), year));
                else
                    productCosting.setStartingDate(today);
                Calendar calendar = Calendar.getInstance();
                calendar.set(9999, 11, 31);
                productCosting.setEndingDate(calendar.getTime());
                productCosting.setManual(true);
                productCosting.setCostType(costType);
                productCosting.setCost(cost);
                productCosting.setCurrency(OBDal.getInstance().get(Currency.class, CURRENCY1_ID));
                productCosting.setWarehouse(OBDal.getInstance().get(Warehouse.class, WAREHOUSE1_ID));
                productCosting.setProduct(productClone);
                productClone.getMaterialMgmtCostingList().add(productCosting);
            }
        }

        else {
            productClone.setBillOfMaterials(true);
            int i = 0;
            for (String productBOMId : productIdList) {
                ProductBOM productBOMClone = OBProvider.getInstance().get(ProductBOM.class);
                setGeneralData(productBOMClone);
                productBOMClone.setLineNo(new Long((i + 1) * 10));
                productBOMClone.setProduct(productClone);
                productBOMClone.setBOMProduct(OBDal.getInstance().get(Product.class, productBOMId));
                productBOMClone.setBOMQuantity(quantityList.get(i));
                i++;

                OBDal.getInstance().save(productBOMClone);
                OBDal.getInstance().flush();
                OBDal.getInstance().refresh(productBOMClone);
            }
            OBDal.getInstance().save(productClone);
            OBDal.getInstance().flush();
            OBDal.getInstance().refresh(productClone);

            verifyBOM(productClone.getId());
            productClone.setBOMVerified(true);
        }

        OBDal.getInstance().save(productClone);
        OBDal.getInstance().flush();
        OBDal.getInstance().refresh(productClone);

        OBCriteria<ProductAccounts> criteria = OBDal.getInstance().createCriteria(ProductAccounts.class);
        criteria.add(Restrictions.eq(ProductAccounts.PROPERTY_PRODUCT, product));
        criteria.add(Restrictions.isNotNull(ProductAccounts.PROPERTY_INVOICEPRICEVARIANCE));
        productClone.getProductAccountsList().get(0)
                .setInvoicePriceVariance(criteria.list().get(0).getInvoicePriceVariance());

        OBDal.getInstance().save(productClone);
        OBDal.getInstance().flush();
        OBDal.getInstance().refresh(productClone);

        return productClone;
    } catch (Exception e) {
        throw new OBException(e);
    }
}