Example usage for java.util Calendar before

List of usage examples for java.util Calendar before

Introduction

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

Prototype

public boolean before(Object when) 

Source Link

Document

Returns whether this Calendar represents a time before the time represented by the specified Object.

Usage

From source file:com.aimluck.eip.services.storage.impl.ALDefaultStorageHanlder.java

@Override
public boolean deleteOldFolder(String folderPath, Calendar cal) {
    Calendar mod = Calendar.getInstance();
    boolean flag = true;
    File parent_folder = new File(folderPath);
    try {//from  w  ww .  j a  v a 2 s  .  c om
        if (!parent_folder.exists()) {
            return false;
        }
        if (parent_folder.isFile()) {
            return false;
        }
        String folders_path[] = parent_folder.list();
        if (folders_path.length == 0) {
            return true;
        }
        int length = folders_path.length;
        for (int i = 0; i < length; i++) {
            File folder = new File(parent_folder.getAbsolutePath() + File.separator + folders_path[i]);
            mod.setTimeInMillis(folder.lastModified());// ??
            if (folder.isDirectory()) {
                if (!deleteOldFolder(folder.getAbsolutePath(), cal)) {// ?????????
                    flag = false;
                } else if (mod.before(cal)) {// ?????
                    if (!folder.delete()) {
                        flag = false;
                    }
                }
            } else {
                if (mod.before(cal)) {
                    // ??????????
                    if (!folder.delete()) {
                        flag = false;
                    }
                } else {
                    flag = false;
                }
            }

        }
    } catch (Exception e) {
        logger.error("ALDefaultStorageHanlder.deleteOldFolder", e);
        return false;
    }
    return flag;
}

From source file:nl.strohalm.cyclos.services.ads.AdImportServiceImpl.java

