Example usage for java.util Date equals

List of usage examples for java.util Date equals

Introduction

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

Prototype

public boolean equals(Object obj) 

Source Link

Document

Compares two dates for equality.

Usage

From source file:uk.co.thinkofdeath.thinkcraft.bukkit.web.InternalWebServer.java

@Override
public void handle(ChannelHandlerContext context, URI uri, FullHttpRequest request) throws Exception {
    if (request.getMethod() != HttpMethod.GET) {
        sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED));
        return;/*w w w. j  av  a2  s  .c  o m*/
    }
    String modified = request.headers().get(IF_MODIFIED_SINCE);
    if (modified != null && !modified.isEmpty()) {
        Date modifiedDate = format.parse(modified);

        if (modifiedDate.equals(plugin.getStartUpDate())) {
            sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED));
            return;
        }
    }

    String path = uri.getPath();
    if (path.equals("/")) {
        path = "/index.html";
    }

    ByteBuf buffer;
    try (InputStream stream = this.getClass().getClassLoader().getResourceAsStream("www" + path)) {
        if (stream == null) {
            sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
            return;
        }
        ByteBufOutputStream out = new ByteBufOutputStream(context.alloc().buffer());
        IOUtils.copy(stream, out);
        buffer = out.buffer();
        out.close();
    }

    if (path.equals("/index.html")) {
        String page = buffer.toString(Charsets.UTF_8);
        page = page.replaceAll("%SERVERPORT%", Integer.toString(plugin.getConfiguration().getPort()));
        buffer.release();
        buffer = Unpooled.wrappedBuffer(page.getBytes(Charsets.UTF_8));
    }

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buffer);

    response.headers().set(DATE, format.format(new Date()));
    response.headers().set(LAST_MODIFIED, format.format(plugin.getStartUpDate()));

    String ext = path.substring(path.lastIndexOf('.') + 1);
    String type = mimeTypes.containsKey(ext) ? mimeTypes.get(ext) : "text/plain";
    if (type.startsWith("text/")) {
        type += "; charset=UTF-8";
    }
    response.headers().set(CONTENT_TYPE, type);
    sendHttpResponse(context, request, response);
}

From source file:org.phenotips.data.internal.PatientBirthdateUpdater.java

@Override
public void onEvent(Event event, Object source, Object data) {
    XWikiDocument doc = (XWikiDocument) source;

    BaseObject patientRecordObj = doc.getXObject(Patient.CLASS_REFERENCE);
    if (patientRecordObj == null) {
        return;//from  w  w  w.jav a  2 s  .c  o  m
    }
    String targetPropertyName = "date_of_birth";
    int year = getParameter("date_of_birth_year", patientRecordObj.getNumber());
    int month = getParameter("date_of_birth_month", patientRecordObj.getNumber());
    int day = getParameter("date_of_birth_day", patientRecordObj.getNumber());
    if (year == -1 || month == -1) {
        // No values specified in the request, skip this step
        return;
    }
    if (year == -2 || month == -2) {
        // Clear value specified in request, clear birth date.
        patientRecordObj.setDateValue(targetPropertyName, null);
        return;
    }
    if (day <= 0) {
        day = 1;
    }
    Date birthdate = patientRecordObj.getDateValue(targetPropertyName);
    Date newBirthdate = new GregorianCalendar(year, month, day).getTime();
    if (!newBirthdate.equals(birthdate)) {
        patientRecordObj.setDateValue(targetPropertyName, newBirthdate);
    }
}

From source file:org.phenotips.listeners.PatientBirthdateUpdater.java

@Override
public void onEvent(Event event, Object source, Object data) {
    XWikiDocument doc = (XWikiDocument) source;

    BaseObject patientRecordObj = doc.getXObject(new DocumentReference(
            doc.getDocumentReference().getRoot().getName(), Constants.CODE_SPACE, "PatientClass"));
    if (patientRecordObj == null) {
        return;//  w  ww.  j a  v  a  2s. c  o  m
    }
    String targetPropertyName = "date_of_birth";
    int year = getParameter("date_of_birth_year", patientRecordObj.getNumber());
    int month = getParameter("date_of_birth_month", patientRecordObj.getNumber());
    int day = getParameter("date_of_birth_day", patientRecordObj.getNumber());
    if (year == -1 || month == -1) {
        // No values specified in the request, skip this step
        return;
    }
    if (day <= 0) {
        day = 1;
    }
    Date birthdate = patientRecordObj.getDateValue(targetPropertyName);
    Date newBirthdate = new GregorianCalendar(year, month, day).getTime();
    if (!newBirthdate.equals(birthdate)) {
        patientRecordObj.setDateValue(targetPropertyName, newBirthdate);
    }
}

