Example usage for java.util Date before

List of usage examples for java.util Date before

Introduction

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

Prototype

public boolean before(Date when) 

Source Link

Document

Tests if this date is before the specified date.

Usage

From source file:eionet.web.action.VocabularyFolderActionBean.java

/**
 * Validates save concept.//from www. ja va 2 s.c  o  m
 *
 * @throws ServiceException
 *             if an error occurs
 */
@ValidationMethod(on = { "saveConcept" })
public void validateSaveConcept() throws ServiceException {
    if (!isUpdateRight()) {
        addGlobalValidationError("No permission to modify vocabulary");
    }

    VocabularyConcept vc = null;
    if (vocabularyConcept != null) {
        // Validating new concept
        vc = vocabularyConcept;
        editDivId = NEW_CONCEPT_DIV_ID;
    } else {
        // Validating edit concept
        vc = getEditableConcept();
        editDivId = EDIT_DIV_ID_PREFIX + vc.getId();
    }

    if (StringUtils.isEmpty(vc.getIdentifier())) {
        addGlobalValidationError("Vocabulary concept identifier is missing");
    } else {
        if (vocabularyFolder.isNumericConceptIdentifiers()) {
            if (!Util.isNumericID(vc.getIdentifier())) {
                addGlobalValidationError("Vocabulary concept identifier must be numeric value");
            }
        } else {
            if (!Util.isValidIdentifier(vc.getIdentifier())) {
                addGlobalValidationError("Vocabulary concept identifier contains illegal characters (/%?#:\\)");
            }
            if (RESERVED_VOCABULARY_EVENTS.contains(vc.getIdentifier())) {
                addGlobalValidationError(
                        "This vocabulary concept identifier is reserved value and cannot be used");
            }
        }
    }
    if (StringUtils.isEmpty(vc.getLabel())) {
        addGlobalValidationError("Vocabulary concept label is missing");
    }

    // Validate unique identifier
    if (!vocabularyService.isUniqueConceptIdentifier(vc.getIdentifier(), vocabularyFolder.getId(),
            vc.getId())) {
        addGlobalValidationError("Vocabulary concept identifier is not unique");
    }

    //check for dates, they cannot be set to future
    Date today = new Date(System.currentTimeMillis());

    if (vc.getStatusModified() != null && today.before(vc.getStatusModified())) {
        addGlobalValidationError("Status modified date cannot be set to future");
    }

    if (vc.getAcceptedDate() != null && today.before(vc.getAcceptedDate())) {
        addGlobalValidationError("Accepted date cannot be set to future");
    }

    if (vc.getNotAcceptedDate() != null && today.before(vc.getNotAcceptedDate())) {
        addGlobalValidationError("Not accepted date cannot be set to future");
    }

    if (isValidationErrors()) {
        vocabularyFolder = vocabularyService.getVocabularyFolder(vocabularyFolder.getId());
        initFilter();
        vocabularyConcepts = vocabularyService.searchVocabularyConcepts(filter);
        boundElements = vocabularyService.getVocabularyDataElements(vocabularyFolder.getId());
    }
}

From source file:com.dotmarketing.util.ImportExportUtil.java

private boolean validateDate(Date date) {
    java.util.Calendar calendar = java.util.Calendar.getInstance();
    calendar.set(1753, 01, 01);//  w w w  .  j  a v a2 s. co  m
    boolean validated = true;
    if (date != null && date.before(calendar.getTime())) {
        validated = false;
    }
    return validated;

}

From source file:de.tuttas.servlets.DokuServlet.java