private void importAd(final AdImport adImport, final int lineNumber,
        final Map<String, AdCategory> existingAdCategoryMap,
        final Map<String, ImportedAdCategory> importedAdCategoryMap,
        final Map<String, CustomField> customFieldMap, final LocalSettings localSettings,
        final List<String> headers, final List<String> values) {
    final Map<String, String> customFieldValues = new HashMap<String, String>();

    final CalendarConverter dateConverter = localSettings.getRawDateConverter();
    final NumberConverter<BigDecimal> numberConverter = localSettings.getNumberConverter();

    // Insert the ad
    ImportedAd ad = new ImportedAd();
    ad.setLineNumber(lineNumber);/*from   w w  w. j a  va  2s. co m*/
    ad.setImport(adImport);
    ad.setStatus(ImportedAd.Status.SUCCESS);
    ad = importedAdDao.insert(ad);
    ad.setPublicationPeriod(new Period());
    ad.setExternalPublication(true);
    try {
        ad.setCustomValues(new ArrayList<ImportedAdCustomFieldValue>());

        // Process each field. Field names are lowercased to ignore case
        for (int i = 0; i < headers.size() && i < values.size(); i++) {
            final String field = StringUtils.trimToEmpty(headers.get(i)).toLowerCase();
            final String value = StringUtils.trimToNull(values.get(i));
            final boolean valueIsTrue = "true".equalsIgnoreCase(value) || "1".equals(value);
            if ("owner".equals(field)) {
                if (value != null) {
                    try {
                        final MemberUser user = (MemberUser) elementService.loadUser(value, RelationshipHelper
                                .nested(User.Relationships.ELEMENT, Element.Relationships.GROUP));
                        ad.setOwner(user.getMember());
                    } catch (final Exception e) {
                        ad.setStatus(ImportedAd.Status.INVALID_OWNER);
                        ad.setErrorArgument1(value);
                    }
                }
            } else if ("title".equals(field)) {
                ad.setTitle(value);
            } else if ("description".equals(field)) {
                ad.setDescription(value);
            } else if ("html".equals(field)) {
                ad.setHtml(valueIsTrue);
            } else if ("publicationstart".equals(field)) {
                try {
                    ad.getPublicationPeriod().setBegin(dateConverter.valueOf(value));
                } catch (final Exception e) {
                    ad.setStatus(ImportedAd.Status.INVALID_PUBLICATION_START);
                    ad.setErrorArgument1(value);
                    break;
                }
            } else if ("publicationend".equals(field)) {
                try {
                    ad.getPublicationPeriod().setEnd(dateConverter.valueOf(value));
                } catch (final Exception e) {
                    ad.setStatus(ImportedAd.Status.INVALID_PUBLICATION_END);
                    ad.setErrorArgument1(value);
                    break;
                }
            } else if ("tradetype".equals(field)) {
                // Only search is handled now, as it's the exception. Later, if it's null, offer is implied
                if ("search".equalsIgnoreCase(value)) {
                    ad.setTradeType(TradeType.SEARCH);
                }
            } else if ("external".equals(field)) {
                ad.setExternalPublication(valueIsTrue);
            } else if ("price".equals(field)) {
                try {
                    ad.setPrice(numberConverter.valueOf(value));
                    if (BigDecimal.ZERO.equals(ad.getPrice())) {
                        ad.setPrice(null);
                    }
                } catch (final Exception e) {
                    ad.setStatus(ImportedAd.Status.INVALID_PRICE);
                    ad.setErrorArgument1(value);
                    break;
                }
            } else if ("category".equals(field)) {
                final Object category = handleCategory(ad, value, existingAdCategoryMap, importedAdCategoryMap);
                if (category instanceof AdCategory) {
                    ad.setExistingCategory((AdCategory) category);
                } else if (category instanceof ImportedAdCategory) {
                    ad.setImportedCategory((ImportedAdCategory) category);
                } else if (ad.getStatus() != null) {
                    // The handleCategory may have set the status. Set the argument and leave
                    ad.setErrorArgument1(value);
                    break;
                }
            } else if (customFieldMap.containsKey(field)) {
                // Create a custom field value
                final ImportedAdCustomFieldValue fieldValue = new ImportedAdCustomFieldValue();
                fieldValue.setField(customFieldMap.get(field));
                fieldValue.setValue(value);
                ad.getCustomValues().add(fieldValue);
                customFieldValues.put(field, value);
            } else {
                throw new UnknownColumnException(field);
            }
        }

        // When there was an error, stop processing
        if (ad.getStatus() != ImportedAd.Status.SUCCESS) {
            return;
        }

        // Validate some data
        if (ad.getOwner() == null) {
            ad.setStatus(ImportedAd.Status.MISSING_OWNER);
            return;
        }
        if (ad.getExistingCategory() == null && ad.getImportedCategory() == null) {
            ad.setStatus(ImportedAd.Status.MISSING_CATEGORY);
            return;
        }
        if (ad.getTitle() == null) {
            ad.setStatus(ImportedAd.Status.MISSING_TITLE);
            return;
        }
        if (ad.getDescription() == null) {
            ad.setStatus(ImportedAd.Status.MISSING_DESCRIPTION);
            return;
        }
        // Set some default data
        final MemberGroupSettings groupSettings = ad.getOwner().getMemberGroup().getMemberSettings();
        Calendar begin = ad.getPublicationPeriod().getBegin();
        if (begin == null) {
            // When there's no begin, assume today
            begin = Calendar.getInstance();
            ad.getPublicationPeriod().setBegin(begin);
        }
        final Calendar end = ad.getPublicationPeriod().getEnd();
        if (end == null) {
            // Without end, it's a permanent ad
            // Check whether permanent ads are allowed
            if (!groupSettings.isEnablePermanentAds()) {
                ad.setStatus(ImportedAd.Status.MISSING_PUBLICATION_PERIOD);
                return;
            }
            ad.setPermanent(true);
        } else {
            // Validate the publication period
            if (begin.after(end)) {
                ad.setStatus(ImportedAd.Status.PUBLICATION_BEGIN_AFTER_END);
                return;
            } else {
                // Check the max publication time
                final TimePeriod maxAdPublicationTime = groupSettings.getMaxAdPublicationTime();
                if (!end.before(maxAdPublicationTime.add(begin))) {
                    ad.setStatus(ImportedAd.Status.MAX_PUBLICATION_EXCEEDED);
                    return;
                }
            }
        }
        if (ad.getTradeType() == null) {
            ad.setTradeType(TradeType.OFFER);
        }
        switch (groupSettings.getExternalAdPublication()) {
        case DISABLED:
            ad.setExternalPublication(false);
            break;
        case ENABLED:
            ad.setExternalPublication(true);
            break;
        }

        // Save the custom field values
        try {
            adCustomFieldService.saveValues(ad);
        } catch (final Exception e) {
            ad.setStatus(ImportedAd.Status.INVALID_CUSTOM_FIELD);
            if (e instanceof ValidationException) {
                final ValidationException vex = (ValidationException) e;
                final Map<String, Collection<ValidationError>> errorsByProperty = vex.getErrorsByProperty();
                if (MapUtils.isNotEmpty(errorsByProperty)) {
                    final String fieldName = errorsByProperty.keySet().iterator().next();
                    ad.setErrorArgument1(fieldName);
                    final String fieldValue = StringUtils.trimToNull(customFieldValues.get(fieldName));
                    if (fieldValue == null) {
                        // When validation failed and the field is null, it's actually missing
                        ad.setStatus(ImportedAd.Status.MISSING_CUSTOM_FIELD);
                    } else {
                        ad.setErrorArgument2(fieldValue);
                    }
                }
            }
            return;
        }

    } catch (final UnknownColumnException e) {
        throw e;
    } catch (final Exception e) {
        ad.setStatus(ImportedAd.Status.UNKNOWN_ERROR);
        ad.setErrorArgument1(e.toString());
    } finally {
        importedAdDao.update(ad);
    }

}

