Example usage for java.util Date compareTo

List of usage examples for java.util Date compareTo

Introduction

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

Prototype

public int compareTo(Date anotherDate) 

Source Link

Document

Compares two Dates for ordering.

Usage

From source file:io.fabric8.maven.plugin.AbstractDeployMojo.java

protected Pod getNewestPod(Collection<Pod> pods) {
    if (pods == null || pods.isEmpty()) {
        return null;
    }//from   w w  w .  jav  a2  s  . c o m
    List<Pod> sortedPods = new ArrayList<>(pods);
    Collections.sort(sortedPods, new Comparator<Pod>() {
        @Override
        public int compare(Pod p1, Pod p2) {
            Date t1 = getCreationTimestamp(p1);
            Date t2 = getCreationTimestamp(p2);
            if (t1 != null) {
                if (t2 == null) {
                    return 1;
                } else {
                    return t1.compareTo(t2);
                }
            } else if (t2 == null) {
                return 0;
            }
            return -1;
        }
    });
    return sortedPods.get(sortedPods.size() - 1);
}

From source file:View.DialogoEstadisticas.java

private boolean combrobarIntervalo(String periodo) {
    if (intervalo) {
        String fechaI = null;//from w ww .j  av  a2s.c o  m
        String fechaF = null;
        String periodoI = null;
        String periodoF = null;

        SimpleDateFormat dt1 = new SimpleDateFormat("dd-MM-yyyy");
        StringTokenizer st = new StringTokenizer(periodo, "/");
        while (st.hasMoreTokens()) {
            fechaI = st.nextToken();
            fechaF = st.nextToken();
        }

        st = new StringTokenizer(fechaIntervaloI, "/");
        periodoI = st.nextToken();

        st = new StringTokenizer(fechaIntervaloF, "/");
        while (st.hasMoreTokens()) {
            st.nextToken();
            periodoF = st.nextToken();
        }
        try {
            Date dI = dt1.parse(fechaI);
            Date dF = dt1.parse(fechaF);
            Date dIntevaloI = dt1.parse(periodoI);
            Date dIntevaloF = dt1.parse(periodoF);

            return (dI.after(dIntevaloI) && dF.before(dIntevaloF)) || (dI.compareTo(dIntevaloI) == 0)
                    || (dF.compareTo(dIntevaloF) == 0);
        } catch (ParseException ex) {
            Logger.getLogger(DialogoEstadisticas.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }

    } else {
        return true;
    }
}

From source file:fr.univrouen.poste.web.candidat.MyPosteCandidatureController.java

@RequestMapping(produces = "text/html")
public String list(@ModelAttribute("command") PosteCandidatureSearchCriteria searchCriteria,
        BindingResult bindResult, @RequestParam(value = "page", required = false) Integer page,
        @RequestParam(value = "size", required = false) Integer size,
        @RequestParam(value = "sortFieldName", required = false) String sortFieldName,
        @RequestParam(value = "sortOrder", required = false) String sortOrder,
        @RequestParam(value = "zip", required = false, defaultValue = "off") Boolean zip,
        HttpServletResponse response, HttpServletRequest request, Model uiModel)
        throws IOException, SQLException {

    // uiModel.addAttribute("users", User.findUserEntries(firstResult,
    // sizeNo));/*from w  ww. j  ava2s  .c  om*/

    List<PosteCandidature> postecandidatures = null;

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    String emailAddress = auth.getName();
    User user = User.findUsersByEmailAddress(emailAddress, null, null).getSingleResult();

    boolean isAdmin = auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_ADMIN"));
    boolean isManager = auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_MANAGER"));
    boolean isSuperManager = isManager
            || auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_SUPER_MANAGER"));
    boolean isMembre = auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_MEMBRE"));
    boolean isCandidat = auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_CANDIDAT"));

    if (sortFieldName == null)
        sortFieldName = "o.poste.numEmploi,o.candidat.nom";
    if ("nom".equals(sortFieldName))
        sortFieldName = "candidat.nom";
    if ("email".equals(sortFieldName))
        sortFieldName = "candidat.emailAddress";
    if ("numCandidat".equals(sortFieldName))
        sortFieldName = "candidat.numCandidat";
    if ("managerReviewState".equals(sortFieldName))
        sortFieldName = "managerReview.reviewStatus";

    // pagination only for admin / manager users ...
    if (isAdmin || isManager) {

        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            long nbResultsTotal = PosteCandidature.countPosteCandidatures();
            uiModel.addAttribute("nbResultsTotal", nbResultsTotal);
            float nrOfPages = (float) nbResultsTotal / sizeNo;
            uiModel.addAttribute("maxPages",
                    (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
            postecandidatures = PosteCandidature.findPosteCandidatureEntries(firstResult, sizeNo, sortFieldName,
                    sortOrder);
        } else {
            postecandidatures = PosteCandidature.findAllPosteCandidatures(sortFieldName, sortOrder);
            uiModel.addAttribute("nbResultsTotal", postecandidatures.size());
        }

        uiModel.addAttribute("posteapourvoirs", PosteAPourvoir.findAllPosteAPourvoirNumEplois());
        uiModel.addAttribute("candidats", User.findAllCandidatsIds());
        uiModel.addAttribute("reviewStatusList", Arrays.asList(ReviewStatusTypes.values()));

        String mailAuditionnableEntete = AppliConfig.getCacheTexteEnteteMailCandidatAuditionnable();
        String mailAuditionnablePiedPage = AppliConfig.getCacheTextePiedpageMailCandidatAuditionnable();
        uiModel.addAttribute("mailAuditionnableEntete", mailAuditionnableEntete);
        uiModel.addAttribute("mailAuditionnablePiedPage", mailAuditionnablePiedPage);
    }

    else if (isCandidat) {

        if (!AppliConfig.getCacheCandidatCanSignup()) {

            postecandidatures = new ArrayList<PosteCandidature>(
                    PosteCandidature.findPosteCandidaturesByCandidat(user, null, null).getResultList());

            // restrictions si phase auditionnable
            Date currentTime = new Date();
            if (currentTime.compareTo(AppliConfig.getCacheDateEndCandidat()) > 0
                    && currentTime.compareTo(AppliConfig.getCacheDateEndCandidatActif()) > 0) {
                for (PosteCandidature postecandidature : PosteCandidature
                        .findPosteCandidaturesByCandidat(user, null, null).getResultList()) {
                    if (!postecandidature.getAuditionnable() || postecandidature.getPoste()
                            .getDateEndCandidatAuditionnable() != null
                            && currentTime.compareTo(
                                    postecandidature.getPoste().getDateEndCandidatAuditionnable()) > 0) {
                        postecandidatures.remove(postecandidature);
                    }
                }
            }

        } else {
            postecandidatures = new ArrayList<PosteCandidature>(PosteCandidature
                    .findPosteCandidaturesByCandidatAndByDateEndCandidatGreaterThanAndNoAuditionnableOrByDateEndCandidatAuditionnableGreaterThanAndAuditionnable(
                            user, new Date())
                    .getResultList());
        }

    }

    else if (isMembre) {
        Set<PosteAPourvoir> membresPostes = new HashSet<PosteAPourvoir>(user.getPostes());
        List<PosteAPourvoir> postes = searchCriteria.getPostes();
        if (postes != null && !postes.isEmpty()) {
            membresPostes.retainAll(postes);
            uiModel.addAttribute("finderview", true);
            uiModel.addAttribute("command", searchCriteria);
        }
        if (membresPostes.isEmpty()) {
            membresPostes = new HashSet<PosteAPourvoir>(user.getPostes());
        }
        postecandidatures = PosteCandidature.findPosteCandidaturesRecevableByPostes(membresPostes,
                searchCriteria.getAuditionnable(), sortFieldName, sortOrder).getResultList();
        if (zip) {
            String contentType = "application/zip";
            Calendar cal = Calendar.getInstance();
            Date currentTime = cal.getTime();
            SimpleDateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
            String currentTimeFmt = dateFmt.format(currentTime);
            String baseName = "demat-" + currentTimeFmt + ".zip";
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "attachment; filename=\"" + baseName + "\"");
            zipService.writeZip(postecandidatures, response.getOutputStream());
            logService.logActionFile(LogService.DOWNLOAD_ACTION, postecandidatures, request, currentTime);
            return null;
        }

        for (PosteCandidature pc : postecandidatures) {
            if (pc.getReporters() != null && pc.getReporters().contains(user)) {
                pc.setReporterTag(true);
            }
        }

        uiModel.addAttribute("nbResultsTotal", postecandidatures.size());
        List<PosteAPourvoir> membresPostes2Display = new ArrayList<PosteAPourvoir>(user.getPostes());

        Collections.sort(membresPostes2Display, new Comparator<PosteAPourvoir>() {
            @Override
            public int compare(PosteAPourvoir p1, PosteAPourvoir p2) {
                return p1.getNumEmploi().compareTo(p2.getNumEmploi());
            }
        });

        uiModel.addAttribute("membresPostes", membresPostes2Display);
    }

    uiModel.addAttribute("postecandidatures", postecandidatures);

    uiModel.addAttribute("zip", new Boolean(false));

    uiModel.addAttribute("texteMembreAideCandidatures", AppliConfig.getCacheTexteMembreAideCandidatures());
    uiModel.addAttribute("texteCandidatAideCandidatures", AppliConfig.getCacheTexteCandidatAideCandidatures());

    uiModel.addAttribute("legendColors", ManagerReviewLegendColor.getLegendColors());

    addDateTimeFormatPatterns(uiModel);
    return "postecandidatures/list";
}

From source file:org.libreplan.importers.MPXJProjectFileConverter.java

/**
 * Get a list of {@link CalendarWeekDTO} from a list of ProjectCalendarWeek.
 *
 * @param projectCalendar//from www  .  ja v  a  2 s  . c om
 *            ProjectCalendarWeek with the default data
 * @param workWeeks
 *            List of ProjectCalendarWeek to extract data from.Assume that is ordered
 *            for its DataRange start date.
 * @return List<CalendarDataDTO> List with the CalendarData that we want to import.
 */
private static List<CalendarWeekDTO> getCalendarWeekDTOs(ProjectCalendar projectCalendar,
        List<ProjectCalendarWeek> workWeeks) {

    List<CalendarWeekDTO> calendarDataDTOs = new ArrayList<>();

    Date startCalendarDate;
    Date endCalendarDate;

    if (projectCalendar.getDateRange() == null) {
        startCalendarDate = projectCalendar.getParentFile().getProjectProperties().getStartDate();
        endCalendarDate = projectCalendar.getParentFile().getProjectProperties().getFinishDate();

    } else {
        startCalendarDate = projectCalendar.getDateRange().getStart();
        endCalendarDate = projectCalendar.getDateRange().getEnd();

    }

    if (workWeeks.isEmpty()) {
        calendarDataDTOs.add(toCalendarWeekDTO(projectCalendar));
    } else {

        /*
         * TODO
         *  This utility is not currently implemented in MPXJ.
         *  This one is going to represent all the work weeks.
         *  Including the ones with the default value that are in the middle of two.
         */

        Date firsWorkWeekCalendarDate = workWeeks.get(0).getDateRange().getStart();
        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();

        // If the star of the first work week is after the start of the default we have to fill the hole
        if (startCalendarDate.compareTo(firsWorkWeekCalendarDate) < 0) {
            calendar1.setTime(firsWorkWeekCalendarDate);
            calendar1.set(Calendar.DAY_OF_MONTH, -1);
            calendarDataDTOs.add(toCalendarWeekDTO(projectCalendar));
        }

        Date endDate;
        Date nextStartDate;

        int j;
        for (int i = 0; i < workWeeks.size(); i++) {
            endDate = workWeeks.get(i).getDateRange().getEnd();
            calendarDataDTOs.add(toCalendarWeekDTO(workWeeks.get(i)));

            j = i + 1;

            // If is not the last one
            if (j < workWeeks.size()) {
                nextStartDate = workWeeks.get(i + 1).getDateRange().getStart();
                calendar1.setTime(endDate);
                calendar1.set(Calendar.DAY_OF_MONTH, +1);

                // If the end of the current work week is more than one day before the beginning of the next
                if (calendar1.getTime().compareTo(nextStartDate) < 0) {
                    calendar2.setTime(nextStartDate);
                    calendar1.set(Calendar.DAY_OF_MONTH, -1);

                    // Adds a new default calendar week in the hole
                    calendarDataDTOs.add(toCalendarWeekDTO(projectCalendar));
                }
            }
        }

        Date endWorkWeekCalendarDate = workWeeks.get(workWeeks.size()).getDateRange().getEnd();

        // If the end of the last work week is earlier than the end of the default we have to fill the hole
        if (endCalendarDate.compareTo(endWorkWeekCalendarDate) > 0) {
            calendar1.setTime(endWorkWeekCalendarDate);
            calendar1.set(Calendar.DAY_OF_MONTH, +1);
            calendarDataDTOs.add(toCalendarWeekDTO(projectCalendar));
        }

    }

    return calendarDataDTOs;
}

From source file:org.everit.jira.timetracker.plugin.JiraTimetrackerPluginImpl.java

@Override
public String lastEndTime(final List<EveritWorklog> worklogs) throws ParseException {
    if ((worklogs == null) || (worklogs.size() == 0)) {
        return "08:00";
    }//from   ww w .java  2s  .c  om
    String endTime = worklogs.get(0).getEndTime();
    for (int i = 1; i < worklogs.size(); i++) {
        Date first = DateTimeConverterUtil.stringTimeToDateTime(worklogs.get(i - 1).getEndTime());
        Date second = DateTimeConverterUtil.stringTimeToDateTime(worklogs.get(i).getEndTime());
        if (first.compareTo(second) == 1) {
            endTime = worklogs.get(i - 1).getEndTime();
        } else {
            endTime = worklogs.get(i).getEndTime();
        }
    }
    return endTime;
}

From source file:org.apache.falcon.resource.AbstractInstanceManager.java

private List<Instance> sortInstances(List<Instance> instanceSet, String orderBy, String sortOrder) {
    final String order = getValidSortOrder(sortOrder, orderBy);
    if (orderBy.equals("status")) {
        Collections.sort(instanceSet, new Comparator<Instance>() {
            @Override/*from  w  ww .j a v  a2s .  c  o m*/
            public int compare(Instance i1, Instance i2) {
                if (i1.getStatus() == null) {
                    i1.status = InstancesResult.WorkflowStatus.ERROR;
                }
                if (i2.getStatus() == null) {
                    i2.status = InstancesResult.WorkflowStatus.ERROR;
                }
                return (order.equalsIgnoreCase("asc")) ? i1.getStatus().name().compareTo(i2.getStatus().name())
                        : i2.getStatus().name().compareTo(i1.getStatus().name());
            }
        });
    } else if (orderBy.equals("cluster")) {
        Collections.sort(instanceSet, new Comparator<Instance>() {
            @Override
            public int compare(Instance i1, Instance i2) {
                return (order.equalsIgnoreCase("asc")) ? i1.getCluster().compareTo(i2.getCluster())
                        : i2.getCluster().compareTo(i1.getCluster());
            }
        });
    } else if (orderBy.equals("starttime")) {
        Collections.sort(instanceSet, new Comparator<Instance>() {
            @Override
            public int compare(Instance i1, Instance i2) {
                Date start1 = (i1.getStartTime() == null) ? new Date(0) : i1.getStartTime();
                Date start2 = (i2.getStartTime() == null) ? new Date(0) : i2.getStartTime();
                return (order.equalsIgnoreCase("asc")) ? start1.compareTo(start2) : start2.compareTo(start1);
            }
        });
    } else if (orderBy.equals("endtime")) {
        Collections.sort(instanceSet, new Comparator<Instance>() {
            @Override
            public int compare(Instance i1, Instance i2) {
                Date end1 = (i1.getEndTime() == null) ? new Date(0) : i1.getEndTime();
                Date end2 = (i2.getEndTime() == null) ? new Date(0) : i2.getEndTime();
                return (order.equalsIgnoreCase("asc")) ? end1.compareTo(end2) : end2.compareTo(end1);
            }
        });
    } //Default : no sort

    return instanceSet;
}

From source file:org.kuali.ole.select.document.OleAcquisitionsSearchDocument.java

/**
 * This method tests Whether DateTO is Lesser than DateFrom and returns true if Lesser.
 *
 * @return boolean//from w w  w  . j av  a  2s .  c o  m
 * @throws Exception
 */
public boolean isToDateLesserThanFromDate() throws Exception {
    //for adding date
    if (this.getDocumentType() != null && this.getDateFrom() == null) {
        this.dateFrom = getConfigurationService().getPropertyValueAsString("dateFrom");
    }
    boolean isToDateLesserThanFromDate = false;
    if (this.dateFrom != null && this.dateTo != null) {
        DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        Date startDate = formatter.parse(this.dateFrom);
        Date endDate = formatter.parse(this.dateTo);
        if (startDate.compareTo(endDate) > 0) {
            isToDateLesserThanFromDate = true;
        }
    }
    return isToDateLesserThanFromDate;
}

From source file:org.rapidandroid.activity.chart.form.FormDataBroker.java

private JSONGraphData loadNumericLine() {
    Date startDateToUse = getStartDate();

    SQLiteDatabase db = rawDB.getReadableDatabase();

    String fieldcol = RapidSmsDBConstants.FormData.COLUMN_PREFIX + fieldToPlot.getName();
    StringBuilder rawQuery = new StringBuilder();
    rawQuery.append("select rapidandroid_message.time, " + fieldcol);
    rawQuery.append(" from ");
    rawQuery.append(RapidSmsDBConstants.FormData.TABLE_PREFIX + mForm.getPrefix());

    rawQuery.append(" join rapidandroid_message on (");
    rawQuery.append(RapidSmsDBConstants.FormData.TABLE_PREFIX + mForm.getPrefix());
    rawQuery.append(".message_id = rapidandroid_message._id");
    rawQuery.append(") ");

    if (startDateToUse.compareTo(Constants.NULLDATE) != 0 && mEndDate.compareTo(Constants.NULLDATE) != 0) {
        rawQuery.append(" WHERE rapidandroid_message.time > '" + Message.SQLDateFormatter.format(startDateToUse)
                + "' AND rapidandroid_message.time < '" + Message.SQLDateFormatter.format(mEndDate) + "' ");
    }// w w w. ja  v  a  2 s.co m

    rawQuery.append(" order by rapidandroid_message.time ASC");

    // the string value is column 0
    // the magnitude is column 1

    Cursor cr = db.rawQuery(rawQuery.toString(), null);
    int barCount = cr.getCount();

    if (barCount == 0) {
        cr.close();
    } else {
        Date[] xVals = new Date[barCount];
        int[] yVals = new int[barCount];
        cr.moveToFirst();
        int i = 0;
        do {
            try {
                xVals[i] = Message.SQLDateFormatter.parse(cr.getString(0));
                yVals[i] = cr.getInt(1);
            } catch (Exception ex) {

            }
            i++;
        } while (cr.moveToNext());

        // xaxis: { ticks: [0, [Math.PI/2, "\u03c0/2"], [Math.PI, "\u03c0"],
        // [Math.PI * 3/2, "3\u03c0/2"], [Math.PI * 2, "2\u03c0"]]},

        try {
            return new JSONGraphData(prepareDateData(xVals, yVals),
                    loadOptionsForDateGraph(xVals, false, DateDisplayTypes.Daily));
        } catch (Exception ex) {

        } finally {
            if (!cr.isClosed()) {
                cr.close();
            }
        }

    }
    // either there was no data or something bad happened
    return new JSONGraphData(getEmptyData(), new JSONObject());
}

From source file:org.atomserver.core.dbstore.dao.BatchEntriesDAOTest.java

public void testCRUDBatch() throws Exception {
    // COUNT//from  w w  w . j  a va 2  s  .c o m
    BaseServiceDescriptor serviceDescriptor = new BaseServiceDescriptor(workspace);
    int startCount = entriesDAO.getTotalCount(serviceDescriptor);
    log.debug("startCount = " + startCount);

    String workspace = "widgets";
    String sysId = "acme";
    int propIdSeed = 12540;
    Locale locale = LocaleUtils.toLocale("en_US");

    // INSERT 
    List<EntryDescriptor> entryURIDatas = new ArrayList<EntryDescriptor>();
    int numRecs = 12;
    int knt = 0;
    for (int ii = 0; ii < numRecs; ii++) {
        knt++;
        String propId = "" + (propIdSeed + knt);

        IRI iri = IRI.create(
                "http://localhost:8080/" + entryURIHelper.constructURIString(workspace, sysId, propId, locale));
        EntryTarget entryTarget = entryURIHelper
                .getEntryTarget(new MockRequestContext(serviceContext, "GET", iri.toString()), true);
        entryURIDatas.add(entryTarget);
    }

    // Batch INSERT
    int numOpOn = entriesDAO.insertEntryBatch(workspace, entryURIDatas);
    assertEquals(numRecs, numOpOn);

    // Batch SELECT
    List selectList = entriesDAO.selectEntryBatch(entryURIDatas);
    log.debug("selectList = " + selectList);
    assertNotNull(selectList);
    assertEquals(numRecs, selectList.size());

    Date lastModified = null;
    Date published = null;
    long seqNum = 0L;
    entryURIDatas = new ArrayList<EntryDescriptor>();
    for (Object obj : selectList) {
        EntryMetaData entryOut = (EntryMetaData) obj;
        assertEquals(entryOut.getWorkspace(), workspace);
        assertEquals(entryOut.getCollection(), sysId);
        assertEquals(entryOut.getLocale(), locale);
        int id = Integer.valueOf(entryOut.getEntryId());
        assertTrue(id >= (propIdSeed + 1) && id <= (propIdSeed + numRecs));
        assertEquals(entryOut.getRevision(), 0);
        assertEquals(entryOut.getDeleted(), false);

        if (lastModified != null) {
            assertTrue(lastModified.compareTo(entryOut.getUpdatedDate()) <= 0);
        }
        lastModified = entryOut.getUpdatedDate();

        if (published != null) {
            assertTrue(published.compareTo(entryOut.getPublishedDate()) <= 0);
        }
        published = entryOut.getPublishedDate();

        log.debug("seqNum= " + seqNum + " entryOut.getUpdateTimestamp()= " + entryOut.getUpdateTimestamp());

        assertTrue(seqNum < entryOut.getUpdateTimestamp());
        seqNum = entryOut.getUpdateTimestamp();

        IRI iri = IRI.create("http://localhost:8080/" + entryURIHelper.constructURIString(workspace, sysId,
                entryOut.getEntryId(), locale, (entryOut.getRevision() + 1)));
        EntryTarget entryTarget = entryURIHelper
                .getEntryTarget(new MockRequestContext(serviceContext, "GET", iri.toString()), true);
        entryURIDatas.add(entryTarget);
    }

    // Batch UPDATE
    numOpOn = entriesDAO.updateEntryBatch(workspace, entryURIDatas);
    assertEquals(numRecs, numOpOn);

    // Batch SELECT
    selectList = entriesDAO.selectEntryBatch(entryURIDatas);
    log.debug("selectList = " + selectList);
    assertNotNull(selectList);
    assertEquals(numRecs, selectList.size());

    seqNum = 0L;
    lastModified = null;
    published = null;
    entryURIDatas = new ArrayList<EntryDescriptor>();
    for (Object obj : selectList) {
        EntryMetaData entryOut = (EntryMetaData) obj;
        assertEquals(entryOut.getWorkspace(), workspace);
        assertEquals(entryOut.getCollection(), sysId);
        assertEquals(entryOut.getLocale(), locale);
        int id = Integer.valueOf(entryOut.getEntryId());
        assertTrue(id >= (propIdSeed + 1) && id <= (propIdSeed + numRecs));
        assertEquals(entryOut.getRevision(), 1);
        assertEquals(entryOut.getDeleted(), false);

        if (lastModified != null) {
            assertTrue(lastModified.compareTo(entryOut.getUpdatedDate()) <= 0);
        }
        lastModified = entryOut.getUpdatedDate();

        if (published != null) {
            assertTrue(published.compareTo(entryOut.getPublishedDate()) <= 0);
        }
        published = entryOut.getPublishedDate();

        assertTrue(seqNum < entryOut.getUpdateTimestamp());
        seqNum = entryOut.getUpdateTimestamp();

        IRI iri = IRI.create("http://localhost:8080/" + entryURIHelper.constructURIString(workspace, sysId,
                entryOut.getEntryId(), locale, (entryOut.getRevision() + 1)));
        EntryTarget entryTarget = entryURIHelper
                .getEntryTarget(new MockRequestContext(serviceContext, "GET", iri.toString()), true);
        entryURIDatas.add(entryTarget);
    }

    // Batch DELETE
    numOpOn = entriesDAO.deleteEntryBatch(workspace, entryURIDatas);
    assertEquals(numRecs, numOpOn);

    // Batch SELECT
    selectList = entriesDAO.selectEntryBatch(entryURIDatas);
    log.debug("selectList = " + selectList);
    assertNotNull(selectList);
    assertEquals(numRecs, selectList.size());

    seqNum = 0L;
    lastModified = null;
    published = null;
    for (Object obj : selectList) {
        EntryMetaData entryOut = (EntryMetaData) obj;
        assertEquals(entryOut.getWorkspace(), workspace);
        assertEquals(entryOut.getCollection(), sysId);
        assertEquals(entryOut.getLocale(), locale);
        int id = Integer.valueOf(entryOut.getEntryId());
        assertTrue(id >= (propIdSeed + 1) && id <= (propIdSeed + numRecs));
        assertEquals(entryOut.getRevision(), 2);
        assertEquals(entryOut.getDeleted(), true);

        if (lastModified != null) {
            assertTrue(lastModified.compareTo(entryOut.getUpdatedDate()) <= 0);
        }
        lastModified = entryOut.getUpdatedDate();

        if (published != null) {
            assertTrue(published.compareTo(entryOut.getPublishedDate()) <= 0);
        }
        published = entryOut.getPublishedDate();

        assertTrue(seqNum < entryOut.getUpdateTimestamp());
        seqNum = entryOut.getUpdateTimestamp();
    }

    // DELETE them all for real
    knt = 0;
    for (int ii = 0; ii < numRecs; ii++) {
        knt++;
        String propId = "" + (propIdSeed + knt);
        IRI iri = IRI.create(
                "http://localhost:8080/" + entryURIHelper.constructURIString(workspace, sysId, propId, locale));
        EntryTarget entryTarget = entryURIHelper
                .getEntryTarget(new MockRequestContext(serviceContext, "GET", iri.toString()), true);
        entriesDAO.obliterateEntry(entryTarget);
    }

    // COUNT
    Thread.sleep(DB_CATCHUP_SLEEP); // give the DB a chance to catch up
    int finalCount = entriesDAO.getTotalCount(serviceDescriptor);
    log.debug("finalCount = " + finalCount);
    assertEquals(startCount, finalCount);
}

From source file:com.surevine.alfresco.repo.delete.SiteNameBasedManagedDeletionService.java

/**
 * Delete the item.  This moves the item to the deleted items site, removed the marked-for-delete aspect and adds a deleted aspect
 * @param nodeRef NodeRef of the item to delete
 * @return the NodeRef of the new parent node, or <code>null</code> if deleting a folder.
 *//*  ww w  .j  a  va 2 s  .  com*/
@Override
public NodeRef delete(final NodeRef nodeRef) {
    QName nodeType = _nodeService.getType(nodeRef);

    if (ContentModel.TYPE_FOLDER.equals(nodeType)) {
        if (_logger.isDebugEnabled()) {
            _logger.debug("Deleting the contents of folder " + nodeRef);
        }

        List<ChildAssociationRef> children = _nodeService.getChildAssocs(nodeRef, ContentModel.ASSOC_CONTAINS,
                RegexQNamePattern.MATCH_ALL);

        for (ChildAssociationRef assoc : children) {
            delete(assoc.getChildRef());
        }

        return null;
    }

    try {
        //Double check the locking, as am unsure of exact semantics of .lock
        try {
            _lockService.checkForLock(nodeRef);
        } catch (NodeLockedException nle) {
            _logger.warn("Could not delete " + nodeRef + " as the node was locked");
            throw new ManagedDeletionLockException(nodeRef,
                    "Could not delete " + nodeRef + " as the node was locked", nle);
        }

        // If this is a working copy, we won't attempt deletion.
        if (_nodeService.hasAspect(nodeRef, ContentModel.ASPECT_WORKING_COPY)) {
            _logger.warn("Could not delete " + nodeRef + " as the node is a working copy of a locked node.");
            throw new ManagedDeletionLockException(nodeRef,
                    "Could not delete " + nodeRef + " as the node is a working copy of a locked node.", null);
        }

        try {
            _lockService.lock(nodeRef, LockType.WRITE_LOCK);
        } catch (UnableToAquireLockException uale) {
            _logger.warn("Could not delete " + nodeRef + " as a lock could not be acquired");
            throw new ManagedDeletionLockException(nodeRef,
                    "Could not delete " + nodeRef + " as a lock could not be acquired", uale);
        }

        final NodeRef[] targetWrapper = new NodeRef[1];

        try {
            try {
                _transactionService.getRetryingTransactionHelper()
                        .doInTransaction(new RetryingTransactionCallback<Boolean>() {
                            @Override
                            public Boolean execute() throws Throwable {
                                _logger.debug("Attempting delete of " + nodeRef);

                                //We should only be able to delete things that have been marked as Delete or Perishable
                                if (!_nodeService.hasAspect(nodeRef,
                                        ManagedDeletionModel.ASPECT_MARKED_FOR_DELETION)
                                        && !_nodeService.hasAspect(nodeRef,
                                                ManagedDeletionModel.ASPECT_PERISHABLE)) {
                                    throw new ManagedDeletionException(nodeRef,
                                            "Item is not marked for deletion or perishable, so cannot be deleted. This may simply be because it has already been deleted.");
                                }

                                //If this node has previously failed to delete, remove records of that failure
                                if (_nodeService.hasAspect(nodeRef,
                                        ManagedDeletionModel.ASPECT_FAILED_TO_DELETE)) {
                                    _nodeService.removeAspect(nodeRef,
                                            ManagedDeletionModel.ASPECT_FAILED_TO_DELETE);
                                }

                                //Disable audit policy to maintain metadata and stop hitting bugs when running from quartz
                                //This call only applies to the current transaction and so all policies will re-enable upon commit
                                //and this code is thread-safe
                                _policyFilter.disableBehaviour(ContentModel.ASPECT_AUDITABLE);

                                // Disable the mds:folderMarkedForDelete behaviours so that the parent folder doesn't have its deletion
                                // mark removed (if it has one)
                                _policyFilter.disableBehaviour(
                                        ManagedDeletionModel.ASPECT_FOLDER_MARKED_FOR_DELETION);

                                //Work out where we will be moving the item to
                                Path destinationPath = getDeleteDesinationPath(_nodeService.getPath(nodeRef));
                                if (_logger.isDebugEnabled()) {
                                    _logger.debug("Moving item to: " + destinationPath);
                                }

                                // Include a property that indicates the original site the item was deleted.
                                String originalSiteName = getSiteName(nodeRef);
                                Map<QName, Serializable> propertiesMap = new HashMap<QName, Serializable>();
                                propertiesMap.put(ManagedDeletionModel.PROP_ORIGINAL_SITE_NAME,
                                        originalSiteName);
                                propertiesMap.put(ManagedDeletionModel.PROP_DELETED_TIMESTAMP, new Date());

                                if (_logger.isDebugEnabled()) {
                                    _logger.debug("Original site name: " + originalSiteName);
                                }

                                // Get the current parent folder before we move the file (we will use this later)
                                ChildAssociationRef parentAssoc = _nodeService.getPrimaryParent(nodeRef);

                                // Move the item to it's destination.
                                final NodeRef target = moveNode(nodeRef, destinationPath);

                                //Add the deleted aspect to the node, and remove the mark for deletion and perishable aspects.
                                _nodeService.addAspect(target, ManagedDeletionModel.ASPECT_DELETED,
                                        propertiesMap);
                                _nodeService.removeAspect(target,
                                        ManagedDeletionModel.ASPECT_MARKED_FOR_DELETION);
                                _nodeService.removeAspect(target, ManagedDeletionModel.ASPECT_PERISHABLE);

                                // Check if the parent folder is marked for delete, and whether it is now empty
                                if (parentAssoc != null) {
                                    NodeRef parentNodeRef = parentAssoc.getParentRef();

                                    if (_nodeService.hasAspect(parentNodeRef,
                                            ManagedDeletionModel.ASPECT_FOLDER_MARKED_FOR_DELETION)) {
                                        List<ChildAssociationRef> children = _nodeService.getChildAssocs(
                                                parentNodeRef, ContentModel.ASSOC_CONTAINS,
                                                RegexQNamePattern.MATCH_ALL);

                                        if (children.isEmpty()) {
                                            _nodeService.deleteNode(parentNodeRef);
                                        }
                                    }
                                }

                                if (_logger.isInfoEnabled()) {
                                    _logger.info("NodeRef " + nodeRef + " has been succesfully deleted");
                                }

                                targetWrapper[0] = target;

                                return Boolean.TRUE;
                            }
                        }, false, false);
            } catch (AlfrescoRuntimeException e) {
                _logger.error("An error was encountered while attempting to delete " + nodeRef, e);

                throw e;
            }
        }
        /**
         * If we get an exception, attempt to record the exception in the repository against the item
         * (this will stop the quartz job from trying to delete the item again, but the UI will still allow for future attempts).
         * If we can't for whatever reason, then just throw the error
         */
        catch (Exception e) {
            //If the node doesn't exist anymore, don't do any special recording and just re-throw
            if (_nodeService.exists(nodeRef)) {
                Map<QName, Serializable> propertiesMap = new HashMap<QName, Serializable>();
                propertiesMap.put(ManagedDeletionModel.PROP_DELETE_FAILURE_DATE, new Date());
                propertiesMap.put(ManagedDeletionModel.PROP_DELETE_FAILURE_MESSAGE,
                        e instanceof AlfrescoRuntimeException ? e.getCause().toString() : e.toString());
                _nodeService.addAspect(nodeRef, ManagedDeletionModel.ASPECT_FAILED_TO_DELETE, propertiesMap);
            }
            boolean failedToPerish = false;

            if (_nodeService.getProperty(nodeRef, ManagedDeletionModel.PROP_PERISH_REASON) != null) {
                Date perishDue = (Date) _nodeService.getProperty(nodeRef, ManagedDeletionModel.PROP_PERISH_DUE);

                if (perishDue.compareTo(new Date()) < 0) {
                    failedToPerish = true;
                }
            }

            // Raise a different error message if the node has failed to be perished
            if (failedToPerish) {
                _logger.error("Failed to perish " + nodeRef, e);
            } else {
                _logger.error("Failed to delete " + nodeRef, e);
            }
        }

        return targetWrapper[0];
    }
    //If we locked the node during this process, then try to unlock it when we exit, bearing in mind the node may no longer exist
    finally {
        if (_nodeService.exists(nodeRef)) {
            try {
                _lockService.unlock(nodeRef);
            } catch (Exception e) {
                throw new ManagedDeletionLockException(nodeRef, "After attempting to delete the node " + nodeRef
                        + ", the nodeRef still existed, and could not be unlocked due to a: " + e, e);
            }
        }
    }
}