private Document createAnwesenheit(Klasse kl, String kopf, Date parsedFrom, Date parsedTo, OutputStream out,
        int filter1Id, int filter2Id) throws ParseException, IOException, DocumentException {
    Document document = new Document();
    /* Basic PDF Creation inside servlet */
    PdfWriter writer = PdfWriter.getInstance(document, out);
    StringBuilder htmlString = new StringBuilder();
    htmlString.append(kopf);/*from   w  w  w . j a  v  a2  s .  c  o m*/
    /* Anwesenheit einfgen */
    TypedQuery<AnwesenheitEintrag> query = em.createNamedQuery("findAnwesenheitbyKlasse",
            AnwesenheitEintrag.class);
    query.setParameter("paramKName", kl.getKNAME());
    query.setParameter("paramFromDate", new java.sql.Date(parsedFrom.getTime()));
    query.setParameter("paramToDate", new java.sql.Date(parsedTo.getTime()));

    Log.d("setze From auf " + new java.sql.Date(parsedFrom.getTime()));
    List<AnwesenheitObjekt> anwesenheit = getData(query);

    /**
     * Termindaten holen
     */
    Termine t1 = null;
    Termine t2 = null;
    if (filter1Id != -1) {
        t1 = em.find(Termine.class, filter1Id);

    }
    if (filter2Id != -1) {
        t2 = em.find(Termine.class, filter2Id);
    }
    List<Termin> termine = null;
    TypedQuery<Termin> tquery = null;
    if (filter1Id != 0) {
        // zwei Filter
        if (filter2Id != 0) {
            tquery = em.createNamedQuery("findAllTermineTwoFilters", Termin.class);
            tquery.setParameter("filter1", t1.getId());
            tquery.setParameter("filter2", t2.getId());
            tquery.setParameter("fromDate", new java.sql.Date(parsedFrom.getTime()));
            tquery.setParameter("toDate", new java.sql.Date(parsedTo.getTime()));
            termine = tquery.getResultList();
        } // nur Filter1
        else {
            tquery = em.createNamedQuery("findAllTermineOneFilter", Termin.class);
            tquery.setParameter("filter1", t1.getId());
            tquery.setParameter("fromDate", new java.sql.Date(parsedFrom.getTime()));
            tquery.setParameter("toDate", new java.sql.Date(parsedTo.getTime()));
            termine = tquery.getResultList();
        }
    } else {
        // nur Filter2
        if (filter2Id != 0) {
            tquery = em.createNamedQuery("findAllTermineOneFilter", Termin.class);
            tquery.setParameter("filter1", t2.getId());
            tquery.setParameter("fromDate", new java.sql.Date(parsedFrom.getTime()));
            tquery.setParameter("toDate", new java.sql.Date(parsedTo.getTime()));
            termine = tquery.getResultList();
        } // kein Filter, Termine so generieren
        else {
            termine = new ArrayList<>();
            Date current = new Date(parsedFrom.getTime());
            parsedTo.setTime(parsedTo.getTime() + 1000);
            while (current.before(parsedTo)) {
                termine.add(new Termin(new Timestamp(current.getTime())));
                Log.d("Erzeuge neuen Termin:" + new Termin(new Timestamp(current.getTime())));
                current.setTime(current.getTime() + 24 * 60 * 60 * 1000);
            }
        }
    }

    Log.d("Result List:" + anwesenheit);
    GregorianCalendar c = (GregorianCalendar) GregorianCalendar.getInstance();
    c.setTime(parsedFrom);

    String tagZeile = "";
    document.open();
    Query q = em.createNamedQuery("findSchuelerEinerBenanntenKlasse");
    q.setParameter("paramNameKlasse", kl.getKNAME());
    List<Schueler> schueler = q.getResultList();
    Date current = new Date(parsedFrom.getTime());
    Log.d("Current=" + current + " TO=" + parsedTo + " From=" + parsedFrom + " Termine=" + termine.size());
    int spalte = 0;

    for (spalte = 0; spalte < termine.size(); spalte++) {
        tagZeile += "<table  align='center' width='100%' style=\"border: 2px solid black; border-collapse: collapse;\">\n";
        tagZeile += ("<tr >\n");
        tagZeile += ("<td width='25%' style=\"font-size: 14;border: 1px solid black;\"><b>Name</b></td>\n");
        // Zeile f.  Tage (Headline)
        Log.d("Spalte ist nun " + spalte);
        int i = 0;
        for (i = 0; i < 7 && spalte + i < termine.size(); i++) {
            current = new Date(termine.get(spalte + i).getDate().getTime());
            c.setTime(current);
            if (c.get(GregorianCalendar.DAY_OF_WEEK) == 1 || c.get(GregorianCalendar.DAY_OF_WEEK) == 7) {
                tagZeile += ("<td align=\"center\" style=\"padding:5px; background-color: #cccccc; font-size: 12;border: 1px solid black;\">"
                        + DatumUtil.getWochentag(c.get(GregorianCalendar.DAY_OF_WEEK)) + "<br></br>"
                        + c.get(GregorianCalendar.DATE) + "." + (c.get(GregorianCalendar.MONTH) + 1) + "."
                        + c.get(GregorianCalendar.YEAR) + "</td>\n");
            } else {
                tagZeile += ("<td align=\"center\" style=\"padding: 5px; font-size: 12;border: 1px solid black;\">"
                        + DatumUtil.getWochentag(c.get(GregorianCalendar.DAY_OF_WEEK)) + "<br></br>"
                        + c.get(GregorianCalendar.DATE) + "." + (c.get(GregorianCalendar.MONTH) + 1) + "."
                        + c.get(GregorianCalendar.YEAR) + "</td>\n");
            }
            Log.d("Spalte " + (i + spalte) + " Datum=" + current);
        }
        Log.d("Head aufgebaut");
        tagZeile += "</tr>\n";

        // Zeile pro Name
        for (Schueler s : schueler) {
            tagZeile += "<tr>\n";
            tagZeile += ("<td width='20%' style=\"padding: 5px;font-size: 12;border: 1px solid black;\"><b>"
                    + s.getVNAME() + " " + s.getNNAME() + "</b></td>\n");
            // Zeile f.  Tage
            //Log.d("Zeile f. Schler " + s.getNNAME());
            for (i = 0; i < 7 && spalte + i < termine.size(); i++) {
                current = new Date(termine.get(spalte + i).getDate().getTime());
                c.setTime(current);
                if (c.get(GregorianCalendar.DAY_OF_WEEK) == 1 || c.get(GregorianCalendar.DAY_OF_WEEK) == 7) {
                    tagZeile += ("<td style=\"background-color:#cccccc;font-size: 11;border: 1px solid black;\">"
                            + findVermerk(s.getId(), current, anwesenheit) + "</td>\n");
                } else {
                    tagZeile += ("<td style=\"font-size: 11;border: 1px solid black;\">"
                            + findVermerk(s.getId(), current, anwesenheit) + "</td>\n");
                }
                Log.d("Zeile f. Schler " + s.getNNAME() + " Datum " + current);
            }
            tagZeile += "</tr>\n";
        }
        Log.d("Rumpf aufgebaut");

        spalte = spalte + i - 1;

        // neue Seite bei 7 Terminen
        if (i == 7) {
            tagZeile += "</table>\n";
            htmlString.append(tagZeile);
            InputStream is = new ByteArrayInputStream(htmlString.toString().getBytes());
            // Bild einfgen
            String url = "http://www.mmbbs.de/fileadmin/template/mmbbs/gfx/mmbbs_logo_druck.gif";
            Image image = Image.getInstance(url);
            image.setAbsolutePosition(45f, 720f);
            image.scalePercent(50f);
            document.add(image);
            XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
            document.newPage();
            Log.d("neue Seite");
            htmlString = new StringBuilder();
            tagZeile = "";
            htmlString.append(kopf);
        }
        Log.d("SPalte ist " + spalte + " Termine=" + termine.size());

    }
    Log.d("Ende der ForSchleife spalte=" + spalte);
    // den Rest der Seite noch drucken
    if (spalte % 7 != 0) {
        tagZeile += "</table>\n";
        htmlString.append(tagZeile);
        Log.d("Rest Seite erzeugen");
        //Log.d("html String =" + htmlString.toString());
        //document.add(new Paragraph("Tutorial to Generate PDF using Servlet"));

        InputStream is = new ByteArrayInputStream(htmlString.toString().getBytes());
        // Bild einfgen
        String url = "http://www.mmbbs.de/fileadmin/template/mmbbs/gfx/mmbbs_logo_druck.gif";
        Image image = Image.getInstance(url);
        image.setAbsolutePosition(45f, 720f);
        image.scalePercent(50f);
        document.add(image);
        Log.d("writer=" + writer + " document=" + document + " is=" + is);
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);

    }

    document.close();
    return document;
}

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;/* w w w  .  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:com.streamreduce.core.service.InventoryServiceImpl.java

private void pullJiraActivity(Connection connection)
        throws ConnectionNotFoundException, InvalidCredentialsException, IOException {
    JiraClient client = (JiraClient) getClient(connection);
    Map<String, InventoryItem> inventoryItemMap = getInventoryItemMap(connection);
    Date lastActivityPoll = connection.getLastActivityPollDate();
    Date lastActivity = lastActivityPoll;

    try {//from   w w  w .  j a va2 s  .c om
        List<Entry> feedEntries = client.getActivity(inventoryItemMap.keySet());
        if (feedEntries == null) {
            return;
        }

        for (Entry entry : feedEntries) {
            // To map project activity in Jira to a Nodeable ProjectHostingInventoryItem, we have
            // to do some magic.  Said magic is below.
            Element activityObject = entry
                    .getFirstChild(new QName("http://activitystrea.ms/spec/1.0/", "object", "activity"));
            String projectKey = client.getProjectKeyOfEntry(activityObject, inventoryItemMap.keySet());

            if (projectKey == null) {
                // If the projectKey is null here, this means we've gotten activity for a project we're monitoring
                // but we were unable to map said activity to the project in question.  This is a known issue and
                // typically only seen in non-hosted Jira environments where people link their Jira project to other
                // Atlassian products but do not use the same key for the Jira project and the project in the other
                // Atlassian application.  (SOBA-1193)  Let's go ahead and log it so we do not forget but this is a
                // known issue and should not become a ZenDesk ticket.
                logger.error("Project key for Jira activity was unable to be found, possibly related to "
                        + "SOBA-1193: " + entry.toString().substring(0, 140));

                // Move on to the next activity entry
                continue;
            }

            InventoryItem inventoryItem = inventoryItemMap.get(projectKey);

            // This can happen if the activity is from a project, or Jira Studio product, not associated with a
            // project in our inventory system.  (A good example of this is wiki changes.  Each Jira Studio project
            // gets its own wiki but you can create new wiki spaces that are not associated with a Jira Studio
            // project and will end up without an inventory item in our system.)
            if (inventoryItem == null) {
                logger.error(
                        "Project with key of " + projectKey + " did not correspond with an inventory item, "
                                + "possibley related to SOBA-1193: " + entry.toString().substring(0, 140));

                // Move on to the next activity entry
                continue;
            }

            Date pubDate = entry.getPublished();

            // Only create messages newer than the last activity poll date
            if (pubDate.before(lastActivityPoll)) {
                continue;
            }

            if (pubDate.after(lastActivity)) {
                lastActivity = pubDate;
            }

            Map<String, Object> activityParts = client.getPartsForActivity(inventoryItem, entry);

            // This can happen for unknown events which we log
            if (activityParts == null) {
                // We have ran into a Jira activity we do not know how to handle. Log the issue with as much
                // detail as possible.
                String entryAsJSON = entry.toString();

                logger.error("Unable to parse Jira activity to create activity message: " + entryAsJSON);

                // Submit a but report so we are aware of it.
                emailService.sendBugReport(Constants.NODEABLE_SUPER_USERNAME,
                        Constants.NODEABLE_SUPER_ACCOUNT_NAME, "Unable to handle Jira activity",
                        "There was a Jira activity that we currently do not handle.", entryAsJSON);

                // Should we create some specialized error message in the stream instead?

                // Move on to the next activity entry
                continue;
            }

            Map<String, Object> eventContext = new HashMap<>();

            eventContext.put("activityPubDate", pubDate);
            eventContext.put("activityTitle", MessageUtils.cleanEntry((String) activityParts.get("title")));
            eventContext.put("activityContent", MessageUtils.cleanEntry((String) activityParts.get("content")));
            eventContext.put("activityHashtags", activityParts.get("hashtags"));
            eventContext.put("payload", JSONUtils.xmlToJSON(entry.toString()).toString());

            // Create the event stream entry
            Event event = eventService.createEvent(EventId.ACTIVITY, inventoryItem, eventContext);

            JiraActivityDetails details = getJiraActivityDetailsFromActivityParts(activityParts);

            messageService.sendAccountMessage(event, inventoryItem, connection, pubDate.getTime(),
                    MessageType.ACTIVITY,
                    activityParts.get("hashtags") != null ? (Set<String>) activityParts.get("hashtags") : null,
                    details);
        }

    } catch (Exception e) {
        logger.error("Unknown exception occurred while pulling Jira activity for connection ["
                + connection.getId() + "]: " + e, e);
    } finally {
        // Update the connection's last polling time
        connection.setLastActivityPollDate(new Date(lastActivity.getTime() + 1));
        try {
            connectionService.updateConnection(connection, true);
        } catch (Exception e) {
            // This is a silent update to only update the last polling time so this should never throw an exception
        }
    }
}

From source file:com.aurel.track.attachment.AttachmentAction.java

public String save() {
    MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) servletRequest;
    HttpServletResponse response = ServletActionContext.getResponse();
    //response.setContentType("text/html");
    if (wrapper.hasErrors()) {
        StringBuffer sb = new StringBuffer();
        Collection errors = wrapper.getErrors();
        Iterator i = errors.iterator();
        while (i.hasNext()) {
            sb.append((String) i.next()).append("</br>");
        }//from www  . j a  va 2s  .  c  o m
        if (!errors.isEmpty()) {
            JSONUtility.encodeJSONFailure(response, sb.toString(), null, false);
            return null;
        }
    }
    if (wrapper.getFiles("theFile") == null) {
        List<LabelValueBean> errors = new ArrayList<LabelValueBean>();
        errors.add(new LabelValueBean(
                getText("common.err.required", new String[] { getText("report.export.manager.upload.file") }),
                "theFile"));
        JSONUtility.encodeJSONErrorsExtJS(response, errors, false);
        return null;
    }
    File[] files = wrapper.getFiles("theFile");
    String[] fileNames = wrapper.getFileNames("theFile");
    if (files == null || files.length == 0 || fileNames == null || fileNames.length == 0) {
        String err = getText("common.err.required",
                new String[] { getText("report.export.manager.upload.file") });
        addFieldError("theFile", err);
        List<LabelValueBean> errors = new ArrayList<LabelValueBean>();
        errors.add(new LabelValueBean(err, "theFile"));
        JSONUtility.encodeJSONErrorsExtJS(response, errors, false);
        return null;
    }

    ApplicationBean applicationBean = (ApplicationBean) application.get(Constants.APPLICATION_BEAN);
    Double maxAttachmentSizeInMb = AttachBL.getMaxAttachmentSizeInMb(applicationBean);
    int MAXFILESIZE = AttachBL.getMaxFileSize(applicationBean);
    int maxDescriptionSize = ApplicationBean.getInstance().getDescriptionMaxLength();
    if (description != null && description.length() > maxDescriptionSize) {
        List<LabelValueBean> errors = new ArrayList<LabelValueBean>();
        errors.add(new LabelValueBean(getText("item.err.tooLong",
                new String[] { getText("common.lbl.description"), Integer.toString(maxDescriptionSize) }),
                "description"));
        JSONUtility.encodeJSONErrorsExtJS(response, errors, false);
        return null;
    }

    Date originalLastModifiedDate = null;
    Date lastModifiedDate = DateTimeUtils.getInstance().parseISODateTime(lastModified);
    TWorkItemBean workItemBean = ItemBL.loadWorkItemSystemAttributes(workItemID);
    if (workItemBean != null) {
        originalLastModifiedDate = workItemBean.getLastEdit();
    }
    List<LabelValueBean> errors = new ArrayList<LabelValueBean>();
    for (int i = 0; i < files.length; i++) {
        if (AttachBL.storeFile(workItemID, personID, description, locale, session, response, files[i],
                fileNames[i], maxAttachmentSizeInMb, MAXFILESIZE, errors, true) == null) {
            break;
        }
    }
    if (!errors.isEmpty()) {
        JSONUtility.encodeJSONErrorsExtJS(response, errors, false);
        return null;
    }

    description = null;

    StringBuilder sb = new StringBuilder();
    sb.append("{");
    JSONUtility.appendBooleanValue(sb, JSONUtility.JSON_FIELDS.SUCCESS, true);
    JSONUtility.appendFieldName(sb, JSONUtility.JSON_FIELDS.DATA).append(":{");
    if (originalLastModifiedDate != null && lastModifiedDate != null) {
        if (!lastModifiedDate.before(originalLastModifiedDate)) {
            workItemBean = ItemBL.loadWorkItemSystemAttributes(workItemID);
            Date lastModified = null;
            if (workItemBean != null) {
                lastModified = workItemBean.getLastEdit();
            }
            JSONUtility.appendStringValue(sb, "lastModified",
                    DateTimeUtils.getInstance().formatISODateTime(lastModified), true);
        }
    }

    sb.append("}}");
    try {
        //Client side ie9 and ie10 does not support application/json when the request is submitted as:    form.submit({... (The callback is not called!),
        //This is why needed to return response as text, despite this is a JSON. For other browsers does not matter!
        JSONUtility.prepareServletResponseJSON(ServletActionContext.getResponse(), false);
        PrintWriter out = ServletActionContext.getResponse().getWriter();
        out.println(sb);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
    return null;
}

From source file:eu.europa.esig.dss.validation.process.subprocess.X509CertificateValidation.java

/**
 * This method checks if the TSL status of the signing certificate.
 *
 * @param conclusion        the conclusion to use to add the result of the check.
 * @param certificateId//ww w .  ja  v a  2s . co m
 * @param certificateXmlDom @return
 */