From source file:com.aimluck.eip.services.storage.impl.ALDefaultStorageHandler.java

@Override
public boolean deleteOldFolder(String folderPath, Calendar cal) {
    Calendar mod = Calendar.getInstance();
    boolean flag = true;
    File parent_folder = new File(getAbsolutePath(folderPath));
    try {/*from   ww  w. ja  va2  s .  c o m*/
        if (!parent_folder.exists()) {
            return false;
        }
        if (parent_folder.isFile()) {
            return false;
        }
        String folders_path[] = parent_folder.list();
        if (folders_path.length == 0) {
            return true;
        }
        int length = folders_path.length;
        for (int i = 0; i < length; i++) {
            File folder = new File(parent_folder.getAbsolutePath() + File.separator + folders_path[i]);
            mod.setTimeInMillis(folder.lastModified());// ??
            if (folder.isDirectory()) {
                if (!deleteOldFolder(folder.getAbsolutePath(), cal)) {// ?????????
                    flag = false;
                } else if (mod.before(cal)) {// ?????
                    if (!folder.delete()) {
                        flag = false;
                    }
                }
            } else {
                if (mod.before(cal)) {
                    // ??????????
                    if (!folder.delete()) {
                        flag = false;
                    }
                } else {
                    flag = false;
                }
            }

        }
    } catch (Exception e) {
        logger.error("ALDefaultStorageHandler.deleteOldFolder", e);
        return false;
    }
    return flag;
}

From source file:es.pode.modificador.presentacion.planificar.PlanificarControllerImpl.java

public final void planificar(ActionMapping mapping,
        es.pode.modificador.presentacion.planificar.PlanificarForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String actionSubmit = form.getAction();
    int day, year, month, hour, minute;
    Calendar fechaHoy = Calendar.getInstance();

    if (actionSubmit.equals("Aceptar")) {
        if (form.getFecha() == null || form.getFecha().equals("")) {
            throw new ValidatorException("{planificar.msgErrorFecha}");
        } else if (form.getHoras() == null || form.getHoras().equals("")) {
            throw new ValidatorException("{planificar.msgErrorHora}");
        } else if (form.getMinutos() == null || form.getMinutos().equals("")) {
            throw new ValidatorException("{planificar.msgErrorMinutos}");
        } else {/*from  w  w w  .j  a v  a 2 s . c  o m*/

            String idModificacion = form.getIdModificacion();
            try {
                hour = Integer.valueOf(form.getHoras()).intValue();
                minute = Integer.valueOf(form.getMinutos()).intValue();

            } catch (Exception e) {
                throw new ValidatorException("{planificar.msgErrorFormato}");
            }

            try {
                StringBuffer fechaStr = new StringBuffer();
                fechaStr.append(form.getFecha()).append(guion).append(hour).append(guion);
                fechaStr.append(minute);

                SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy-HH-mm");
                format.setLenient(false);

                Date fecha = format.parse(fechaStr.toString());
                Calendar fechaEjecucion = Calendar.getInstance();
                fechaEjecucion.setTime(fecha);
                if (fechaHoy.before(fechaEjecucion)) {
                    Long idModificacionLong = Long.valueOf(idModificacion);

                    this.getSrvHerramientaModificacion().planificarModificacion(idModificacionLong,
                            fechaEjecucion);
                } else {
                    throw new ValidatorException("{planificar.msgErrorFecha}");

                }
            } catch (ParseException e1) {
                throw new ValidatorException("{planificar.msgErrorFormato}");
            } catch (ValidatorException e2) {
                throw new ValidatorException("{planificar.msgErrorFecha}");
            } catch (Exception e3) {
                throw new ValidatorException("{planificar.msgExcepcion}");
            }

        }

    }
}