From source file:org.mifos.reports.business.AbstractReportParameterForm.java

protected void addErrorIfInvalid(Errors errors, String meetingDate, Date notAvailableDate, String fieldName,
        String errorCode) {//from   w  ww  .  jav a 2  s .  co  m
    Date date = parseDate(meetingDate, REPORT_DATE_PARAM_FORMAT);
    if (notAvailableDate.equals(date)) {
        errors.addError(fieldName, errorCode);
    }
}

From source file:org.orcid.frontend.web.forms.validate.StartDateBeforeEndDateValidator.java

/**
 * Method to validate the date fields of a form Rules to validate If the
 * date format is missing - the form is automatically invalid. If the dates
 * are missing, the form is **VALID** because we can't assess. If dates
 * cannot be parsed, the form is invalid If the end date is before the start
 * date, the form is invalid.//  w  w  w  .j  a v a  2 s  . c o m
 */
@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
    try {
        String startDateRepresentation = BeanUtils.getProperty(value, startDate);
        String endDateRepresentation = BeanUtils.getProperty(value, endDate);
        if (StringUtils.isBlank(startDateRepresentation) && StringUtils.isBlank(endDateRepresentation)) {
            // not our concern if the fields are both missing
            return true;
        }

        Date parsedStartDate = dateFormat.parse(startDateRepresentation);
        Date parsedEndDate = dateFormat.parse(endDateRepresentation);

        if (parsedEndDate.before(parsedStartDate) && !parsedEndDate.equals(parsedStartDate)) {
            for (String binding : boundFields) {
                context.buildConstraintViolationWithTemplate("Start date must be before end date")
                        .addNode(binding).addConstraintViolation();
            }
        } else {
            return true;
        }

    } catch (NoSuchMethodException e) {
        LOGGER.error("Cannot find method for validation of dates", e);
    } catch (ParseException e) {
        LOGGER.error("Invalid date format passed in as argument. Please check the date validation annotation",
                e);
    } catch (IllegalAccessException e) {
        LOGGER.error("The method you're using for validation is not accessible", e);
    } catch (InvocationTargetException e) {
        LOGGER.error("The underlying method used for date validation threw an exception", e);
    }

    return false;

}

From source file:hu.petabyte.redflags.engine.gear.indicator.hu.OpeningDateDiffersFromDeadlineIndicator.java

@Override
protected IndicatorResult flagImpl(Notice notice) {
    Date deadline = notice.getData().getDeadline();
    Date openingDate = null;
    if (null != notice.getProc()) {
        openingDate = notice.getProc().getOpeningDate();
    }/*w w w .  j a  v  a 2s  . c om*/

    if (null != openingDate && null != deadline && !openingDate.equals(deadline)) {
        return returnFlag();
    }
    return null;
}

From source file:org.openmrs.module.clinicalsummary.rule.antenatal.grouped.DatetimeBasedConceptFilteredRule.java

/**
 * @see org.openmrs.logic.Rule#eval(org.openmrs.logic.LogicContext, Integer, java.util.Map)
 *//*from   ww  w .ja v a  2  s .c  o  m*/
@Override
protected Result evaluate(final LogicContext context, final Integer patientId,
        final Map<String, Object> parameters) {
    Result result = new Result();

    Object conceptObjects = parameters.get(EvaluableConstants.OBS_CONCEPT);
    Map<Concept, Integer> conceptNamePositions = searchPositions(conceptObjects);

    ObsWithRestrictionRule obsWithRestrictionRule = new ObsWithStringRestrictionRule();
    Result obsResults = obsWithRestrictionRule.eval(context, patientId, parameters);

    Map<Date, Result[]> obsResultDates = new HashMap<Date, Result[]>();
    for (Result obsResult : obsResults) {
        Obs obs = (Obs) obsResult.getResultObject();
        Date obsDatetime = obs.getObsDatetime();
        // see if we already have obs array for this date
        Result[] obsResultDate = obsResultDates.get(obsDatetime);
        if (obsResultDate == null) {
            obsResultDate = new Result[CollectionUtils.size(conceptNamePositions)];
            obsResultDates.put(obsDatetime, obsResultDate);
        }
        // search the concept in the concept ordering map
        Integer position = conceptNamePositions.get(obs.getConcept());
        if (position != null)
            obsResultDate[position] = obsResult;
    }

    TreeSet<Date> keys = new TreeSet<Date>(new Comparator<Date>() {

        public int compare(final Date firstDate, final Date secondDate) {
            return firstDate.equals(secondDate) ? 0 : firstDate.after(secondDate) ? -1 : 1;
        }
    });
    keys.addAll(obsResultDates.keySet());

    // TODO: need to merge the two loop into one
    Integer counter = 0;
    Iterator<Date> iterator = keys.iterator();
    while (iterator.hasNext() && counter < 5) {
        Date date = iterator.next();
        // create the grouped results
        Result groupedResult = new Result();
        groupedResult.add(new Result(date));
        groupedResult.addAll(Arrays.asList(obsResultDates.get(date)));
        // add them to the main result of the rule
        result.add(groupedResult);
        // increase the counter as we only want last 5
        counter++;
    }

    Collections.reverse(result);

    return result;
}