private boolean checkSigningCertificateTSLStatusAndValidityConstraint(final Conclusion conclusion,
        String certificateId, final XmlDom certificateXmlDom) {

    final String trustedSource = certificateXmlDom
            .getValue("./CertificateChain/ChainCertificate[last()]/Source/text()");
    if (CertificateSourceType.TRUSTED_STORE.name().equals(trustedSource)) {
        return true;
    }

    final Constraint constraint = constraintData
            .getSigningCertificateTSLStatusAndValidityConstraint(contextName);
    if (constraint == null) {
        return true;
    }

    constraint.create(validationDataXmlNode, MessageTag.CTS_ITACBT);

    final Date certificateValidFrom = certificateXmlDom.getTimeValueOrNull("./NotBefore/text()");
    final List<XmlDom> tspList = certificateXmlDom.getElements("./TrustedServiceProvider");
    boolean found = false;
    for (final XmlDom trustedServiceProviderXmlDom : tspList) {

        final String serviceTypeIdentifier = trustedServiceProviderXmlDom.getValue("./TSPServiceType/text()");
        if (!TSLConstant.CA_QC.equals(serviceTypeIdentifier)) {
            continue;
        }
        final Date statusStartDate = trustedServiceProviderXmlDom.getTimeValueOrNull("./StartDate/text()");
        final Date statusEndDate = trustedServiceProviderXmlDom.getTimeValueOrNull("./EndDate/text()");
        if (certificateValidFrom.after(statusStartDate)
                && ((statusEndDate == null) || certificateValidFrom.before(statusEndDate))) {

            final String status = trustedServiceProviderXmlDom == null ? ""
                    : trustedServiceProviderXmlDom.getValue("./Status/text()");
            found = TSLConstant.SERVICE_STATUS_UNDERSUPERVISION.equals(status)
                    || TSLConstant.SERVICE_STATUS_SUPERVISIONINCESSATION.equals(status)
                    || TSLConstant.SERVICE_STATUS_ACCREDITED.equals(status)
                    || TSLConstant.SERVICE_STATUS_UNDERSUPERVISION_119612.equals(status)
                    || TSLConstant.SERVICE_STATUS_SUPERVISIONINCESSATION_119612.equals(status)
                    || TSLConstant.SERVICE_STATUS_ACCREDITED_119612.equals(status);
            if (found) {
                break;
            }
        }
    }

    constraint.setValue(found);
    constraint.setIndications(Indication.INDETERMINATE, SubIndication.TRY_LATER, MessageTag.CTS_ITACBT_ANS);
    constraint.setAttribute(AttributeValue.CERTIFICATE_ID, certificateId);
    constraint.setConclusionReceiver(conclusion);

    return constraint.check();
}