From source file:org.broadleafcommerce.core.offer.service.processor.AbstractBaseProcessor.java

/**
 * Removes all out of date offers.  If an offer does not have a start date, or the start
 * date is a later date, that offer will be removed.  Offers without a start date should
 * not be processed.  If the offer has a end date that has already passed, that offer
 * will be removed.  Offers without a end date will be processed if the start date
 * is prior to the transaction date.//www. j a va  2s  .com
 *
 * @param offers
 * @return List of Offers with valid dates
 */
protected List<Offer> removeOutOfDateOffers(List<Offer> offers) {
    List<Offer> offersToRemove = new ArrayList<Offer>();
    for (Offer offer : offers) {
        TimeZone timeZone = getOfferTimeZoneProcessor().getTimeZone(offer);

        Calendar current = timeZone == null ? SystemTime.asCalendar() : SystemTime.asCalendar(timeZone);
        Calendar start = null;
        if (offer.getStartDate() != null) {
            LocalDateTime startDate = new LocalDateTime(offer.getStartDate());
            start = timeZone == null ? new GregorianCalendar() : new GregorianCalendar(timeZone);
            start.set(Calendar.YEAR, startDate.getYear());
            start.set(Calendar.MONTH, startDate.getMonthOfYear() - 1);
            start.set(Calendar.DAY_OF_MONTH, startDate.getDayOfMonth());
            start.set(Calendar.HOUR_OF_DAY, startDate.getHourOfDay());
            start.set(Calendar.MINUTE, startDate.getMinuteOfHour());
            start.set(Calendar.SECOND, startDate.getSecondOfMinute());
            start.get(Calendar.HOUR_OF_DAY);//do not delete this line
            start.get(Calendar.MINUTE);
            if (LOG.isTraceEnabled()) {
                LOG.debug("Offer: " + offer.getName() + " timeZone:" + timeZone + " startTime:"
                        + start.getTime() + " currentTime:" + current.getTime());
            }
        }
        Calendar end = null;
        if (offer.getEndDate() != null) {
            LocalDateTime endDate = new LocalDateTime(offer.getEndDate());
            end = timeZone == null ? new GregorianCalendar() : new GregorianCalendar(timeZone);
            end.set(Calendar.YEAR, endDate.getYear());
            end.set(Calendar.MONTH, endDate.getMonthOfYear() - 1);
            end.set(Calendar.DAY_OF_MONTH, endDate.getDayOfMonth());
            end.set(Calendar.HOUR_OF_DAY, endDate.getHourOfDay());
            end.set(Calendar.MINUTE, endDate.getMinuteOfHour());
            end.set(Calendar.SECOND, endDate.getSecondOfMinute());
            end.get(Calendar.HOUR_OF_DAY);//do not delete this line
            end.get(Calendar.MINUTE);
            if (LOG.isTraceEnabled()) {
                LOG.debug("Offer: " + offer.getName() + " endTime:" + start.getTime());
            }
        }
        if ((offer.getStartDate() == null) || (start.after(current))) {
            offersToRemove.add(offer);
        } else if (offer.getEndDate() != null && end.before(current)) {
            offersToRemove.add(offer);
        }
    }
    // remove all offers in the offersToRemove list from original offers list
    for (Offer offer : offersToRemove) {
        offers.remove(offer);
    }
    return offers;

    // return offers;
}

From source file:com.ecofactor.qa.automation.newapp.service.BaseDataServiceImpl.java

