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:com.aurel.track.fieldType.runtime.matchers.run.DateMatcherRT.java

/**
 * Whether the value matches or not/* w  w w  . ja v a  2 s.c o  m*/
 * @param attributeValue
 * @return
 */
@Override
public boolean match(Object attributeValue) {
    Boolean nullMatch = nullMatcher(attributeValue);
    if (nullMatch != null) {
        return nullMatch.booleanValue();
    }
    if (attributeValue == null) {
        return false;
    }
    //probably no value specified
    if (dayBegin == null && dayEnd == null) {
        return true;
    }
    Date attributeValueDate = null;
    try {
        attributeValueDate = (Date) attributeValue;
    } catch (Exception e) {
        LOGGER.error("Converting the attribute value " + attributeValue + " of type "
                + attributeValue.getClass().getName() + " to Date failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        return false;
    }
    switch (relation) {
    case MatchRelations.EQUAL_DATE:
    case MatchRelations.THIS_WEEK:
    case MatchRelations.THIS_MONTH:
    case MatchRelations.LAST_WEEK:
    case MatchRelations.LAST_MONTH:
        //for dates without time value (for ex. startDate, endDate) the equality should be also tested
        return (attributeValueDate.getTime() == dayBegin.getTime() || attributeValueDate.after(dayBegin))
                && attributeValueDate.before(dayEnd);
    case MatchRelations.NOT_EQUAL_DATE:
        //dayEnd is already the next day so the equality should be also tested
        return attributeValueDate.before(dayBegin) || attributeValueDate.after(dayEnd)
                || attributeValueDate.getTime() == dayEnd.getTime();
    case MatchRelations.GREATHER_THAN_DATE:
    case MatchRelations.IN_MORE_THAN_DAYS:
        return attributeValueDate.after(dayEnd) || attributeValueDate.getTime() == dayEnd.getTime();
    case MatchRelations.LESS_THAN_DAYS_AGO:
        return (attributeValueDate.after(dayEnd) || attributeValueDate.getTime() == dayEnd.getTime())
                && attributeValueDate.before(new Date());
    case MatchRelations.GREATHER_THAN_EQUAL_DATE:
    case MatchRelations.LESS_THAN_EQUAL_DAYS_AGO:
    case MatchRelations.IN_MORE_THAN_EQUAL_DAYS:
        return attributeValueDate.after(dayBegin) || attributeValueDate.getTime() == dayBegin.getTime();
    case MatchRelations.LESS_THAN_DATE:
    case MatchRelations.MORE_THAN_DAYS_AGO:
        return attributeValueDate.before(dayBegin);
    case MatchRelations.IN_LESS_THAN_DAYS:
        return (attributeValueDate.before(dayBegin) || attributeValueDate.getTime() == dayBegin.getTime())
                && attributeValueDate.after(new Date());
    case MatchRelations.LESS_THAN_EQUAL_DATE:
    case MatchRelations.MORE_THAN_EQUAL_DAYS_AGO:
    case MatchRelations.IN_LESS_THAN_EQUAL_DAYS:
        return attributeValueDate.before(dayEnd);
    case MatchRelations.LATER_AS_LASTLOGIN:
        if (dayBegin == null) {
            //the very first logging 
            return true;
        }
        return attributeValueDate.after(dayBegin);
    default:
        return false;
    }
}

From source file:au.edu.uq.cmm.paul.servlet.WebUIController.java

@RequestMapping(value = "/facilities/{facilityName:.+}", params = {
        "setIntertidal" }, method = RequestMethod.POST)
public String setFacilityHWM(@PathVariable String facilityName, Model model, HttpServletRequest request,
        @RequestParam String lwmTimestamp, @RequestParam String hwmTimestamp) throws ConfigurationException {
    model.addAttribute("returnTo", inferReturnTo(request, "/facilities"));
    Facility facility = lookupFacilityByName(facilityName);
    FacilityStatus status = getFacilityStatusManager().getStatus(facility);
    if (status.getStatus() == FacilityStatusManager.Status.ON) {
        model.addAttribute("message", "Cannot change LWM and HWM while the Grabber is running.");
        return "failed";
    }//from w  ww  .  j  a  va  2s  .  co m
    Date oldLWM = status.getGrabberLWMTimestamp();
    Date oldHWM = status.getGrabberHWMTimestamp();
    Date lwm = parseDate(lwmTimestamp);
    Date hwm = parseDate(hwmTimestamp);
    Date now = new Date();
    if (lwm != null && hwm != null && !lwm.after(hwm) && hwm.before(now)) {
        getFacilityStatusManager().updateIntertidalTimestamp(facility, lwm, hwm);
        model.addAttribute("message", "Changed LWM / HWM for '" + facilityName + "' from " + oldLWM + " / "
                + oldHWM + " to " + lwm + " / " + hwm);
        return "ok";
    } else {
        if (lwm == null) {
            model.addAttribute("message", "Invalid LWM timestamp");
        } else if (hwm == null) {
            model.addAttribute("message", "Invalid HWM timestamp");
        } else if (lwm.after(hwm)) {
            model.addAttribute("message", "Inconsistent timestamps: LWM > HWM");
        } else if (!hwm.before(now)) {
            model.addAttribute("message", "Inconsistent timestamps: HWM in the future");
        }
        return "failed";
    }
}

From source file:POP3Mail.java

public static final boolean printMessageInfo(BufferedReader reader, int id, PrintWriter printWriter)
        throws IOException {
    String from = "";
    String subject = "";
    String received = "";
    String to = "";
    String replyto = "";
    String date = "";
    String line = null;// ww w  .  j  av a2s  .  com
    Date d = null;
    Date dd = null;
    try {
        dd = dateformat.parse("01 Jan 2020 00:00:00");
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    while (true) {
        if (line == null) {
            line = reader.readLine();
        }
        if (line == null) {
            break;
        }
        String lower = line.toLowerCase(Locale.ENGLISH);
        System.out.println(line);
        if (lower.startsWith("from: ")) {
            from = line.substring(6).trim();
            line = null;
        } else if (lower.startsWith("reply-to: ")) {
            replyto = line.substring("reply-to: ".length()).trim();
            line = null;
        } else if (lower.startsWith("to: ")) {
            to = line.substring(3).trim();
            while ((line = reader.readLine()) != null) {
                lower = line.toLowerCase(Locale.ENGLISH);
                if (line.startsWith(" ")) {
                    to += line;
                } else {
                    break;
                }
            }

        } else if (lower.startsWith("subject: ")) {
            subject = line.substring(9).trim();
            line = null;
        } else if (lower.startsWith("date: ")) {
            date = line.substring("date: ".length()).trim();
            try {
                date = date.split(",")[1].trim();
                String[] tokens = date.split(" ");
                d = dateformat.parse(tokens[0] + " " + tokens[1] + " " + tokens[2] + " " + tokens[3]);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            line = null;
        } else {
            line = null;
        }
    }
    if (d != null && d.before(dd)) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", id);
        jsonObject.put("to", to);
        jsonObject.put("from", from);
        String[] t = parseTo(to);
        jsonObject.put("tolist", Arrays.asList(t));
        String ttt = "";
        for (String tt : t) {
            ttt += "," + tt;
        }
        String[] f = parseTo(from);
        String fff = "";
        for (String ff : f) {
            fff += "," + ff;
        }
        jsonObject.put("fromlist", Arrays.asList(f));
        jsonObject.put("subject", subject);
        jsonObject.put("date", date);
        jsonObject.put("time", d.getTime());
        jsonObject.put("reply-to", replyto);
        FileWriter fileWriter = new FileWriter(String.format("../json/%05d.json", id));
        jsonObject.write(fileWriter);
        fileWriter.close();
        printWriter.println(
                String.format("%d,'%s','%s','%s','%s','%s','%s','%s',%d", id, escape(from), fff.substring(1),
                        escape(to), ttt.substring(1), escape(replyto), escape(subject), date, d.getTime()));
        return true;

    }
    return false;
}

From source file:org.sakaiproject.signup.tool.jsf.organizer.action.EditMeeting.java

/**
 * setup the event/meeting's signup begin and deadline time and validate it
 * too//from w  w w.  j  a  v a  2  s.c o  m
 */
private void setSignupBeginDeadlineData(SignupMeeting meeting, int signupBegin, String signupBeginType,
        int signupDeadline, String signupDeadlineType) throws Exception {
    Date sBegin = Utilities.subTractTimeToDate(meeting.getStartTime(), signupBegin, signupBeginType);
    Date sDeadline = Utilities.subTractTimeToDate(meeting.getEndTime(), signupDeadline, signupDeadlineType);

    boolean origSignupStarted = originalMeetingCopy.getSignupBegins().before(new Date());// ????
    /* TODO have to pass it in?? */
    if (!START_NOW.equals(signupBeginType) && sBegin.before(new Date()) && !origSignupStarted) {
        // a warning for user
        Utilities.addErrorMessage(
                Utilities.rb.getString("warning.your.event.singup.begin.time.passed.today.time"));
    }

    if (!isSignupBeginModifiedByUser() && this.isStartNowTypeForRecurEvents) {
        /*do nothing and keep the original value since the Sign-up process is already started
         * No need to re-assign a new start_now value*/
    } else {
        meeting.setSignupBegins(sBegin);
    }

    if (sBegin.after(sDeadline))
        throw new SignupUserActionException(Utilities.rb.getString("signup.deadline.is.before.signup.begin"));

    meeting.setSignupDeadline(sDeadline);
}

From source file:gov.utah.dts.sdc.actions.BaseCommercialStudentAction.java

public String addMultiTrainingTime() throws Exception {
    int start = decodeTime(trainingStartTime);
    Date startDate = new Date(getTrainingDate().getTime() + start);

    int end = decodeTime(trainingEndTime);
    Date endDate = new Date(getTrainingDate().getTime() + end);

    if (endDate.before(startDate)) {
        addActionError("Start Time Must Be Before End Time");
    } else {/* ww  w .  j  ava  2 s . c  o m*/
        Map<String, Object> hm = new HashMap<String, Object>();
        hm.put("trainingStartTime", startDate);
        hm.put("trainingEndTime", endDate);
        hm.put("section", section);
        hm.put("vehicleFk", vehicleFk);
        hm.put("instructorFk", instructorFk);
        hm.put("classroomFk", classroomPk);
        hm.put("branchFk", branchFk);

        int result = 0;
        for (int i = 0; i < studentArray.size(); i++) {
            hm.put("studentFk", studentArray.get(i));
            if (getStudentService().insertTraining(hm) == 1) {
                result++;
            }
        }

        resultMsg = "These " + result + " students of " + getStudentList().size()
                + " available have been added to this training class.";
    }

    if (hasErrors()) {
        return INPUT;
    } else {
        return SUCCESS;
    }
}

From source file:gov.utah.dts.sdc.actions.BaseCommercialStudentAction.java

public String addMultiObservationTime() throws Exception {
    int start = decodeTime(observationStartTime);
    Date startDate = new Date(getObservationDate().getTime() + start);

    int end = decodeTime(observationEndTime);
    Date endDate = new Date(getObservationDate().getTime() + end);

    if (endDate.before(startDate)) {
        addActionError("Start Time Must Be Before End Time");
    } else {/*from   w  w  w .  j  av  a 2s.co m*/
        Map<String, Object> hm = new HashMap<String, Object>();
        hm.put("observationStartTime", startDate);
        hm.put("observationEndTime", endDate);
        hm.put("vehicleFk", vehicleFk);
        hm.put("instructorFk", instructorFk);
        hm.put("classroomFk", classroomPk);
        hm.put("branchFk", branchFk);

        int result = 0;
        for (int x = 0; x < studentArray.size(); x++) {
            hm.put("studentFk", studentArray.get(x));
            if (getStudentService().insertObservation(hm) == 1) {
                result++;
            }
        }

        resultMsg = "These " + result + " students of " + getStudentList().size()
                + " available have been added to this observation class.";
    }

    if (hasErrors()) {
        return INPUT;
    } else {
        return SUCCESS;
    }
}

From source file:com.ssbusy.controller.checkout.CheckoutController.java

private String saveSingleShip0(HttpServletRequest request, HttpServletResponse response, Model model,
        OrderInfoForm orderInfoForm, MyBillingInfoForm billingForm, MyShippingInfoForm shippingForm,
        BindingResult result, boolean ajax)
        throws PricingException, ServiceException, CheckoutException, ParseException {
    MyCustomer myCustomer = (MyCustomer) CustomerState.getCustomer();
    Region region = myCustomer.getRegion();
    Boolean w_flag = (Boolean) request.getSession().getAttribute("w_flag");
    if (region == null) {
        if (w_flag != null && w_flag) {
            return "redirect:/weixin/region";
        } else//from  w ww  .jav  a 2  s  .co m
            return REDIRECT_REGION_SELECT;
    }

    MyAddress myAddress = processShippingForm(shippingForm, result);
    if (result.hasErrors()) {
        putFulfillmentOptionsAndEstimationOnModel(model);
        populateModelWithShippingReferenceData(request, model);
        model.addAttribute("states", stateService.findStates());
        model.addAttribute("countries", countryService.findCountries());
        model.addAttribute("expirationMonths", populateExpirationMonths());
        model.addAttribute("expirationYears", populateExpirationYears());
        model.addAttribute("validShipping", false);
        if (w_flag != null && w_flag) {
            return "weixin/cart/w_checkout";
        } else
            return checkoutAddress;
    }

    billingForm.setPaymentMethod(shippingForm.getPaymentMethod());
    billingForm.setBp_pay(shippingForm.getBp_pay());
    billingForm.setAlipay(shippingForm.getAlipay());
    if (shippingForm.getBp_pay() == null || shippingForm.getBp_pay().doubleValue() < 0)
        billingForm.setBp_pay(BigDecimal.ZERO);
    if (shippingForm.getAlipay() == null || shippingForm.getAlipay().doubleValue() < 0)
        billingForm.setAlipay(BigDecimal.ZERO);
    billingForm.setMyAddress(myAddress);
    prepopulateCheckoutForms(CartState.getCart(), orderInfoForm, null, billingForm);

    String assign = request.getParameter("assign");
    MyOrder cart = (MyOrder) CartState.getCart();

    Date dStart = null, dEnd = null;
    Date nowDay = Calendar.getInstance().getTime();
    if (nowDay.after(myDate1) && nowDay.before(myDate2)) {
        dStart = myDate1;
        dEnd = myDate2;
    } else if (nowDay.after(myDate2) && nowDay.before(myDate3)) {
        dStart = myDate2;
        dEnd = myDate3;
    } else if (nowDay.after(myDate3) && nowDay.before(myDate4)) {
        dStart = myDate3;
        dEnd = myDate4;
    }
    if (dStart != null) {
        List<Order> orders = myorderService.getAllSubmittedInTime(myCustomer.getId(), dStart, dEnd);
        boolean contain = ifCanAdd(orders);
        if (contain) {
            if (w_flag != null && w_flag) {
                return "redirect:/weixin/checkout";
            } else
                return "redirect:/checkout/checkout-step-2?error=%E4%B8%8D%E8%A6%81%E5%A4%AA%E8%B4%AA%E5%BF%83%EF%BC%8C%E5%8F%AA%E8%83%BD%E6%8A%A21%E6%AC%A1%E5%93%A6";
        }
    }

    String a1;
    Date a2;
    if ("2".equals(assign)) {
        String date = request.getParameter("date");
        String detaildate = request.getParameter("detaildate");
        int deta = 0;
        try {
            deta = Integer.parseInt(detaildate);
        } catch (Exception e) {
            // ignore
        }

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, deta);
        if ("1".equals(date)) {
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
        } else if ("2".equals(date)) {
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 2);
        }
        SimpleDateFormat dateformat1 = new SimpleDateFormat("HH:mm");
        a2 = calendar.getTime();
        a1 = dateformat1.format(a2);
    } else {
        SimpleDateFormat dateformat1 = new SimpleDateFormat("HH:mm");
        a2 = new Date();
        a1 = dateformat1.format(a2);
    }
    cart.setDelieverDate(a2);

    FulfillmentGroup fulfillmentGroup = cart.getFulfillmentGroups().get(0);

    fulfillmentGroup.setAddress(shippingForm.getMyAddress());
    fulfillmentGroup.setPersonalMessage(shippingForm.getPersonalMessage());
    fulfillmentGroup.setDeliveryInstruction(shippingForm.getDeliveryMessage());

    cart = (MyOrder) orderService.save(cart, true);
    CartState.setCart(cart);
    CustomerAddress defaultAddress = customerAddressService
            .findDefaultCustomerAddress(CustomerState.getCustomer().getId());
    if (defaultAddress == null) {
        MyAddress address = (MyAddress) addressService.saveAddress(shippingForm.getMyAddress());
        CustomerAddress customerAddress = customerAddressService.create();
        customerAddress.setAddress(address);
        customerAddress.setCustomer(CustomerState.getCustomer());
        customerAddress = customerAddressService.saveCustomerAddress(customerAddress);
        customerAddressService.makeCustomerAddressDefault(customerAddress.getId(),
                customerAddress.getCustomer().getId());
    }

    // ????
    if (false) {// if("no".equals(request.getParameter("forcedSubmit"))){
        String[] times = region.getShipping_time().split(";");
        boolean isOutDeliveryDateRange = true;
        for (String time : times) {
            String[] shipping_time = time.split("-");
            if ((a1.compareTo(shipping_time[0]) > 0) && (a1.compareTo(shipping_time[1]) < 0))
                isOutDeliveryDateRange = false;
        }
        if (isOutDeliveryDateRange) {
            return "redirect:/checkout/checkout-step-2?flag=1";
        }
    }

    try {
        if ("alipay_pay".equals(billingForm.getPaymentMethod())) {
            String description = "";
            for (OrderItem ot : cart.getOrderItems()) {
                description = description + ot.getName() + "";
                if (description.length() > 50) {
                    description = description + "....";
                    break;
                }
            }
            // TODO ?location
            FulfillmentLocation loc = null;
            List<FulfillmentGroup> fgroups = cart.getFulfillmentGroups();
            if (fgroups == null || fgroups.size() == 0) {
                Customer customer = CustomerState.getCustomer();
                if (customer instanceof MyCustomer)
                    loc = ((MyCustomer) customer).getRegion().getFulfillmentLocations().get(0);
            } else {
                Address addr = fgroups.get(0).getAddress();
                if (addr instanceof MyAddress) {
                    loc = ((MyAddress) addr).getDormitory().getAreaAddress().getRegion()
                            .getFulfillmentLocations().get(0);
                }
            }
            // TODO path??alipay
            String path = "/alipay/direct_pay?tradeNo="
                    + (new SimpleDateFormat("yyyyMMddHHmm").format(SystemTime.asDate()) + cart.getId())
                    + "&subject= " + (loc == null ? "" : loc.getId())
                    + (new Date().getTime() % 1000000) + cart.getId() + " ??&description=" + description
                    + "&tradeUrl=http://www.onxiao.com/customer/orders";
            if (billingForm.getAlipay().compareTo(cart.getTotal().getAmount()) >= 0) {
                // ?
                path = path + "&totalFee=" + cart.getTotal();
                return "forward:" + path;

            } else {
                if (billingForm.getAlipay().doubleValue() == 0) {
                    return completeCodCheckout(request, response, model, billingForm, result);
                } else {
                    // ?
                    path = path + "&totalFee=" + billingForm.getAlipay();
                    return "forward:" + path;
                }
            }
        } else if ("balance_pay".equals(billingForm.getPaymentMethod())) {
            if (billingForm.getBp_pay().compareTo(cart.getTotal().getAmount()) >= 0) {
                return completeBpCheckout(request, response, model, billingForm, result);
            } else {
                if (billingForm.getAlipay().doubleValue() <= 0) {
                    return completeCodCheckout(request, response, model, billingForm, result);
                } else {
                    return complexCheckout(request, response, model, billingForm, result,
                            MyPaymentInfoType.Payment_Bp, cart.getId());
                }
            }

        } else if ("integral_pay".equals(billingForm.getPaymentMethod())) {
            return completeIntegrlCheckout(request, response, model, billingForm, result);
        } else {
            return completeCodCheckout(request, response, model, billingForm, result);
        }
    } catch (CheckoutException e) {
        if (ajax)
            throw e;
        if (e.getCause() instanceof InventoryUnavailableException) {
            try {
                if (w_flag != null && w_flag) {
                    return "redirect:/weixin/checkout";
                } else
                    return "redirect:/checkout/checkout-step-2?inventoryError=1&errorMessage=" + URLEncoder
                            .encode(((InventoryUnavailableException) e.getCause()).getMessage(), "utf-8");
            } catch (UnsupportedEncodingException e1) {
                if (w_flag != null && w_flag) {
                    return "redirect:/weixin/checkout";
                } else
                    return "redirect:/checkout/checkout-step-2?inventoryError=1&errorMessage="
                            + ((InventoryUnavailableException) e.getCause()).getMessage();
            }
        } else if (e.getCause() instanceof InsufficientFundsException) {
            if (w_flag != null && w_flag) {
                return "redirect:/weixin/checkout";
            } else
                return "redirect:/checkout/checkout-step-2?error=%E7%A7%AF%E5%88%86%E6%88%96%E8%80%85%E4%BD%99%E9%A2%9D%E4%B8%8D%E8%B6%B3";
        } else {
            throw e;
        }
    }
}

