Example usage for org.apache.commons.httpclient.util DateUtil formatDate

List of usage examples for org.apache.commons.httpclient.util DateUtil formatDate

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.util DateUtil formatDate.

Prototype

public static String formatDate(Date paramDate) 

Source Link

Usage

From source file:jp.co.opentone.bsol.linkbinder.view.logo.ProjectLogoManagerTest.java

/**
 * projectId:??ifModifiedSince: + 1//from w w  w  .j av  a 2s  . c  o m
 */
@Test
public void testIsModified7() {
    String projectId = "test-project";

    String testFile = MockSystemConfig.CONFIG_PROJECT_LOGO_DIR + "/" + projectId + ".png";
    File f = new File(testFile);
    if (!f.exists()) {
        fail("?[" + testFile + "] ????????");
        return;
    }

    MockSystemConfig.CONFIG_PROJECT_LOGO_DEFAULT = "test-default.png";
    String testFile2 = MockSystemConfig.CONFIG_PROJECT_LOGO_DIR + "/"
            + MockSystemConfig.CONFIG_PROJECT_LOGO_DEFAULT;
    File f2 = new File(testFile2);
    if (!f2.exists()) {
        fail("?[" + testFile2 + "] ????????");
        return;
    }

    String ifModifiedSince = DateUtil.formatDate(new Date(f.lastModified() + 1000));
    assertTrue(projectLogoManager.isModified(projectId, ifModifiedSince));
}

From source file:jp.co.opentone.bsol.linkbinder.view.logo.ProjectLogoManagerTest.java

/**
 * projectId:??ifModifiedSince: - 1/*from   ww  w  .ja  v a 2  s .c  o  m*/
 */
@Test
public void testIsModified8() {
    String projectId = "test-project";

    String testFile = MockSystemConfig.CONFIG_PROJECT_LOGO_DIR + "/" + projectId + ".png";
    File f = new File(testFile);
    if (!f.exists()) {
        fail("?[" + testFile + "] ????????");
        return;
    }

    MockSystemConfig.CONFIG_PROJECT_LOGO_DEFAULT = "test-default.png";
    String testFile2 = MockSystemConfig.CONFIG_PROJECT_LOGO_DIR + "/"
            + MockSystemConfig.CONFIG_PROJECT_LOGO_DEFAULT;
    File f2 = new File(testFile2);
    if (!f2.exists()) {
        fail("?[" + testFile2 + "] ????????");
        return;
    }

    String ifModifiedSince = DateUtil.formatDate(new Date(f.lastModified() - 1000));
    assertTrue(projectLogoManager.isModified(projectId, ifModifiedSince));
}

From source file:jp.co.opentone.bsol.linkbinder.view.logo.ProjectLogoManagerTest.java

/**
 * ?????ifModifiedSince:?//from w  w  w .j  a  v a 2  s.c  om
 */
@Test
public void testIsModified11() {
    String projectId = "not_exist_project";
    String ifModifiedSince = DateUtil.formatDate(new Date(System.currentTimeMillis()));
    assertTrue(projectLogoManager.isModified(projectId, ifModifiedSince));
}

From source file:com.prashsoft.javakiva.Loan.java

/**
 * To String/*from   ww w.  j  a va2 s. c  o m*/
 * 
 * @return toString Of Attributes
 * @see String
 */