/**
 * @param thermostatId//from   w  ww.j  a v a  2 s .c  o  m
 * @param algoId
 * @see com.ecofactor.qa.automation.algorithm.service.DataService#waitAndVerifyEventProcessed(java.lang.Integer,
 *      int)
 */
public void waitAndVerifyEventProcessed(Integer thermostatId, int algoId) {

    DriverConfig.setLogString(
            "Wait and verify algorithm event " + algoId + " fired for Thermostat : " + thermostatId, true);
    boolean eventProcessed = false;

    Algorithm algorithm = findByAlgorithmId(algoId);
    Integer phaseDuration = (int) ((2.5) * (int) (algorithm.getPhaseDuration()));
    String startTimeString = DateUtil.getUTCCurrentTimeStamp();
    Calendar startTime = DateUtil.parseToCalendar(startTimeString, DateUtil.DATE_FMT_FULL);

    String endTimeString = DateUtil.getUTCCurrentTimeStamp();
    Calendar endTime = DateUtil.parseToCalendar(endTimeString, DateUtil.DATE_FMT_FULL);

    if (algoId == 190 || algoId == 191) {
        endTime.add(Calendar.MINUTE, 15);
    } else {
        endTime.add(Calendar.SECOND, phaseDuration);
    }

    String currentTimeString = DateUtil.getUTCCurrentTimeStamp();
    Calendar currentTime = DateUtil.parseToCalendar(currentTimeString, DateUtil.DATE_FMT_FULL);
    DriverConfig.setLogString("Current Time : " + DateUtil.format(currentTime, DateUtil.DATE_FMT_FULL)
            + ", Wait until : " + DateUtil.format(endTime, DateUtil.DATE_FMT_FULL)
            + " to check algorithm events in event table", true);

    do {
        smallWait();
        List<PartitionedThermostatEvent> events = listEvents(thermostatId, startTime, endTime);
        if (events != null) {
            for (PartitionedThermostatEvent event : events) {
                if (event.getAlgorithmId().intValue() == algoId) {
                    if (algoId == -20 || event.getStatus() == 1) {
                        DataUtil.printEventTableGrid(events);
                        eventProcessed = true;
                        break;
                    }
                }
            }
        }

        if (eventProcessed) {
            break;
        }

        currentTimeString = DateUtil.getUTCCurrentTimeStamp();
        currentTime = DateUtil.parseToCalendar(currentTimeString, DateUtil.DATE_FMT_FULL);

    } while (currentTime.before(endTime));

    Assert.assertTrue(eventProcessed, "Processed Event not found for algo " + algoId);
}

From source file:org.ms123.common.team.TeamServiceImpl.java

private boolean checkTeamDate(Map teamInternalMap, Map teamMap) {
    Calendar today = Calendar.getInstance();
    today.set(Calendar.HOUR_OF_DAY, 0);
    today.set(Calendar.MINUTE, 0);
    today.set(Calendar.SECOND, 0);
    today.set(Calendar.MILLISECOND, 0);
    Calendar validFrom = null;//w  w  w . ja v a 2  s .c  o m
    if (teamMap != null && teamMap.get("validFrom") != null) {
        validFrom = getCalendar(teamMap, "validFrom", 0);
    } else {
        if (teamInternalMap != null) {
            validFrom = getCalendar(teamInternalMap, "validFrom", 0);
        }
    }
    Calendar validTo = null;
    if (teamMap != null && teamMap.get("validTo") != null) {
        validTo = getCalendar(teamMap, "validTo", Long.MAX_VALUE);
    } else {
        if (teamInternalMap != null) {
            validTo = getCalendar(teamInternalMap, "validTo", Long.MAX_VALUE);
        }
    }
    boolean startOk = true;
    boolean endOk = true;
    if (validFrom != null) {
        debug("checkTeamDate.validFrom:" + validFrom.getTime());
        debug("checkTeamDate.validFrom.before:" + today.before(validFrom));
        if (today.before(validFrom)) {
            startOk = false;
        }
    }
    if (validTo != null) {
        debug("checkTeamDate.validTo:" + validTo.getTime());
        debug("checkTeamDate.validTo.after:" + today.after(validTo));
        if (today.after(validTo)) {
            endOk = false;
        }
    }
    debug("checkTeamDate:" + startOk + "/" + endOk);
    if (!startOk || !endOk) {
        return false;
    }
    return true;
}