From source file:ch.entwine.weblounge.test.harness.content.CacheTest.java

/**
 * Test if the cache is returning proper header to enable caching on the
 * client side, such as <code>Last-Modified</code>, <code>Expires</code> or
 * <code>ETag</code>./*www . java2 s  .c o  m*/
 * 
 * @param serverUrl
 *          the server url
 * @throws Exception
 *           if the test fails
 */
private void testCacheHeaders(String serverUrl) throws Exception {
    logger.info("Preparing test of response caching");

    DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
    df.setTimeZone(TimeZone.getTimeZone("GMT"));

    // Prepare the request
    logger.info("Testing response cache");

    String requestUrl = UrlUtils.concat(serverUrl, contentTestPage, language.getIdentifier());

    logger.info("Sending request to the {} version of {}", language.getLocale().getDisplayName(), requestUrl);
    HttpGet request = new HttpGet(requestUrl);
    request.addHeader("X-Cache-Debug", "yes");
    String[][] params = new String[][] { { "language", language.getIdentifier() } };

    // Send and the request and examine the response. The first request might
    // not come out of the cache
    logger.debug("Sending request to {}", request.getURI());
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, request, params);
        int statusCode = response.getStatusLine().getStatusCode();
        boolean okOrNotModified = statusCode == HttpServletResponse.SC_OK
                || statusCode == HttpServletResponse.SC_NOT_MODIFIED;
        assertTrue(okOrNotModified);

        // Get the ETag header
        assertNotNull(response.getHeaders("ETag"));
        assertEquals(1, response.getHeaders("ETag").length);
        String eTag = response.getHeaders("ETag")[0].getValue();

        // Get the Expires header
        assertNotNull(response.getHeaders("Expires"));
        assertEquals(1, response.getHeaders("Expires").length);
        Date expires = df.parse(response.getHeaders("Expires")[0].getValue());

        // Prepare the second request
        response.getEntity().consumeContent();
        httpClient.getConnectionManager().shutdown();

        // Give the cache time to persist the entry
        Thread.sleep(1000);

        httpClient = new DefaultHttpClient();

        request.setHeader("If-None-Match", eTag);
        request.setHeader("If-Modified-Since", df.format(System.currentTimeMillis()));

        response = TestUtils.request(httpClient, request, params);
        assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatusLine().getStatusCode());

        // Get the Expires header
        assertNotNull(response.getHeaders("Expires"));
        assertEquals(1, response.getHeaders("Expires").length);

        // We are explicitly not checking for equality with the previously
        // received value, since on first request, that value is not yet correct

        // Get the ETag header
        assertNotNull(response.getHeaders("ETag"));
        assertEquals(0, response.getHeaders("ETag").length);

        // Test the Cache header
        assertNotNull(response.getHeaders("X-Cache-Key"));
        assertEquals(1, response.getHeaders("X-Cache-Key").length);

        // Test the expires header
        Date newExpires = df.parse(response.getHeaders("Expires")[0].getValue());
        assertTrue(expires.before(newExpires) || expires.equals(newExpires));

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.trial.phonegap.plugin.calendar.CalendarAccessorGoogle.java