@Override
public String toString() {
    return "" + " Activity: " + (activity == null ? "" : activity) + "\n" + " Basket Amount: "
            + (basketAmount == null ? "" : basketAmount) + "\n" + " Funded Amount: "
            + (fundedAmount == null ? "" : fundedAmount) + "\n" + " Id: " + id + "\n" + " Image: "
            + (image == null ? "" : image.getImageUrl()) + "\n" + " Loan Amount: "
            + (loanAmount == null ? "" : loanAmount) + "\n" + " Loan Description: "
            + (description == null ? "" : description.getTexts().get("en")) + "\n" + "Location: " + "\n"
            + (location == null ? ""
                    : ("Country Code: " + location.getCountryCode() + "\n" + "Country: " + location.getCountry()
                            + "\n" + "Town: " + location.getTown() + "\n"
                            + (location.getGeo() == null ? ""
                                    : ("Geo Level: " + location.getGeo().getLevel() + "\n" + "Geo Pairs: "
                                            + location.getGeo().getPairs() + "\n" + "Geo Type: "
                                            + location.getGeo().getType() + "\n"))))
            + "\n" + " Name: " + (name == null ? "" : name) + "\n" + " Paid Amount: "
            + (paidAmount == null ? "" : paidAmount) + "\n" + " Posted Date: "
            + (postedDate == null ? "" : DateUtil.formatDate(postedDate)) + "\n" + " Funded Date: "
            + (fundedDate == null ? "" : DateUtil.formatDate(fundedDate)) + "\n" + " Raised Amount: "
            + (raisedAmount == null ? "" : raisedAmount) + "\n" + " Sector: " + (sector == null ? "" : sector)
            + "\n" + " Status: " + (status == null ? "" : status) + "\n" + " Partner Id: " + partnerId + "\n"
            + " Use: " + (use == null ? "" : use) + "\n" + " Borrowers: " + "\n"
            + (borrowers == null ? ""
                    : ("Borrower Id: " + ((Borrower) borrowers.get(0)).getId() + "\n" + "Borrower First Name: "
                            + ((Borrower) borrowers.get(0)).getFirstName() + "\n" + "Borrower Last Name: "
                            + ((Borrower) borrowers.get(0)).getLastName() + "\n" + "Borrower Gender: "
                            + ((Borrower) borrowers.get(0)).getGender() + "\n" + "Borrower Pictured: "
                            + ((Borrower) borrowers.get(0)).getPictured()))
            + "\n" + "Terms: " + "\n"
            + (terms == null ? ""
                    : "Disbursal Amount: " + terms.getDisbursalAmount() + "\n" + "Disbursal Currency: "
                            + terms.getDisbursalCurrency() + "\n" + " Local Payments: Due Date: "
                            + (terms.getLocalPayments().get(0)).getDueDate() + "\n"
                            + " Local Payments: Amount: " + (terms.getLocalPayments().get(0)).getAmount() + "\n"
                            + " Scheduled Payments: Due Date: "
                            + (terms.getScheduledPayments().get(0)).getDueDate() + "\n"
                            + " Scheduled Payments: Amount: "
                            + (terms.getScheduledPayments().get(0)).getAmount() + "\n" + "Disbursal Date: "
                            + terms.getDisbursalDate() + "\n" + "Loan Amount: " + terms.getLoanAmount() + "\n"
                            + "Loss Liability: Non Payment: " + terms.getLossLiability().getNonpayment() + "\n"
                            + "Loss Liability: Currency Exchange: "
                            + terms.getLossLiability().getCurrencyExchange())

            + "\n" + " Payments: " + "\n"
            + (payments == null ? ""
                    : ("Payment Id: " + ((Payment) payments.get(0)).getPaymentId() + "\n" + "Payment Amount: "
                            + ((Payment) payments.get(0)).getAmount() + "\n" + "Payment Local Amount: "
                            + ((Payment) payments.get(0)).getLocalAmount() + "\n" + "Payment Processed Date: "
                            + ((Payment) payments.get(0)).getProcessedDate() + "\n"
                            + "Payment Settlement Date: " + ((Payment) payments.get(0)).getSettlementDate()
                            + "\n" + "Payment Comment: " + ((Payment) payments.get(0)).getComment() + "\n"
                            + "Payment Rounded Local Amount: "
                            + ((Payment) payments.get(0)).getRoundedLocalAmount()))
            + "\n" + "Posted Date: " + postedDate + "\n" + "Funded Date: " + fundedDate + "\n"
            + ((journalTotals == null) ? ""
                    : ("Journal Totals: Entries: " + journalTotals.getEntries() + "\n"
                            + "Journal Totals: Bulk Entries: " + journalTotals.getBulkEntries()));
}

From source file:com.zimbra.cs.mailbox.calendar.ZRecur.java