From source file:edu.ku.brc.specify.config.Scriptlet.java

/**
 * Create a string representing the difference between two dates.
 * @param startDate the start date/*from w w w  . j  a v a2  s.  c  o  m*/
 * @param endDate the end date
 */
public String dateDifference(java.sql.Date startDate, java.sql.Date endDate) {
    String loanLength = UIRegistry.getResourceString("NA");

    if (startDate != null && endDate != null) {
        Calendar startCal = Calendar.getInstance();
        startCal.setTime(startDate);

        Calendar endCal = Calendar.getInstance();
        endCal.setTime(endDate);

        int monthCount = 0;
        while (startCal.before(endCal)) {
            startCal.add(Calendar.MONTH, 1);
            monthCount++;
        }

        loanLength = String.format(
                UIRegistry.getResourceString(monthCount == 1 ? "SCRPLT_1_MON_LEN" : "SCRPLT_MON_LEN"),
                monthCount);
    }
    return loanLength;
}

From source file:org.overlord.sramp.server.mvn.services.MavenFacadeServlet.java

/**
 * Generates the maven-metadata.xml file dynamically for a given groupId/artifactId/snapshot-version.
 * This will list all of the snapshot versions available.
 * @param gavInfo/*  w  w  w  .  j a v a  2s  . co m*/
 * @throws Exception
 */
private String doGenerateSnapshotMavenMetaData(MavenGavInfo gavInfo) throws Exception {
    List<BaseArtifactType> artifacts = queryService.query(
            "/s-ramp[@maven.groupId = '" + gavInfo.getGroupId() + "'" + " and @maven.artifactId = '"
                    + gavInfo.getArtifactId() + "'" + " and @maven.version = '" + gavInfo.getVersion() + "']",
            "createdTimestamp", true);
    if (artifacts.size() == 0) {
        return null;
    }

    SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyyMMdd.HHmmss");
    SimpleDateFormat updatedFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    StringBuilder snapshotVersions = new StringBuilder();
    snapshotVersions.append("    <snapshotVersions>\n");
    Set<String> processed = new HashSet<String>();
    Calendar latestDate = null;
    for (BaseArtifactType artifact : artifacts) {
        String extension = SrampModelUtils.getCustomProperty(artifact, "maven.type");
        String classifier = SrampModelUtils.getCustomProperty(artifact, "maven.classifier");
        String value = gavInfo.getVersion();
        Calendar updatedDate = artifact.getLastModifiedTimestamp().toGregorianCalendar();
        String updated = updatedFormat.format(updatedDate.getTime());
        String pkey = classifier + "::" + extension;
        if (processed.add(pkey)) {
            snapshotVersions.append("      <snapshotVersion>\n");
            if (classifier != null)
                snapshotVersions.append("        <classifier>").append(classifier).append("</classifier>\n");
            snapshotVersions.append("        <extension>").append(extension).append("</extension>\n");
            snapshotVersions.append("        <value>").append(value).append("</value>\n");
            snapshotVersions.append("        <updated>").append(updated).append("</updated>\n");
            snapshotVersions.append("      </snapshotVersion>\n");
            if (latestDate == null || latestDate.before(updatedDate)) {
                latestDate = updatedDate;
            }
        }
    }
    snapshotVersions.append("    </snapshotVersions>\n");

    String groupId = gavInfo.getGroupId();
    String artifactId = gavInfo.getArtifactId();
    String version = gavInfo.getVersion();
    String lastUpdated = updatedFormat.format(latestDate.getTime());

    StringBuilder mavenMetadata = new StringBuilder();
    mavenMetadata.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    mavenMetadata.append("<metadata>\n");
    mavenMetadata.append("  <groupId>").append(groupId).append("</groupId>\n");
    mavenMetadata.append("  <artifactId>").append(artifactId).append("</artifactId>\n");
    mavenMetadata.append("  <version>").append(version).append("</version>\n");
    mavenMetadata.append("  <versioning>\n");
    mavenMetadata.append("    <snapshot>\n");
    mavenMetadata.append("      <timestamp>").append(timestampFormat.format(latestDate.getTime()))
            .append("</timestamp>\n");
    mavenMetadata.append("      <buildNumber>1</buildNumber>\n");
    mavenMetadata.append("    </snapshot>\n");
    mavenMetadata.append("    <lastUpdated>").append(lastUpdated).append("</lastUpdated>\n");
    mavenMetadata.append(snapshotVersions.toString());
    mavenMetadata.append("  </versioning>\n");
    mavenMetadata.append("</metadata>\n");

    if (!gavInfo.isHash()) {
        return mavenMetadata.toString();
    } else {
        return generateHash(mavenMetadata.toString(), gavInfo.getHashAlgorithm());
    }
}