From source file:de.forsthaus.webui.calendar.CalendarCreateEventCtrl.java

/**
 * Saves the data of an CalendarEvent and closes the window.
 * /*  w w w. ja  va 2  s  .  co  m*/
 * @param event
 */
public void doSave(Event event) {
    Calendars cals = getCalendarCtrl().getCal();

    MySimpleCalendarEvent ce = new MySimpleCalendarEvent();
    Calendar cal = Calendar.getInstance(cals.getDefaultTimeZone());
    Date beginDate = ppbegin.getValue();
    Date endDate = ppend.getValue();

    beginDate.setSeconds(0);
    endDate.setSeconds(0);
    if (!ppallDay.isChecked()) {
        String[] times = ppbt.getSelectedItem().getLabel().split(":");

        cal.setTime(beginDate);
        cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(times[0]));
        cal.set(Calendar.MINUTE, Integer.parseInt(times[1]));
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        beginDate = cal.getTime();
        times = ppet.getSelectedItem().getLabel().split(":");
        cal.setTime(endDate);
        cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(times[0]));
        cal.set(Calendar.MINUTE, Integer.parseInt(times[1]));
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        endDate = cal.getTime();
    }

    if (!beginDate.before(endDate)) {
        alert("The end date cannot be before/equal than begin date!");
        return;
    }

    String[] colors = ((String) ppcolor.getSelectedItem().getValue()).split(",");
    ce.setHeaderColor(colors[0]);
    ce.setContentColor(colors[1]);
    ce.setBeginDate(beginDate);
    ce.setEndDate(endDate);
    ce.setTitle(txtb_title.getValue());
    ce.setContent(ppcnt.getValue());
    ce.setLocked(pplocked.isChecked());
    getCalendarCtrl().getCalModel().add(ce);

    ppcnt.setRawValue("");
    ppbt.setSelectedIndex(0);
    ppet.setSelectedIndex(0);

    final SecUser user = ((UserImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal())
            .getSecUser();

    // prepare the backend Bean
    MyCalendarEvent calEvt = getCalendarEventService().getNewCalendarEvent();
    calEvt.setSecUser(user);
    calEvt.setTitle(ce.getTitle());
    calEvt.setContent(ce.getContent());
    calEvt.setBeginDate(ce.getBeginDate());
    calEvt.setEndDate(ce.getEndDate());
    calEvt.setHeaderColor(colors[0]);
    calEvt.setContentColor(ce.getContentColor());

    // Save the calendar event to database
    try {
        getCalendarEventService().saveOrUpdate(calEvt);
        syncModel();
    } catch (Exception e) {
        e.printStackTrace();
    }

    createEventWindow.onClose();

}

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