public List<Date> expandRecurrenceOverRange(ParsedDateTime dtStart, long rangeStart, long rangeEnd)
        throws ServiceException {
    List<Date> toRet = new LinkedList<Date>();

    Date rangeStartDate = new Date(rangeStart);
    // subtract 1000ms (1sec) because the code in the method treats
    // end time as inclusive while the rangeEnd input argument is
    // exclusive value
    Date rangeEndDate = new Date(rangeEnd - 1000);
    Date dtStartDate = new Date(dtStart.getUtcTime());

    Date earliestDate;//from www  .ja va2 s .  c  o  m
    if (dtStartDate.after(rangeStartDate))
        earliestDate = dtStartDate;
    else
        earliestDate = rangeStartDate;

    if (mUntil != null) {
        Date until = mUntil.getDateForRecurUntil(dtStart.getTimeZone());
        if (until.before(rangeEndDate))
            rangeEndDate = until;
    }

    // Set limit of expansion count.
    int maxInstancesFromConfig = sExpansionLimits.maxInstances;
    int maxInstancesExpanded;
    if (maxInstancesFromConfig <= 0)
        maxInstancesExpanded = mCount;
    else if (mCount <= 0)
        maxInstancesExpanded = maxInstancesFromConfig;
    else
        maxInstancesExpanded = Math.min(mCount, maxInstancesFromConfig);
    int numInstancesExpanded = 1; // initially 1 rather than 0 because DTSTART is always included

    // Set hard limit of expansion time range.  (bug 21989)
    ParsedDateTime earliestDateTime = ParsedDateTime.fromUTCTime(earliestDate.getTime());
    Date hardEndDate = getEstimatedEndTime(earliestDateTime);
    if (hardEndDate.before(rangeEndDate))
        rangeEndDate = hardEndDate;

    if (rangeEndDate.before(earliestDate)) {
        ZimbraLog.calendar.debug(
                "Expanding recurrence over range where range end %s is before earliest date %s",
                DateUtil.formatDate(rangeEndDate), DateUtil.formatDate(earliestDate));
        return toRet;
    }

    GregorianCalendar cur = dtStart.getCalendarCopy();
    int baseMonthDay = cur.get(Calendar.DAY_OF_MONTH);
    boolean baseIsLeapDay = ((baseMonthDay == 29) && (cur.get(Calendar.MONTH) == Calendar.FEBRUARY));

    // until we hit rangeEnd, or we've SAVED count entries:
    //
    //     gather each set {
    //
    //
    //
    //        curDate forward one INTERVAL
    //
    //     }
    //     check Set against BYSETPOS & ranges & count
    //

    int interval = mInterval;
    if (interval <= 0)
        interval = 1;

    // DTSTART is always part of the expansion, as long as it falls within
    // the range.
    if (!dtStartDate.before(earliestDate) && !dtStartDate.after(rangeEndDate))
        toRet.add(dtStartDate);

    int numConsecutiveIterationsWithoutMatchingInstance = 0;
    boolean pastHardEndTime = false;
    long numIterations = 0; // track how many times we looped
    while (!pastHardEndTime && (maxInstancesExpanded <= 0 || numInstancesExpanded < maxInstancesExpanded)) {
        numIterations++;
        boolean curIsAtOrAfterEarliestDate = !cur.getTime().before(earliestDate);
        boolean curIsAfterEndDate = cur.getTime().after(rangeEndDate);
        List<Calendar> addList = new LinkedList<Calendar>();

        switch (mFreq) {
        case HOURLY:
            /*
             * BYSECOND - for each listed second
             * BYMINUTE - for each listed minute in hour
             * BYHOUR - match iff in hour list
             * BYDAY - for each day listed
             * BYMONTHDAY - only those monthdays
             * BYYEARDAY - only those yeardays
             * BYMONTH - only those months
             */
            if (!checkMonthList(cur))
                continue;

            if (!checkYearDayList(cur))
                continue;

            if (!checkMonthDayList(cur))
                continue;

            if (!checkDayList(cur))
                continue;

            if (!checkHourList(cur))
                continue;

            addList.add((Calendar) (cur.clone()));

            cur.add(Calendar.HOUR_OF_DAY, interval);

            addList = expandHourList(addList);
            addList = expandMinuteList(addList);
            addList = expandSecondList(addList);

            break;
        case DAILY:
            /*
             * BYSECOND - for each listed second in day
             * BYMINUTE - for each listed minute in day
             * BYHOUR - for each listed hour in day
             * BYDAY - no ordinal allowed, match iff in day list
             * BYMONTHDAY - only that day
             * BYYEARDAY - only that day
             * BYWEEKNO -- YEARLY ONLY
             * BYMONTH - only that month
             *
             * while (count check & until check & rangeEnd check) {
             *    if (byMonth && !month matches)
             *      curDay = set MONTH to matching month
             *
             *    if (byYearDay && !yearday matches)
             *      curDay = set DAY to next matching yearday
             *
             *    if (byMonthday && !monthday matches)
             *      curDay = skip to next matching monthday
             *
             *    if (byDay && !day in list)
             *      curDay = skip to next mathcing byDay
             *
             *    if (!byHour or FOR EACH HOUR IN HOURLIST)
             *      if (!byMinute or FOR EACH MINUTE IN MINLIST)
             *        if (!bySecond or FOR EACH SECOND IN LIST)
             *          ----add to list---
             *
             *     check against BYSETPOS
             *
             *     curDay+=1 day
             * }
             *
             */

            if (!checkMonthList(cur))
                continue;

            if (!checkYearDayList(cur))
                continue;

            if (!checkMonthDayList(cur))
                continue;

            if (!checkDayList(cur))
                continue;

            addList.add((Calendar) (cur.clone()));

            cur.add(Calendar.DAY_OF_YEAR, interval);

            addList = expandHourList(addList);
            addList = expandMinuteList(addList);
            addList = expandSecondList(addList);
            break;
        case WEEKLY:
            /*
             * BYSECOND - for every listed second
             * BYMINUTE - for every listed minute
             * BYHOUR - for every listed hour
             * BYDAY - for every listed day
             * BYMONTHDAY - MAYBE once a month
             * BYYEARDAY - MAYBE once a year
             * BYMONTH - iff month matches
             *
             *  for each (INTERVAL)WEEK{
             *    if (byMonth && !month matches)
             *      curDay = set MONTH to DtStart in next matching month
             *
             *    if (byYearDay && !yearday matches)
             *      curDay = set date to next matching yearday
             *
             *    if (byMonthDay && !monthday matches)
             *      curDay = skip to next matching monthday
             *
             *    if (!byDay or FOREACH day in list)
             *      if (!byHour or FOREACH hour in list)
             *        if (!byMinute or FOREACH minute in list)
             *          if (!bySecond or FOREACH second in list)
             *            ----add to list----
             *
             *    check against BYSETPOS
             *
             *    curDay += 1 week
             * } while (count check & until check & rangeEnd check)
             *
             */
            if (!checkMonthList(cur))
                continue;

            if (!checkYearDayList(cur))
                continue;

            if (!checkMonthDayList(cur))
                continue;

            addList.add((Calendar) (cur.clone()));

            cur.add(Calendar.WEEK_OF_YEAR, interval);

            addList = expandDayListForWeekly(addList);
            addList = expandHourList(addList);
            addList = expandMinuteList(addList);
            addList = expandSecondList(addList);
            break;
        case MONTHLY:
            if (!checkMonthList(cur))
                continue;

            if (!checkYearDayList(cur))
                continue;

            addList.add((Calendar) (cur.clone()));

            cur.set(Calendar.DAY_OF_MONTH, 1);
            cur.add(Calendar.MONTH, interval);
            int daysInMonth = cur.getActualMaximum(Calendar.DAY_OF_MONTH);
            cur.set(Calendar.DAY_OF_MONTH, Math.min(baseMonthDay, daysInMonth));

            addList = expandMonthDayList(addList);
            addList = expandDayListForMonthlyYearly(addList);
            addList = expandHourList(addList);
            addList = expandMinuteList(addList);
            addList = expandSecondList(addList);

            break;
        case YEARLY:
            /*
             * BYSECOND
             * BYMINUTE
             * BYHOUR
             * BYDAY
             * BYMONTHDAY
             * BYYEARDAY
             * BYWEEKNO - specified week
             * BYMONTH - once
             */
            if (baseIsLeapDay) {
                // previously adding a year to a leap day will have rounded down to the 28th.
                // If this happened, we need to be sure that if we are back in a leap
                // year, it is back at 29th
                cur.set(Calendar.DAY_OF_MONTH, cur.getActualMaximum(Calendar.DAY_OF_MONTH));
            }
            if (ignoreYearForRecurrenceExpansion(cur, baseIsLeapDay)) {
                cur.add(Calendar.YEAR, interval);
                break;
            }
            addList.add((Calendar) (cur.clone()));

            cur.add(Calendar.YEAR, interval);

            addList = expandMonthList(addList);
            addList = expandYearDayList(addList);

            addList = expandMonthDayList(addList);
            addList = expandDayListForMonthlyYearly(addList);
            addList = expandHourList(addList);
            addList = expandMinuteList(addList);
            addList = expandSecondList(addList);

            break;
        default:
            // MINUTELY and SECONDLY are intentionally not supported for performance reasons.
            return toRet;
        }

        addList = handleSetPos(addList);

        boolean noInstanceFound = true;
        boolean foundInstancePastEndDate = false;
        // add all the ones that match!
        for (Calendar addCal : addList) {
            Date toAdd = addCal.getTime();

            // We already counted DTSTART before the main loop, so don't
            // count it twice.
            if (toAdd.compareTo(dtStartDate) == 0) {
                noInstanceFound = false;
                continue;
            }

            // we still have expanded this instance, even if it isn't in our
            // current date window
            if (toAdd.after(dtStartDate))
                numInstancesExpanded++;

            if (!toAdd.after(rangeEndDate)) {
                if (!toAdd.before(earliestDate)) {
                    toRet.add(toAdd);
                    noInstanceFound = false;
                }
            } else {
                foundInstancePastEndDate = true;
                break;
            }

            if (maxInstancesExpanded > 0 && numInstancesExpanded >= maxInstancesExpanded)
                break;
        }

        // Detect invalid rule.  If the rule was invalid the current iteration, which is for the current
        // frequency interval, would have found no matching instance.  The next iteration will also find
        // no matching instance, and there is no need to keep iterating until we go past the hard end
        // time or COUNT/UNTIL limit.
        //
        // However, we have to make an exception for leap year.  An yearly rule looking for February 29th
        // will find no instance in up to 3 consecutive years before finding Feb 29th in the fourth year.
        //
        // So the invalid rule detection must look for at least 4 consecutive failed iterations.
        if (curIsAtOrAfterEarliestDate) {
            if (noInstanceFound)
                numConsecutiveIterationsWithoutMatchingInstance++;
            else
                numConsecutiveIterationsWithoutMatchingInstance = 0;
            if (numConsecutiveIterationsWithoutMatchingInstance >= 4) {
                ZimbraLog.calendar.warn("Invalid recurrence rule: " + toString());
                return toRet;
            }
        }

        pastHardEndTime = foundInstancePastEndDate || (noInstanceFound && curIsAfterEndDate);
    }

    return toRet;
}