From source file:ju.ehealthservice.search.Search.java

public List<String> getFileNames(String from, String to) {
    if (patientExists()) {
        try {/* w  w w .  j av a 2 s.c o  m*/
            Date fromDate = Constants.small.parse(from);
            Date toDate = Constants.small.parse(to);
            if (fromDate.equals(toDate)) {
                toDate = DateUtils.addSeconds(toDate, 86399);
            }
            for (File listOfFile : listOfFiles) {
                if (listOfFile.isFile()) {
                    if (!listOfFile.getName().equals("metadata.xml")) {
                        String originalName = listOfFile.getName();
                        String fileName = originalName.split("_", 2)[1];
                        System.out.println("File name is " + fileName);
                        Date date = Constants.sdf.parse(fileName);
                        if (fromDate.compareTo(date) * toDate.compareTo(date) < 0) {
                            files.add(originalName);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return trimFileExtension(files);
}

From source file:org.hspconsortium.cwf.fhir.common.FhirUtil.java

public static String getDisplayValue(Period value) {
    Date start = value.getStart();
    Date end = value.getEnd();//  ww w .jav a2  s.  c  o m
    String result = "";

    if (start != null) {
        result = DateUtil.formatDate(start);

        if (start.equals(end)) {
            end = null;
        }
    }

    if (end != null) {
        result += (result.isEmpty() ? "" : " - ") + DateUtil.formatDate(end);
    }

    return result;
}

From source file:org.kalypso.zml.ui.table.commands.menu.ZmlCommandSetValuesAbove.java

@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {
    try {// ww w .  j a  v  a  2s  . c  o  m
        final IZmlTable table = ZmlHandlerUtil.getTable(event);
        final ZmlModelViewport model = table.getModelViewport();
        final IZmlTableSelection selection = table.getSelection();
        final IZmlModelValueCell active = selection.getFocusCell();
        if (active == null)
            return Status.CANCEL_STATUS;

        final IZmlModelColumn column = active.getColumn();
        final IZmlEditingStrategy strategy = model.getEditingStrategy(column);

        if (strategy.isAggregated()) {
            final ZmlModelCellLabelProvider provider = new ZmlModelCellLabelProvider(column);
            final String targetValue = provider.getText(table.getModelViewport(), active);

            IZmlModelValueCell ptr = model.findPreviousCell(active);
            while (ptr != null) {
                strategy.setValue(ptr, targetValue);

                ptr = model.findPreviousCell(ptr);
            }
        } else {
            final Object targetValue = active.getValue();
            final Date base = active.getIndexValue();

            final TupleModelTransaction transaction = new TupleModelTransaction(column.getTupleModel(),
                    column.getMetadata());

            column.accept(new IZmlModelColumnVisitor() {
                @Override
                public void visit(final IZmlModelValueCell ref) throws CancelVisitorException {
                    final Date current = ref.getIndexValue();
                    if (current.after(base) || current.equals(base))
                        throw new CancelVisitorException();

                    final TupleModelDataSet dataset = new TupleModelDataSet(column.getValueAxis(), targetValue,
                            KalypsoStati.BIT_USER_MODIFIED, IDataSourceItem.SOURCE_MANUAL_CHANGED);
                    transaction.add(new UpdateTupleModelDataSetCommand(ref.getModelIndex(), dataset, true));
                }
            });

            column.getTupleModel().execute(transaction);
        }

        doInterpolation(column);

        return Status.OK_STATUS;
    } catch (final Exception e) {
        throw new ExecutionException(Messages.ZmlCommandSetValuesAbove_0, e);
    }
}