/**
 * this method filter the evenList given by parameter . Events whose ends are Before than dateEndBefore and After than dateEndAfter
 * @param eventList/*from w  ww  .  java  2 s  .  c  o m*/
 * @param dateEndBefore 
 * @param dateEndAfter
 * @return A list of events filtered by dateEndBefore and dateEndAfter
 */
private List<Event> filterEventsByEnd(List<Event> eventList, Date dateEndBefore, Date dateEndAfter) {
    Date end = null;
    List<Event> eventsToRemove = new ArrayList<Event>();
    for (Event event : eventList) {
        if (!checkNotNullObject(parseRecurrence(event.getRecurrence())).equals(NOT_SPECIFIED_PARSE_CONSTANT)) {
            // If event it is a recurrence event should not have "When" fields and
            // viceversa
            Log.i(TAG, "entramos en : RECURRENCIA parsear end Recurrente");
            end = DateUtils.stringCalendarDateToDateGTM((String) parseEndRecurrenceDate(event.getRecurrence()),
                    "yyyy-MM-dd HH:mm:ss");
        } else {
            // If event it is not recurrence event should not have recurrence
            // object info and have "When" info instead of that
            end = DateUtils.stringCalendarDateToDateGTM(parseEndDate(event.getWhen()), "yyyy-MM-dd HH:mm:ss");
        }

        //If dateEndAfter is not null eventList is filtered by this date
        if ((dateEndAfter != null) && end.before(dateEndAfter)) {
            Log.i(TAG,
                    "entramos en : REMOVE EVENT "
                            + DateUtils.dateToStringCalendarDate(end, "yyyy-MM-dd HH:mm:ss") + "end before: "
                            + DateUtils.dateToStringCalendarDate(dateEndAfter, "yyyy-MM-dd HH:mm:ss"));
            eventsToRemove.add(event);

        }

        //If the event has not yet deleted, and dateEndBefore is not null eventList is filtered by this date         
        if (!eventsToRemove.contains(event) && (dateEndBefore != null) && end.after(dateEndBefore)) {
            Log.i(TAG,
                    "entramos en : REMOVE EVENT "
                            + DateUtils.dateToStringCalendarDate(end, "yyyy-MM-dd HH:mm:ss") + "end after: "
                            + DateUtils.dateToStringCalendarDate(dateEndBefore, "yyyy-MM-dd HH:mm:ss"));

            eventsToRemove.add(event);
        }
    }

    for (Event event : eventsToRemove) {
        eventList.remove(event);
    }

    return eventList;
}