From source file:org.alfresco.services.TextRepoContentGetter.java

public GetTextContentResponse getTextContent(Long nodeId, QName propertyQName, Long modifiedSince)
        throws AuthenticationException, IOException, org.alfresco.httpclient.AuthenticationException {
    StringBuilder url = new StringBuilder(128);
    url.append(GET_CONTENT);//from  ww  w.j av  a 2  s  . com

    StringBuilder args = new StringBuilder(128);
    if (nodeId != null) {
        args.append("?");
        args.append("nodeId");
        args.append("=");
        args.append(nodeId);
    } else {
        throw new NullPointerException("getTextContent(): nodeId cannot be null.");
    }
    if (propertyQName != null) {
        if (args.length() == 0) {
            args.append("?");
        } else {
            args.append("&");
        }
        args.append("propertyQName");
        args.append("=");
        args.append(URLEncoder.encode(propertyQName.toString()));
    }

    url.append(args);

    GetRequest req = new GetRequest(url.toString());

    if (modifiedSince != null) {
        Map<String, String> headers = new HashMap<String, String>(1, 1.0f);
        headers.put("If-Modified-Since", String.valueOf(DateUtil.formatDate(new Date(modifiedSince))));
        req.setHeaders(headers);
    }

    Response response = repoClient.sendRequest(req);

    if (response.getStatus() != HttpServletResponse.SC_NOT_MODIFIED
            && response.getStatus() != HttpServletResponse.SC_NO_CONTENT
            && response.getStatus() != HttpServletResponse.SC_OK) {
        throw new AlfrescoRuntimeException("GetTextContentResponse return status is " + response.getStatus());
    }

    return new GetTextContentResponse(response);
}