@Test
public void getSpecificitySearchesRemotely() throws Exception {
    Mockito.doReturn(this.features).when(this.patient).getFeatures();
    URI expectedURI = new URI("https://monarchinitiative.org/score");
    CapturingMatcher<HttpPost> reqCapture = new CapturingMatcher<>();
    when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
    when(this.response.getEntity()).thenReturn(this.responseEntity);
    when(this.responseEntity.getContent())
            .thenReturn(IOUtils.toInputStream("{\"scaled_score\":2}", StandardCharsets.UTF_8));
    CapturingMatcher<PatientSpecificity> specCapture = new CapturingMatcher<>();
    Mockito.doNothing().when(this.cache).set(Matchers.eq("HP:1-HP:2"), Matchers.argThat(specCapture));
    Date d1 = new Date();
    this.mocker.getComponentUnderTest().getSpecificity(this.patient);
    Date d2 = new Date();
    PatientSpecificity spec = specCapture.getLastValue();
    Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
    String content = URLDecoder
            .decode(IOUtils.toString(reqCapture.getLastValue().getEntity().getContent(), "UTF-8"), "UTF-8");
    Assert.assertTrue(content.startsWith("annotation_profile="));
    JSONObject actualJson = new JSONObject(content.substring("annotation_profile=".length()));
    JSONObject expectedJson = new JSONObject(
            "{\"features\":[{\"id\":\"HP:1\"},{\"id\":\"HP:2\",\"isPresent\":false}]}");
    Assert.assertTrue(expectedJson.similar(actualJson));
    Assert.assertEquals("application/x-www-form-urlencoded; charset=UTF-8",
            reqCapture.getLastValue().getEntity().getContentType().getValue());
    Assert.assertEquals(2.0, spec.getScore(), 0.0);
    Assert.assertEquals("monarchinitiative.org", spec.getComputingMethod());
    Assert.assertFalse(d1.after(spec.getComputationDate()));
    Assert.assertFalse(d2.before(spec.getComputationDate()));
}

From source file:com.db4o.sync4o.SyncDb.java

private List findKeysBetween(final SyncClass syncClass, final char state, final Date start, final Date finish) {

    Query query = _shadowDb.query();
    query.constrain(SyncObjectInfo.class);
    query.constrain(new Evaluation() {

        public void evaluate(Candidate c) {

            boolean matches = false;
            SyncObjectInfo info = (SyncObjectInfo) c.getObject();
            if (syncClass.getConfig().equals(info.getClassInfo().getConfig()) && info.getSyncState() == state) {

                Date timestamp = info.getTimestamp();
                matches = ((start == null) || start.before(timestamp))
                        && ((finish == null) || finish.after(timestamp));

            }/* w w  w .  j a  va2 s.c o  m*/

            c.include(matches);

        }

    });

    return query.execute();

}