From source file:edu.mit.mobile.android.locast.data.Sync.java

/**
 * Given a live cursor pointing to a data item and/or a set of contentValues loaded from the network,
 * attempt to sync.//  www  . jav  a  2s  . c  o m
 * Either c or cvNet can be null, but not both.
 * @param c A cursor pointing to the data item. Null is OK here.
 * @param jsonObject JSON object for the item as loaded from the network. null is OK here.
 * @param sync An empty JsonSyncableItem object.
 * @param publicPath TODO
 *
 * @return True if the item has been modified on either end.
 * @throws IOException
 */
private boolean syncItem(Uri toSync, Cursor c, JSONObject jsonObject, JsonSyncableItem sync,
        SyncProgressNotifier syncProgress, String publicPath) throws SyncException, IOException {
    boolean modified = false;
    boolean needToCloseCursor = false;
    boolean toSyncIsIndex = false;
    final SyncMap syncMap = sync.getSyncMap();

    Uri locUri = null;
    final Uri origToSync = toSync;
    ContentValues cvNet = null;

    final Context context = getApplicationContext();
    final ContentResolver cr = context.getContentResolver();
    if (jsonObject != null) {
        if ("http".equals(toSync.getScheme()) || "https".equals(toSync.getScheme())) {
            // we successfully loaded it from the 'net, but toSync is really for local URIs. Erase it.

            toSync = sync.getContentUri();
            if (toSync == null) {
                if (DEBUG) {
                    Log.w(TAG, "cannot get local URI for " + origToSync + ". Skipping...");
                }
                return false;
            }
        }
        try {
            cvNet = JsonSyncableItem.fromJSON(context, null, jsonObject, syncMap);
        } catch (final Exception e) {
            final SyncException se = new SyncException("Problem loading JSON object.");
            se.initCause(e);
            throw se;
        }
    }

    final String contentType = cr.getType(toSync);

    if (c != null) {
        if (contentType.startsWith(CONTENT_TYPE_PREFIX_DIR)) {
            locUri = ContentUris.withAppendedId(toSync, c.getLong(c.getColumnIndex(JsonSyncableItem._ID)))
                    .buildUpon().query(null).build();
            toSyncIsIndex = true;
        } else {
            locUri = toSync;
        }

        // skip any items already sync'd
        if (mLastUpdated.isUpdatedRecently(locUri)) {
            return false;
        }

        final int draftCol = c.getColumnIndex(TaggableItem._DRAFT);
        if (draftCol != -1 && c.getInt(draftCol) != 0) {
            if (DEBUG) {
                Log.d(TAG, locUri + " is marked a draft. Not syncing.");
            }
            return false;
        }

        syncMap.onPreSyncItem(cr, locUri, c);
    } else if (contentType.startsWith(CONTENT_TYPE_PREFIX_DIR)) {
        // strip any query strings
        toSync = toSync.buildUpon().query(null).build();
    }
    //      if (c != null){
    //         MediaProvider.dumpCursorToLog(c, sync.getFullProjection());
    //      }
    // when the PUBLIC_URI is null, that means it's only local
    final int pubUriColumn = (c != null) ? c.getColumnIndex(JsonSyncableItem._PUBLIC_URI) : -1;
    if (c != null && (c.isNull(pubUriColumn) || c.getString(pubUriColumn) == "")) {
        // new content on the local side only. Gotta publish.

        try {
            jsonObject = JsonSyncableItem.toJSON(context, locUri, c, syncMap);
            if (publicPath == null) {
                publicPath = MediaProvider.getPostPath(this, locUri);
            }
            if (DEBUG) {
                Log.d(TAG, "Posting " + locUri + " to " + publicPath);
            }

            // The response from a post to create a new item should be the newly created item,
            // which contains the public ID that we need.
            jsonObject = nc.postJson(publicPath, jsonObject);

            final ContentValues cvUpdate = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap);
            if (cr.update(locUri, cvUpdate, null, null) == 1) {
                // at this point, server and client should be in sync.
                mLastUpdated.markUpdated(locUri);
                if (DEBUG) {
                    Log.i(TAG, "Hooray! " + locUri + " has been posted succesfully.");
                }

            } else {
                Log.e(TAG, "update of " + locUri + " failed");
            }
            modified = true;

        } catch (final Exception e) {
            final SyncException se = new SyncException(getString(R.string.error_sync_no_post));
            se.initCause(e);
            throw se;
        }

        // only on the remote side, so pull it in.
    } else if (c == null && cvNet != null) {
        if (DEBUG) {
            Log.i(TAG, "Only on the remote side, using network-provided values.");
        }
        final String[] params = { cvNet.getAsString(JsonSyncableItem._PUBLIC_URI) };
        c = cr.query(toSync, sync.getFullProjection(), JsonSyncableItem._PUBLIC_URI + "=?", params, null);
        needToCloseCursor = true;

        if (!c.moveToFirst()) {
            locUri = cr.insert(toSync, cvNet);
            modified = true;
        } else {
            locUri = ContentUris.withAppendedId(toSync, c.getLong(c.getColumnIndex(JsonSyncableItem._ID)))
                    .buildUpon().query(null).build();
            syncMap.onPreSyncItem(cr, locUri, c);
        }
    }

    // we've now found data on both sides, so sync them.
    if (!modified && c != null) {

        publicPath = c.getString(c.getColumnIndex(JsonSyncableItem._PUBLIC_URI));

        try {

            if (cvNet == null) {
                try {
                    if (publicPath == null && toSyncIsIndex && !MediaProvider.canSync(locUri)) {

                        // At this point, we've already checked the index and it doesn't contain the item (otherwise it would be in the syncdItems).
                        // If we can't sync individual items, it's possible that the index is paged or the item has been deleted.
                        if (DEBUG) {
                            Log.w(TAG, "Asked to sync " + locUri
                                    + " but item wasn't in server index and cannot sync individual entries. Skipping and hoping it is up to date.");
                        }
                        return false;

                    } else {
                        if (mLastUpdated.isUpdatedRecently(nc.getFullUri(publicPath))) {
                            if (DEBUG) {
                                Log.d(TAG, "already sync'd! " + publicPath);
                            }
                            return false;
                        }
                        if (jsonObject == null) {
                            jsonObject = nc.getObject(publicPath);
                        }
                        cvNet = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap);

                    }
                } catch (final HttpResponseException hre) {
                    if (hre.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                        final SyncItemDeletedException side = new SyncItemDeletedException(locUri);
                        side.initCause(hre);
                        throw side;
                    }
                }
            }
            if (cvNet == null) {
                Log.e(TAG, "got null values from fromJSON() on item " + locUri + ": "
                        + (jsonObject != null ? jsonObject.toString() : "<< no json object >>"));
                return false;
            }
            final Date netLastModified = new Date(cvNet.getAsLong(JsonSyncableItem._MODIFIED_DATE));
            final Date locLastModified = new Date(c.getLong(c.getColumnIndex(JsonSyncableItem._MODIFIED_DATE)));

            if (netLastModified.equals(locLastModified)) {
                // same! yay! We don't need to do anything.
                if (DEBUG) {
                    Log.d("LocastSync", locUri + " doesn't need to sync.");
                }
            } else if (netLastModified.after(locLastModified)) {
                // remote is more up to date, update!
                cr.update(locUri, cvNet, null, null);
                if (DEBUG) {
                    Log.d("LocastSync", cvNet + " is newer than " + locUri);
                }
                modified = true;

            } else if (netLastModified.before(locLastModified)) {
                // local is more up to date, propagate!
                jsonObject = nc.putJson(publicPath, JsonSyncableItem.toJSON(context, locUri, c, syncMap));

                if (DEBUG) {
                    Log.d("LocastSync", cvNet + " is older than " + locUri);
                }
                modified = true;
            }
            mLastUpdated.markUpdated(nc.getFullUri(publicPath));
        } catch (final JSONException e) {
            final SyncException se = new SyncException(
                    "Item sync error for path " + publicPath + ": invalid JSON.");
            se.initCause(e);
            throw se;
        } catch (final NetworkProtocolException e) {
            final SyncException se = new SyncException(
                    "Item sync error for path " + publicPath + ": " + e.getHttpResponseMessage());
            se.initCause(e);
            throw se;
        } finally {
            if (needToCloseCursor) {
                c.close();
                needToCloseCursor = false;
            }
        }
    }

    if (needToCloseCursor) {
        c.close();
    }

    if (locUri == null) {
        throw new RuntimeException("Never got a local URI for a sync'd item.");
    }

    // two calls are made in two different contexts. Which context you use depends on the application.
    syncMap.onPostSyncItem(context, locUri, jsonObject, modified);
    sync.onPostSyncItem(context, locUri, jsonObject, modified);

    mLastUpdated.markUpdated(locUri);

    // needed for things that may have requested a sync with a different URI than what was eventually produced.
    if (origToSync != locUri) {
        mLastUpdated.markUpdated(origToSync);
        cr.notifyChange(origToSync, null);
    }

    return modified;
}