From source file:org.alfresco.solr.client.SOLRAPIClient.java

public GetTextContentResponse getTextContent(Long nodeId, QName propertyQName, Long modifiedSince)
        throws AuthenticationException, IOException {
    StringBuilder url = new StringBuilder(128);
    url.append(GET_CONTENT);//from   w ww . j a  v a2s  .c om

    StringBuilder args = new StringBuilder(128);
    if (nodeId != null) {
        args.append("?");
        args.append("nodeId");
        args.append("=");
        args.append(nodeId);
    } else {
        throw new NullPointerException("getTextContent(): nodeId cannot be null.");
    }
    if (propertyQName != null) {
        if (args.length() == 0) {
            args.append("?");
        } else {
            args.append("&");
        }
        args.append("propertyQName");
        args.append("=");
        args.append(URLEncoder.encode(propertyQName.toString()));
    }

    url.append(args);

    GetRequest req = new GetRequest(url.toString());

    if (modifiedSince != null) {
        Map<String, String> headers = new HashMap<String, String>(1, 1.0f);
        headers.put("If-Modified-Since", String.valueOf(DateUtil.formatDate(new Date(modifiedSince))));
        req.setHeaders(headers);
    }

    Response response = repositoryHttpClient.sendRequest(req);

    if (response.getStatus() != Status.STATUS_NOT_MODIFIED && response.getStatus() != Status.STATUS_NO_CONTENT
            && response.getStatus() != Status.STATUS_OK) {
        throw new AlfrescoRuntimeException("GetTextContentResponse return status is " + response.getStatus());
    }

    return new GetTextContentResponse(response);
}