From source file:org.madsonic.service.MediaFileService.java

private boolean isNewAdded(MediaFile mediafile, String TimeSpan) {

    try {/*from   w  w w .  j a  v a 2  s  .  c om*/

        Date LastSystemScan = null;
        Integer timespan = 0;

        if (TimeSpan.contains("OneHour")) {
            timespan = 1;
        }
        ;
        if (TimeSpan.contains("OneDay")) {
            timespan = 2;
        }
        ;
        if (TimeSpan.contains("OneWeek")) {
            timespan = 3;
        }
        ;
        if (TimeSpan.contains("OneMonth")) {
            timespan = 4;
        }
        ;
        if (TimeSpan.contains("TwoMonth")) {
            timespan = 5;
        }
        ;
        if (TimeSpan.contains("ThreeMonth")) {
            timespan = 6;
        }
        ;
        if (TimeSpan.contains("SixMonth")) {
            timespan = 7;
        }
        ;
        if (TimeSpan.contains("OneYear")) {
            timespan = 8;
        }
        ;

        switch (timespan) {
        case 1:
            LastSystemScan = new Date(System.currentTimeMillis() - 3600 * 1000);
            break;
        case 2:
            LastSystemScan = new Date(System.currentTimeMillis() - 24 * 3600 * 1000);
            break;
        case 3:
            LastSystemScan = new Date(System.currentTimeMillis() - 7L * 24 * 3600 * 1000);
            break;
        case 4:
            LastSystemScan = new Date(System.currentTimeMillis() - 30L * 24 * 3600 * 1000);
            break;
        case 5:
            LastSystemScan = new Date(System.currentTimeMillis() - 60L * 24 * 3600 * 1000);
            break;
        case 6:
            LastSystemScan = new Date(System.currentTimeMillis() - 90L * 24 * 3600 * 1000);
            break;
        case 7:
            LastSystemScan = new Date(System.currentTimeMillis() - 182L * 24 * 3600 * 1000);
            break;
        case 8:
            LastSystemScan = new Date(System.currentTimeMillis() - 365L * 24 * 3600 * 1000);
            break;
        default:

        }

        //      Date LastSystemScan = ThreeMonth;
        Date LastMediaScan = mediafile.getCreated();

        Calendar calLastSystemScan = Calendar.getInstance();
        Calendar calLastMediaScan = Calendar.getInstance();

        calLastMediaScan.setTime(LastMediaScan);
        calLastSystemScan.setTime(LastSystemScan);

        if (calLastSystemScan.before(calLastMediaScan)) {
            return true;
        }
        return false;

        //      System.out.println("Current date(" + new SimpleDateFormat("yyyy.MM.dd hh:mm").format(calLastSystemScan.getTime()) + ")");
        //      System.out.println("Scandat date(" + new SimpleDateFormat("yyyy.MM.dd hh:mm").format(calLastMediaScan.getTime()) + ")");
        //      
        //       long milliseconds1 = calLastSystemScan.getTimeInMillis();
        //      long milliseconds2 = calLastMediaScan.getTimeInMillis();
        //      long diff = milliseconds2 - milliseconds1;
        //      
        //      long diffDays = diff / (24 * 60 * 60 * 1000);
        //      long diffHours = diff / (60 * 60 * 1000);
        //      
        //      System.out.println("Time in days: " + diffDays  + " days.");
        //      System.out.println("Time in hours: " + diffHours  + " hours.");

    } catch (Exception x) {
        LOG.error("Failed to get TimeSpan.", x);
    }
    return false;

}