From source file:org.apache.abdera.protocol.client.RequestOptions.java

/**
 * Set the date value of the specified HTTP header
 *///from  w w  w  . ja  v  a2  s.  c o  m
public RequestOptions setDateHeader(String header, Date value) {
    return value != null ? setHeader(header, DateUtil.formatDate(value)) : removeHeaders(header);
}

From source file:org.apache.abdera.protocol.client.RequestOptions.java

/**
 * Similar to setDateHeader but allows for multiple instances of the specified header
 *//*from  w  w w  .j  a  va 2s . c  o m*/
public RequestOptions addDateHeader(String header, Date value) {
    if (value == null)
        return this;
    return addHeader(header, DateUtil.formatDate(value));
}

From source file:org.apache.solr.servlet.CacheHeaderTest.java

protected void doLastModified(String method) throws Exception {
    // We do a first request to get the last modified
    // This must result in a 200 OK response
    HttpMethodBase get = getSelectMethod(method);
    getClient().executeMethod(get);//  w w  w.ja va 2s  .co m
    checkResponseBody(method, get);

    assertEquals("Got no response code 200 in initial request", 200, get.getStatusCode());

    Header head = get.getResponseHeader("Last-Modified");
    assertNotNull("We got no Last-Modified header", head);

    Date lastModified = DateUtil.parseDate(head.getValue());

    // If-Modified-Since tests
    get = getSelectMethod(method);
    get.addRequestHeader("If-Modified-Since", DateUtil.formatDate(new Date()));

    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals("Expected 304 NotModified response with current date", 304, get.getStatusCode());

    get = getSelectMethod(method);
    get.addRequestHeader("If-Modified-Since", DateUtil.formatDate(new Date(lastModified.getTime() - 10000)));
    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals("Expected 200 OK response with If-Modified-Since in the past", 200, get.getStatusCode());

    // If-Unmodified-Since tests
    get = getSelectMethod(method);
    get.addRequestHeader("If-Unmodified-Since", DateUtil.formatDate(new Date(lastModified.getTime() - 10000)));

    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals("Expected 412 Precondition failed with If-Unmodified-Since in the past", 412,
            get.getStatusCode());

    get = getSelectMethod(method);
    get.addRequestHeader("If-Unmodified-Since", DateUtil.formatDate(new Date()));
    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals("Expected 200 OK response with If-Unmodified-Since and current date", 200,
            get.getStatusCode());
}